diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e153148eeda001e2d24873ea1471bc441c65bd68
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aimv2/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aimv2/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..df767312bf9bedc9b19397d3dd6ba67ea69efdc5
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aimv2/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aimv2/__pycache__/configuration_aimv2.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aimv2/__pycache__/configuration_aimv2.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d8063ca6427fbf69f736dac7714b4cb72d1f83a0
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aimv2/__pycache__/configuration_aimv2.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aimv2/__pycache__/modeling_aimv2.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aimv2/__pycache__/modeling_aimv2.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..395723eaabdb6ce84e77a265794831d62c49147d
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aimv2/__pycache__/modeling_aimv2.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aimv2/__pycache__/modular_aimv2.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aimv2/__pycache__/modular_aimv2.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..29cc00547c2d3a26c3f2d863b9ca7414ca9dac53
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aimv2/__pycache__/modular_aimv2.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/align/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/align/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..aa0651d521b89c4ba8bbeb2ac7a28e8914b0d2e4
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/align/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/align/__pycache__/configuration_align.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/align/__pycache__/configuration_align.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c1d2f596804e1352ba91729c7600436ec3df70c0
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/align/__pycache__/configuration_align.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/align/__pycache__/modeling_align.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/align/__pycache__/modeling_align.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..05aa1d65aa92d4322882245a2705ebe25a5df6ce
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/align/__pycache__/modeling_align.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/align/__pycache__/processing_align.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/align/__pycache__/processing_align.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9d4cf162dd245cac934842f683826f55738edabb
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/align/__pycache__/processing_align.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/apertus/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/apertus/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..adf2f5b8b0242675f94ac613de9ca88548b5cdfa
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/apertus/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/apertus/__pycache__/configuration_apertus.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/apertus/__pycache__/configuration_apertus.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e3bb20069245f8a53495a41c8272a81fe578d431
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/apertus/__pycache__/configuration_apertus.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/apertus/__pycache__/modeling_apertus.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/apertus/__pycache__/modeling_apertus.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2d2066e476b3091ac319cea21fdc7f04482a9824
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/apertus/__pycache__/modeling_apertus.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/apertus/__pycache__/modular_apertus.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/apertus/__pycache__/modular_apertus.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8fac5b4e82d9a5c7ebc18d00a4d998b084452780
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/apertus/__pycache__/modular_apertus.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d85e5c9e73b94da8afabb44a8d0f17c096d5e97c
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/__init__.py
@@ -0,0 +1,31 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_aria import *
+ from .image_processing_aria import *
+ from .image_processing_pil_aria import *
+ from .modeling_aria import *
+ from .processing_aria import *
+
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d285dc9f0ce8b47e55bc19ab899d7c518ffe1f4c
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/__pycache__/configuration_aria.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/__pycache__/configuration_aria.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fd88e459f342ca3f97ee7c95b149b5e103d3c893
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/__pycache__/configuration_aria.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/__pycache__/image_processing_aria.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/__pycache__/image_processing_aria.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..eaa19a09fc326ccfa1b75d5852bdbc9270a84bcb
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/__pycache__/image_processing_aria.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/__pycache__/image_processing_pil_aria.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/__pycache__/image_processing_pil_aria.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7795cd9c87a72eda9dfdbe0e90c5b830c316b8df
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/__pycache__/image_processing_pil_aria.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/__pycache__/modeling_aria.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/__pycache__/modeling_aria.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f6dd0afd5b001be60e30651436a4737d2f03d1a7
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/__pycache__/modeling_aria.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/__pycache__/modular_aria.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/__pycache__/modular_aria.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..074e7ea2c84d60753451b648e524bfbdfa231858
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/__pycache__/modular_aria.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/__pycache__/processing_aria.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/__pycache__/processing_aria.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bd269173de098071d550df5a57d156a89b2e736e
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/__pycache__/processing_aria.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/configuration_aria.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/configuration_aria.py
new file mode 100644
index 0000000000000000000000000000000000000000..7694656905dd7d20403f98b6c74ff875417716e3
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/configuration_aria.py
@@ -0,0 +1,149 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/aria/modular_aria.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_aria.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2024 The Rhymes-AI Teams Authors and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...modeling_rope_utils import RopeParameters
+from ...utils import auto_docstring
+from ...utils.type_validators import interval
+from ..auto import CONFIG_MAPPING, AutoConfig
+
+
+@auto_docstring(checkpoint="rhymes-ai/Aria")
+@strict
+class AriaTextConfig(PreTrainedConfig):
+ r"""
+ moe_num_experts (`int`, *optional*, defaults to 8):
+ The number of experts in the MoE layer.
+ moe_topk (`int`, *optional*, defaults to 2):
+ The number of top experts to route to for each token.
+ moe_num_shared_experts (`int`, *optional*, defaults to 2):
+ The number of shared experts.
+ """
+
+ model_type = "aria_text"
+ keys_to_ignore_at_inference = ["past_key_values"]
+ base_model_tp_plan = {
+ "layers.*.self_attn.q_proj": "colwise",
+ "layers.*.self_attn.k_proj": "colwise",
+ "layers.*.self_attn.v_proj": "colwise",
+ "layers.*.self_attn.o_proj": "rowwise",
+ "layers.*.mlp.shared_experts.gate_proj": "colwise",
+ "layers.*.mlp.shared_experts.up_proj": "colwise",
+ "layers.*.mlp.shared_experts.down_proj": "rowwise",
+ }
+ base_model_pp_plan = {
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
+ "norm": (["hidden_states"], ["hidden_states"]),
+ }
+
+ vocab_size: int = 32000
+ hidden_size: int = 4096
+
+ intermediate_size: int = 4096
+ num_hidden_layers: int = 32
+ num_attention_heads: int = 32
+ num_key_value_heads: int | None = None
+ hidden_act: str = "silu"
+ max_position_embeddings: int = 2048
+ initializer_range: float = interval(min=0.0, max=1.0)(default=0.02)
+ rms_norm_eps: float = 1e-6
+ use_cache: bool = True
+ pad_token_id: int | None = 2
+ bos_token_id: int | None = 1
+ eos_token_id: int | list[int] | None = 2
+ pretraining_tp: int | None = 1
+ tie_word_embeddings: bool = False
+ rope_parameters: RopeParameters | dict | None = None
+ attention_bias: bool = False
+ attention_dropout: int | float | None = 0.0
+ mlp_bias: bool = False
+ head_dim: int | None = None
+ base_config_key = "text_config"
+ moe_num_experts: int = 8
+ moe_topk: int = 2
+ moe_num_shared_experts: int = 2
+
+ def __post_init__(self, **kwargs):
+ if self.head_dim is None:
+ self.head_dim = self.hidden_size // self.num_attention_heads
+ if self.num_key_value_heads is None:
+ self.num_key_value_heads = self.num_attention_heads
+
+ super().__post_init__(**kwargs)
+
+ def validate_architecture(self):
+ """Part of `@strict`-powered validation. Validates the architecture of the config."""
+ if self.hidden_size % self.num_attention_heads != 0:
+ raise ValueError(
+ f"The hidden size ({self.hidden_size}) is not a multiple of the number of attention "
+ f"heads ({self.num_attention_heads})."
+ )
+
+
+@auto_docstring(checkpoint="rhymes-ai/Aria")
+@strict
+class AriaConfig(PreTrainedConfig):
+ r"""
+ projector_patch_to_query_dict (`dict`, *optional*):
+ Mapping of patch sizes to query dimensions.
+ """
+
+ model_type = "aria"
+ attribute_map = {
+ "image_token_id": "image_token_index",
+ }
+ sub_configs = {"text_config": AriaTextConfig, "vision_config": AutoConfig}
+
+ vision_config: dict | PreTrainedConfig | None = None
+ text_config: dict | AriaTextConfig | None = None
+ vision_feature_layer: int | list[int] = -1
+ projector_patch_to_query_dict: dict | None = None
+ image_token_index: int = 9
+ initializer_range: float = 0.02
+ tie_word_embeddings: bool = False
+
+ def __post_init__(self, **kwargs):
+ # Convert the keys and values of projector_patch_to_query_dict to integers
+ # This ensures consistency even if they were provided as strings
+ if self.projector_patch_to_query_dict is None:
+ self.projector_patch_to_query_dict = {
+ 1225: 128,
+ 4900: 256,
+ }
+ self.projector_patch_to_query_dict = {int(k): int(v) for k, v in self.projector_patch_to_query_dict.items()}
+ self.max_value_projector_patch_to_query_dict = max(self.projector_patch_to_query_dict.values())
+
+ if isinstance(self.vision_config, dict):
+ self.vision_config["model_type"] = "idefics3_vision"
+ self.vision_config = CONFIG_MAPPING[self.vision_config["model_type"]](**self.vision_config)
+ elif self.vision_config is None:
+ self.vision_config = CONFIG_MAPPING["idefics3_vision"]()
+
+ if isinstance(self.text_config, dict) and "model_type" in self.text_config:
+ self.text_config = AriaTextConfig(**self.text_config)
+ elif self.text_config is None:
+ self.text_config = AriaTextConfig()
+
+ super().__post_init__(**kwargs)
+
+
+__all__ = ["AriaConfig", "AriaTextConfig"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/image_processing_aria.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/image_processing_aria.py
new file mode 100644
index 0000000000000000000000000000000000000000..e0abc55236f0499d63e5c774fec363bba893efe7
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/image_processing_aria.py
@@ -0,0 +1,226 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/aria/modular_aria.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_aria.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2024 The Rhymes-AI Teams Authors and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import torch
+from torchvision.transforms.v2 import functional as tvF
+
+from ...image_processing_backends import TorchvisionBackend
+from ...image_processing_utils import BatchFeature, get_patch_output_size, select_best_resolution
+from ...image_transforms import divide_to_patches
+from ...image_utils import ChannelDimension, PILImageResampling, SizeDict, get_image_size
+from ...processing_utils import ImagesKwargs, Unpack
+from ...utils import TensorType, auto_docstring
+
+
+class AriaImageProcessorKwargs(ImagesKwargs, total=False):
+ r"""
+ max_image_size (`int`, *optional*, defaults to `self.max_image_size`):
+ Maximum image size. Must be either 490 or 980.
+ min_image_size (`int`, *optional*, defaults to `self.min_image_size`):
+ Minimum image size. Images smaller than this in any dimension will be scaled up.
+ split_resolutions (`list[list[int]]`, *optional*, defaults to `self.split_resolutions`):
+ A list of possible resolutions as (height, width) pairs for splitting high-resolution images into patches.
+ split_image (`bool`, *optional*, defaults to `self.split_image`):
+ Whether to split the image into patches using the best matching resolution from `split_resolutions`.
+ """
+
+ max_image_size: int
+ min_image_size: int
+ split_resolutions: list[list[int]]
+ split_image: bool
+
+
+@auto_docstring
+class AriaImageProcessor(TorchvisionBackend):
+ model_input_names = ["pixel_values", "pixel_mask", "num_crops"]
+ valid_kwargs = AriaImageProcessorKwargs
+
+ resample = PILImageResampling.BICUBIC
+ image_mean = [0.5, 0.5, 0.5]
+ image_std = [0.5, 0.5, 0.5]
+ max_image_size = 980
+ min_image_size = 336
+ split_image = False
+ split_resolutions = None
+ do_convert_rgb = True
+ do_rescale = True
+ do_normalize = True
+
+ def __init__(self, **kwargs: Unpack[AriaImageProcessorKwargs]):
+ if kwargs.get("split_resolutions") is None:
+ default_resolutions = [(1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (2, 4), (2, 3), (2, 2), (2, 1), (3, 1), (3, 2), (4, 1), (4, 2), (5, 1), (6, 1), (7, 1), (8, 1)] # fmt: skip
+ kwargs["split_resolutions"] = [[el[0] * 490, el[1] * 490] for el in default_resolutions]
+ super().__init__(**kwargs)
+
+ def _get_padding_size(self, original_resolution: tuple, target_resolution: tuple) -> list[int]:
+ """Get padding size for patching, returns [left, top, right, bottom] for tvF.pad."""
+ original_height, original_width = original_resolution
+ target_height, target_width = target_resolution
+ paste_x, r_x = divmod(target_width - original_width, 2)
+ paste_y, r_y = divmod(target_height - original_height, 2)
+ return [paste_x, paste_y, paste_x + r_x, paste_y + r_y]
+
+ def _resize_for_patching(
+ self,
+ image: "torch.Tensor",
+ target_resolution: tuple,
+ resample: "PILImageResampling | tvF.InterpolationMode | int | None",
+ ) -> "torch.Tensor":
+ """Resize an image to a target resolution while maintaining aspect ratio."""
+ new_height, new_width = get_patch_output_size(
+ image, target_resolution, input_data_format=ChannelDimension.FIRST
+ )
+ return self.resize(image, SizeDict(height=new_height, width=new_width), resample)
+
+ def _pad_for_patching(
+ self,
+ image: "torch.Tensor",
+ target_resolution: tuple,
+ ) -> "torch.Tensor":
+ """Pad an image to a target resolution while maintaining aspect ratio."""
+ new_resolution = get_patch_output_size(image, target_resolution, input_data_format=ChannelDimension.FIRST)
+ padding = self._get_padding_size(new_resolution, target_resolution)
+ return tvF.pad(image, padding=padding)
+
+ def get_image_patches(
+ self,
+ image: "torch.Tensor",
+ grid_pinpoints: list[list[int]],
+ patch_size: int,
+ resample: "PILImageResampling | tvF.InterpolationMode | int | None",
+ ) -> list["torch.Tensor"]:
+ """
+ Process an image with variable resolutions by dividing it into patches.
+
+ Args:
+ image (`torch.Tensor`):
+ The input image to be processed (channels-first format).
+ grid_pinpoints (`list[list[int]]`):
+ A list of possible resolutions as (height, width) pairs.
+ patch_size (`int`):
+ Size of each square patch to divide the image into.
+ resample (`PILImageResampling | tvF.InterpolationMode | int | None`):
+ Resampling filter to use when resizing.
+
+ Returns:
+ `list[torch.Tensor]`: A list of image patches in channels-first format.
+ """
+ if not isinstance(grid_pinpoints, list):
+ raise TypeError("grid_pinpoints must be a list of possible resolutions.")
+
+ image_size = get_image_size(image, channel_dim=ChannelDimension.FIRST)
+ best_resolution = select_best_resolution(image_size, grid_pinpoints)
+ resized_image = self._resize_for_patching(image, best_resolution, resample)
+ padded_image = self._pad_for_patching(resized_image, best_resolution)
+ patches = divide_to_patches(padded_image, patch_size=patch_size)
+ return patches
+
+ def _preprocess(
+ self,
+ images: list["torch.Tensor"],
+ do_rescale: bool,
+ rescale_factor: float,
+ do_normalize: bool,
+ image_mean: float | list[float] | None,
+ image_std: float | list[float] | None,
+ disable_grouping: bool | None,
+ return_tensors: str | TensorType | None,
+ max_image_size: int = 980,
+ min_image_size: int = 336,
+ split_resolutions: list[list[int]] | None = None,
+ split_image: bool = False,
+ resample: "PILImageResampling | tvF.InterpolationMode | int | None" = None,
+ **kwargs,
+ ) -> BatchFeature:
+ if max_image_size not in [490, 980]:
+ raise ValueError("max_image_size must be either 490 or 980")
+
+ pixel_masks = []
+ processed_crops = []
+ num_crops = None
+
+ for image in images:
+ if split_image:
+ crop_images = self.get_image_patches(image, split_resolutions, max_image_size, resample)
+ else:
+ crop_images = [image]
+
+ if num_crops is None or len(crop_images) > num_crops:
+ num_crops = len(crop_images)
+
+ for crop_image in crop_images:
+ h, w = crop_image.shape[-2], crop_image.shape[-1]
+ scale = max_image_size / max(h, w)
+ if w >= h:
+ new_h = max(int(h * scale), min_image_size)
+ new_w = max_image_size
+ else:
+ new_h = max_image_size
+ new_w = max(int(w * scale), min_image_size)
+
+ crop_image = self.resize(crop_image, SizeDict(height=new_h, width=new_w), resample)
+
+ padding_bottom = max_image_size - new_h
+ padding_right = max_image_size - new_w
+ crop_image = tvF.pad(crop_image, [0, 0, padding_right, padding_bottom])
+
+ pixel_mask = torch.zeros((max_image_size, max_image_size), dtype=torch.bool)
+ pixel_mask[:new_h, :new_w] = True
+ pixel_masks.append(pixel_mask)
+ processed_crops.append(crop_image)
+
+ stacked_images = torch.stack(processed_crops, dim=0)
+ stacked_images = self.rescale_and_normalize(
+ stacked_images, do_rescale, rescale_factor, do_normalize, image_mean, image_std
+ )
+ stacked_masks = torch.stack(pixel_masks, dim=0)
+
+ return BatchFeature(
+ data={
+ "pixel_values": stacked_images,
+ "pixel_mask": stacked_masks,
+ "num_crops": num_crops,
+ },
+ tensor_type=return_tensors,
+ )
+
+ def get_number_of_image_patches(self, height: int, width: int, images_kwargs=None):
+ """
+ A utility that returns number of image patches for a given image size.
+
+ Args:
+ height (`int`):
+ Height of the input image.
+ width (`int`):
+ Width of the input image.
+ images_kwargs (`dict`, *optional*):
+ Any kwargs to override defaults of the image processor.
+
+ Returns:
+ `int`: Number of patches per image.
+ """
+ split_image = images_kwargs.get("split_image", self.split_image)
+ max_image_size = images_kwargs.get("max_image_size", self.max_image_size)
+
+ resized_height, resized_width = select_best_resolution((height, width), self.split_resolutions)
+ num_patches = 1 if not split_image else resized_height // max_image_size * resized_width // max_image_size
+ return num_patches
+
+
+__all__ = ["AriaImageProcessor"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/image_processing_pil_aria.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/image_processing_pil_aria.py
new file mode 100644
index 0000000000000000000000000000000000000000..cd7233e9648c4091d1ce2f8242b488bae0062c7e
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/image_processing_pil_aria.py
@@ -0,0 +1,230 @@
+# Copyright 2024 The Rhymes-AI Teams Authors and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Image processor class for Aria."""
+
+import numpy as np
+
+from ...image_processing_backends import PilBackend
+from ...image_processing_utils import BatchFeature, get_patch_output_size, select_best_resolution
+from ...image_transforms import divide_to_patches
+from ...image_utils import (
+ ChannelDimension,
+ PILImageResampling,
+ SizeDict,
+ get_image_size,
+)
+from ...processing_utils import ImagesKwargs, Unpack
+from ...utils import TensorType, auto_docstring
+
+
+# Adapted from transformers.models.aria.image_processing_aria.AriaImageProcessorKwargs
+class AriaImageProcessorKwargs(ImagesKwargs, total=False):
+ r"""
+ max_image_size (`int`, *optional*, defaults to `self.max_image_size`):
+ Maximum image size. Must be either 490 or 980.
+ min_image_size (`int`, *optional*, defaults to `self.min_image_size`):
+ Minimum image size. Images smaller than this in any dimension will be scaled up.
+ split_resolutions (`list[list[int]]`, *optional*, defaults to `self.split_resolutions`):
+ A list of possible resolutions as (height, width) pairs for splitting high-resolution images into patches.
+ split_image (`bool`, *optional*, defaults to `self.split_image`):
+ Whether to split the image into patches using the best matching resolution from `split_resolutions`.
+ """
+
+ max_image_size: int
+ min_image_size: int
+ split_resolutions: list[list[int]]
+ split_image: bool
+
+
+@auto_docstring
+class AriaImageProcessorPil(PilBackend):
+ model_input_names = ["pixel_values", "pixel_mask", "num_crops"]
+ valid_kwargs = AriaImageProcessorKwargs
+
+ resample = PILImageResampling.BICUBIC
+ image_mean = [0.5, 0.5, 0.5]
+ image_std = [0.5, 0.5, 0.5]
+ max_image_size = 980
+ min_image_size = 336
+ split_image = False
+ split_resolutions = None
+ do_convert_rgb = True
+ do_rescale = True
+ do_normalize = True
+
+ def __init__(self, **kwargs: Unpack[AriaImageProcessorKwargs]):
+ if kwargs.get("split_resolutions") is None:
+ default_resolutions = [(1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (2, 4), (2, 3), (2, 2), (2, 1), (3, 1), (3, 2), (4, 1), (4, 2), (5, 1), (6, 1), (7, 1), (8, 1)] # fmt: skip
+ kwargs["split_resolutions"] = [[el[0] * 490, el[1] * 490] for el in default_resolutions]
+ super().__init__(**kwargs)
+
+ def _get_padding_size(self, original_resolution: tuple, target_resolution: tuple):
+ """Get padding size for patching, returns ((before_h, after_h), (before_w, after_w)) for np.pad."""
+ original_height, original_width = original_resolution
+ target_height, target_width = target_resolution
+ paste_x, r_x = divmod(target_width - original_width, 2)
+ paste_y, r_y = divmod(target_height - original_height, 2)
+ return (paste_y, paste_y + r_y), (paste_x, paste_x + r_x)
+
+ def _resize_for_patching(
+ self,
+ image: np.ndarray,
+ target_resolution: tuple,
+ resample: "PILImageResampling | None",
+ ) -> np.ndarray:
+ """Resize an image to a target resolution while maintaining aspect ratio."""
+ new_height, new_width = get_patch_output_size(
+ image, target_resolution, input_data_format=ChannelDimension.FIRST
+ )
+ return self.resize(image, SizeDict(height=new_height, width=new_width), resample)
+
+ def _pad_for_patching(
+ self,
+ image: np.ndarray,
+ target_resolution: tuple,
+ ) -> np.ndarray:
+ """Pad an image to a target resolution while maintaining aspect ratio."""
+ new_resolution = get_patch_output_size(image, target_resolution, input_data_format=ChannelDimension.FIRST)
+ padding_hw = self._get_padding_size(new_resolution, target_resolution)
+ # CHW format: pad channel dim with zeros, then height/width
+ padding = ((0, 0), padding_hw[0], padding_hw[1])
+ return np.pad(image, padding, mode="constant", constant_values=0)
+
+ def get_image_patches(
+ self,
+ image: np.ndarray,
+ grid_pinpoints: list[list[int]],
+ patch_size: int,
+ resample: "PILImageResampling | None",
+ ) -> list[np.ndarray]:
+ """
+ Process an image with variable resolutions by dividing it into patches.
+
+ Args:
+ image (`np.ndarray`):
+ The input image to be processed (channels-first format).
+ grid_pinpoints (`list[list[int]]`):
+ A list of possible resolutions as (height, width) pairs.
+ patch_size (`int`):
+ Size of each square patch to divide the image into.
+ resample (`PILImageResampling | int | None`):
+ Resampling filter to use when resizing.
+
+ Returns:
+ `list[np.ndarray]`: A list of image patches in channels-first format.
+ """
+ if not isinstance(grid_pinpoints, list):
+ raise TypeError("grid_pinpoints must be a list of possible resolutions.")
+
+ image_size = get_image_size(image, channel_dim=ChannelDimension.FIRST)
+ best_resolution = select_best_resolution(image_size, grid_pinpoints)
+ resized_image = self._resize_for_patching(image, best_resolution, resample)
+ padded_image = self._pad_for_patching(resized_image, best_resolution)
+ patches = divide_to_patches(padded_image, patch_size=patch_size)
+ return patches
+
+ def _preprocess(
+ self,
+ images: list[np.ndarray],
+ do_rescale: bool,
+ rescale_factor: float,
+ do_normalize: bool,
+ image_mean: float | list[float] | None,
+ image_std: float | list[float] | None,
+ return_tensors: str | TensorType | None,
+ max_image_size: int = 980,
+ min_image_size: int = 336,
+ split_resolutions: list[list[int]] | None = None,
+ split_image: bool = False,
+ resample: "PILImageResampling | None" = None,
+ **kwargs,
+ ) -> BatchFeature:
+ if max_image_size not in [490, 980]:
+ raise ValueError("max_image_size must be either 490 or 980")
+
+ pixel_values = []
+ pixel_masks = []
+ num_crops = None
+
+ for image in images:
+ if split_image:
+ crop_images = self.get_image_patches(image, split_resolutions, max_image_size, resample)
+ else:
+ crop_images = [image]
+
+ if num_crops is None or len(crop_images) > num_crops:
+ num_crops = len(crop_images)
+
+ for crop_image in crop_images:
+ h, w = crop_image.shape[-2], crop_image.shape[-1]
+ scale = max_image_size / max(h, w)
+ if w >= h:
+ new_h = max(int(h * scale), min_image_size)
+ new_w = max_image_size
+ else:
+ new_h = max_image_size
+ new_w = max(int(w * scale), min_image_size)
+
+ crop_image = self.resize(crop_image, SizeDict(height=new_h, width=new_w), resample)
+
+ padding_bottom = max_image_size - new_h
+ padding_right = max_image_size - new_w
+ crop_image = np.pad(
+ crop_image, ((0, 0), (0, padding_bottom), (0, padding_right)), mode="constant", constant_values=0
+ )
+
+ pixel_mask = np.zeros((max_image_size, max_image_size), dtype=bool)
+ pixel_mask[:new_h, :new_w] = True
+ pixel_masks.append(pixel_mask)
+
+ if do_rescale:
+ crop_image = self.rescale(crop_image, rescale_factor)
+ if do_normalize:
+ crop_image = self.normalize(crop_image, image_mean, image_std)
+
+ pixel_values.append(crop_image)
+
+ return BatchFeature(
+ data={
+ "pixel_values": np.stack(pixel_values, axis=0),
+ "pixel_mask": np.stack(pixel_masks, axis=0),
+ "num_crops": num_crops,
+ },
+ tensor_type=return_tensors,
+ )
+
+ def get_number_of_image_patches(self, height: int, width: int, images_kwargs=None):
+ """
+ A utility that returns number of image patches for a given image size.
+
+ Args:
+ height (`int`):
+ Height of the input image.
+ width (`int`):
+ Width of the input image.
+ images_kwargs (`dict`, *optional*):
+ Any kwargs to override defaults of the image processor.
+
+ Returns:
+ `int`: Number of patches per image.
+ """
+ split_image = images_kwargs.get("split_image", self.split_image)
+ max_image_size = images_kwargs.get("max_image_size", self.max_image_size)
+
+ resized_height, resized_width = select_best_resolution((height, width), self.split_resolutions)
+ num_patches = 1 if not split_image else resized_height // max_image_size * resized_width // max_image_size
+ return num_patches
+
+
+__all__ = ["AriaImageProcessorPil"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/modeling_aria.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/modeling_aria.py
new file mode 100644
index 0000000000000000000000000000000000000000..e4fab906e561197a973560d67b5b745417345380
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/modeling_aria.py
@@ -0,0 +1,1198 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/aria/modular_aria.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_aria.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2024 The Rhymes-AI Teams Authors and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from collections.abc import Callable
+from dataclasses import dataclass
+from typing import Optional
+
+import torch
+from torch import nn
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...cache_utils import Cache, DynamicCache
+from ...generation import GenerationMixin
+from ...integrations import use_kernel_forward_from_hub, use_kernel_func_from_hub, use_kernelized_func
+from ...masking_utils import create_causal_mask
+from ...modeling_flash_attention_utils import FlashAttentionKwargs
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import (
+ BaseModelOutputWithPast,
+ BaseModelOutputWithPooling,
+ CausalLMOutputWithPast,
+ ModelOutput,
+)
+from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, torch_compilable_check
+from ...utils.generic import maybe_autocast, merge_with_config_defaults
+from ...utils.output_capturing import capture_outputs
+from ..auto import AutoModel
+from .configuration_aria import AriaConfig, AriaTextConfig
+
+
+@use_kernel_forward_from_hub("RMSNorm")
+class AriaTextRMSNorm(nn.Module):
+ def __init__(self, hidden_size, eps: float = 1e-6) -> None:
+ """
+ AriaTextRMSNorm is equivalent to T5LayerNorm
+ """
+ super().__init__()
+ self.weight = nn.Parameter(torch.ones(hidden_size))
+ self.variance_epsilon = eps
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ input_dtype = hidden_states.dtype
+ hidden_states = hidden_states.to(torch.float32)
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
+ return self.weight * hidden_states.to(input_dtype)
+
+ def extra_repr(self):
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
+
+
+class AriaProjectorMLP(nn.Module):
+ """
+ Feed-Forward Network module for the Aria Projector.
+
+ Args:
+ in_features (`int`):
+ Input embedding dimension.
+ hidden_features (`int`):
+ Hidden dimension of the feed-forward network.
+ output_dim (`int`):
+ Output dimension.
+ """
+
+ def __init__(self, in_features, hidden_features, output_dim):
+ super().__init__()
+ self.linear_in = nn.Linear(in_features, hidden_features, bias=False)
+ self.linear_out = nn.Linear(hidden_features, output_dim, bias=False)
+ self.act = ACT2FN["gelu_new"]
+
+ def forward(self, hidden_states):
+ hidden_states = self.act(self.linear_in(hidden_states))
+ hidden_states = self.linear_out(hidden_states)
+ return hidden_states
+
+
+class AriaCrossAttention(nn.Module):
+ """
+ Aria Cross-Attention module.
+
+ Args:
+ config (`AriaConfig`):
+ The configuration to use.
+ """
+
+ def __init__(self, config: AriaConfig, dropout_rate: float = 0):
+ super().__init__()
+ hidden_size = config.vision_config.hidden_size
+ num_heads = config.vision_config.num_attention_heads
+ self.num_heads = num_heads
+ self.q_proj = nn.Linear(hidden_size, hidden_size, bias=False)
+ self.k_proj = nn.Linear(hidden_size, hidden_size, bias=False)
+ self.v_proj = nn.Linear(hidden_size, hidden_size, bias=False)
+
+ # Original code here: https://github.com/rhymes-ai/Aria/blob/719ff4e52b727443cba3793b0e27fe64e0244fe1/aria/model/projector.py#L48
+ self.multihead_attn = nn.MultiheadAttention(hidden_size, num_heads, batch_first=True)
+ self.linear = nn.Linear(hidden_size, hidden_size)
+ self.dropout = nn.Dropout(dropout_rate)
+
+ self.layer_norm = nn.LayerNorm(hidden_size)
+ self.layer_norm_kv = nn.LayerNorm(hidden_size)
+
+ def forward(self, key_value_states, hidden_states, attn_mask=None):
+ """
+ Forward pass of the AriaCrossAttention module.
+
+ Args:
+ key_value_states (`torch.Tensor`):
+ Input tensor for key and value.
+ hidden_states (`torch.Tensor`):
+ Input tensor for query.
+ attn_mask (`torch.Tensor`, *optional*, defaults to None):
+ Attention mask.
+
+ Returns:
+ torch.Tensor:
+ Output tensor after cross-attention.
+ """
+ query = self.q_proj(self.layer_norm(hidden_states))
+
+ key_value_states = self.layer_norm_kv(key_value_states)
+ key = self.k_proj(key_value_states)
+ value = self.v_proj(key_value_states)
+
+ attn_output, _ = self.multihead_attn(query, key, value, attn_mask=attn_mask)
+
+ attn_output = self.dropout(self.linear(attn_output))
+
+ return attn_output
+
+
+class AriaProjector(nn.Module):
+ """
+ Aria Projector module.
+
+ This module projects vision features into the language model's embedding space, enabling interaction between vision and language components.
+
+ Args:
+ config (`AriaConfig`):
+ Configuration object for the model.
+ """
+
+ def __init__(
+ self,
+ config: AriaConfig,
+ ):
+ super().__init__()
+
+ self.patch_to_query_dict = config.projector_patch_to_query_dict
+ self.in_features = config.vision_config.hidden_size
+ self.num_heads = config.vision_config.num_attention_heads
+ self.kv_dim = config.vision_config.hidden_size
+ self.hidden_features = config.text_config.hidden_size
+ self.output_dim = config.text_config.hidden_size
+
+ self.query = nn.Parameter(torch.zeros(config.max_value_projector_patch_to_query_dict, self.in_features))
+
+ self.cross_attn = AriaCrossAttention(config)
+
+ self.layer_norm = nn.LayerNorm(self.in_features)
+ self.feed_forward = AriaProjectorMLP(self.in_features, self.hidden_features, self.output_dim)
+
+ def forward(self, key_value_states: torch.Tensor, attn_mask: torch.Tensor | None = None):
+ """
+ Forward pass of the Projector module.
+
+ Args:
+ key_value_states (`torch.Tensor`):
+ Input tensor of shape (batch_size, num_patches, kv_dim).
+ attn_mask (`torch.Tensor`, *optional*, default is None):
+ Attention mask.
+
+ Returns:
+ `torch.Tensor`: Output tensor of shape (batch_size, query_number, output_dim).
+ """
+ batch_size, num_patches = key_value_states.shape[0], key_value_states.shape[1]
+
+ if num_patches not in self.patch_to_query_dict:
+ raise KeyError(
+ f"Number of patches {num_patches} not found in patch_to_query_dict amongst possible values {self.patch_to_query_dict.keys()}."
+ )
+ query_num = self.patch_to_query_dict[num_patches]
+
+ queries = self.query[:query_num].unsqueeze(0).repeat(batch_size, 1, 1)
+
+ if attn_mask is not None:
+ attn_mask = attn_mask.repeat_interleave(self.num_heads, 0)
+ attn_mask = attn_mask.unsqueeze(1).expand(-1, queries.size(1), -1)
+
+ attention_out = self.cross_attn(key_value_states, queries, attn_mask=attn_mask)
+
+ out = self.feed_forward(self.layer_norm(attention_out))
+
+ return out
+
+
+class AriaSharedExpertsMLP(nn.Module):
+ """
+ Shared Expert MLP for shared experts.
+
+ Unlike routed experts, shared experts process all tokens without routing.
+ This class reconfigures the intermediate size in comparison to the LlamaMLP.
+
+ Args:
+ config (`AriaTextConfig`): Configuration object for the Aria language model.
+ """
+
+ def __init__(self, config: AriaTextConfig):
+ super().__init__()
+ self.config = config
+ self.hidden_size = config.hidden_size
+ self.intermediate_size = config.intermediate_size * config.moe_num_shared_experts
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
+ self.act_fn = ACT2FN[config.hidden_act]
+
+ def forward(self, x):
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
+ return down_proj
+
+
+def sequential_experts_gemm(token_states, expert_weights, tokens_per_expert):
+ """
+ Compute the matrix multiplication (GEMM) for each expert sequentially. This approach is computationally inefficient, especially when dealing with a large number of experts.
+
+ Args:
+ token_states (torch.Tensor): Input tensor of shape (num_tokens, in_features).
+ expert_weights (torch.Tensor): Weight tensor of shape (num_experts, in_features, out_features).
+ tokens_per_expert (torch.Tensor): Number of tokens assigned to each expert.
+
+ Returns:
+ torch.Tensor: Output tensor of shape (num_tokens, out_features).
+ """
+ num_tokens = token_states.shape[0]
+ out_features = expert_weights.shape[-1]
+ output = torch.zeros(num_tokens, out_features, dtype=token_states.dtype, device=token_states.device)
+
+ cumsum_num_tokens = torch.cumsum(tokens_per_expert, dim=0)
+ # Insert zero at the beginning for offset index's convenience
+ zero_tensor = torch.zeros(1, dtype=torch.long, device=cumsum_num_tokens.device)
+ cumsum_num_tokens = torch.cat((zero_tensor, cumsum_num_tokens))
+
+ for expert_num in range(expert_weights.shape[0]):
+ start = cumsum_num_tokens[expert_num]
+ end = cumsum_num_tokens[expert_num + 1]
+ tokens = token_states[start:end]
+
+ out = torch.matmul(tokens, expert_weights[expert_num])
+ output[start:end] = out
+ return output
+
+
+class AriaGroupedExpertsGemm(nn.Module):
+ """
+ Grouped GEMM (General Matrix Multiplication) module for efficient expert computation.
+ This module utilizes the grouped_gemm library (https://github.com/fanshiqing/grouped_gemm)
+ for optimized performance. If the grouped_gemm library is not installed, it gracefully
+ falls back to a sequential GEMM implementation, which may be slower but ensures
+ functionality.
+
+ Args:
+ in_features (`int`):
+ Number of input features.
+ out_features (`int`):
+ Number of output features.
+ groups (`int`):
+ Number of expert groups.
+ """
+
+ def __init__(self, in_features, out_features, groups):
+ super().__init__()
+ self.in_features = in_features
+ self.out_features = out_features
+ self.groups = groups
+ self.weight = nn.Parameter(torch.empty(groups, in_features, out_features))
+
+ def forward(self, input, tokens_per_expert):
+ """
+ Perform grouped matrix multiplication.
+
+ Args:
+ input (`torch.Tensor`):
+ Input tensor of shape (num_tokens, in_features).
+ tokens_per_expert (`torch.Tensor`):
+ Number of tokens assigned to each expert.
+
+ Returns:
+ torch.Tensor: Output tensor of shape (num_tokens, out_features).
+ """
+ return sequential_experts_gemm(
+ input,
+ self.weight,
+ tokens_per_expert.cpu(),
+ )
+
+
+class AriaExperts(nn.Module):
+ def __init__(self, config: AriaTextConfig) -> None:
+ super().__init__()
+ self.config = config
+ self.fc1 = AriaGroupedExpertsGemm(config.hidden_size, config.intermediate_size * 2, config.moe_num_experts)
+ self.fc2 = AriaGroupedExpertsGemm(config.intermediate_size, config.hidden_size, config.moe_num_experts)
+
+ def route_tokens_to_experts(self, router_logits):
+ top_logits, top_indices = torch.topk(router_logits, k=self.config.moe_topk, dim=1)
+ scores = nn.functional.softmax(top_logits, dim=-1)
+ return top_indices, scores
+
+ def forward(self, hidden_states, router_logits) -> torch.Tensor:
+ top_k_index, top_k_weights = self.route_tokens_to_experts(router_logits)
+ original_dtype = top_k_index.dtype
+ tokens_per_expert = torch.histc(
+ top_k_index.flatten().to(torch.float32),
+ bins=self.config.moe_num_experts,
+ min=0,
+ max=self.config.moe_num_experts - 1,
+ ).to(original_dtype)
+ indices = top_k_index
+
+ flatten_indices = indices.view(-1)
+ sorted_indices = torch.argsort(flatten_indices)
+ permuted_tokens = hidden_states.index_select(0, sorted_indices // self.config.moe_topk)
+
+ fc1_output = self.fc1(permuted_tokens, tokens_per_expert)
+ projection, gate = torch.chunk(fc1_output, 2, dim=-1)
+ fc1_output = nn.functional.silu(projection) * gate
+ expert_output = self.fc2(fc1_output, tokens_per_expert)
+
+ unpermuted_tokens = torch.zeros(
+ (top_k_weights.shape[0] * self.config.moe_topk, expert_output.size(1)),
+ dtype=expert_output.dtype,
+ device=expert_output.device,
+ )
+ unpermuted_tokens.index_copy_(0, sorted_indices, expert_output)
+ unpermuted_tokens = unpermuted_tokens.view(-1, self.config.moe_topk, expert_output.size(1))
+
+ output = (unpermuted_tokens * top_k_weights.unsqueeze(-1)).sum(dim=1)
+ return output
+
+
+class AriaTextMoELayer(nn.Module):
+ def __init__(self, config: AriaTextConfig):
+ super().__init__()
+ self.router = nn.Linear(config.hidden_size, config.moe_num_experts, bias=False)
+ self.experts = AriaExperts(config)
+ self.shared_experts = AriaSharedExpertsMLP(config)
+ self.config = config
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ original_shape = hidden_states.shape
+ hidden_states = hidden_states.view(-1, hidden_states.size(-1))
+ router_logits = self.router(hidden_states)
+ expert_output = self.experts(hidden_states, router_logits).view(original_shape)
+ shared_expert_output = self.shared_experts(hidden_states.view(original_shape))
+ return expert_output + shared_expert_output
+
+
+def rotate_half(x):
+ """Rotates half the hidden dims of the input."""
+ x1 = x[..., : x.shape[-1] // 2]
+ x2 = x[..., x.shape[-1] // 2 :]
+ return torch.cat((-x2, x1), dim=-1)
+
+
+@use_kernel_func_from_hub("rotary_pos_emb")
+def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
+ """Applies Rotary Position Embedding to the query and key tensors.
+
+ Args:
+ q (`torch.Tensor`): The query tensor.
+ k (`torch.Tensor`): The key tensor.
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
+ Returns:
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
+ """
+ cos = cos.unsqueeze(unsqueeze_dim)
+ sin = sin.unsqueeze(unsqueeze_dim)
+ q_embed = (q * cos) + (rotate_half(q) * sin)
+ k_embed = (k * cos) + (rotate_half(k) * sin)
+ return q_embed, k_embed
+
+
+def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
+ """
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
+ """
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
+ if n_rep == 1:
+ return hidden_states
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
+
+
+def eager_attention_forward(
+ module: nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: torch.Tensor | None,
+ scaling: float,
+ dropout: float = 0.0,
+ **kwargs: Unpack[TransformersKwargs],
+):
+ key_states = repeat_kv(key, module.num_key_value_groups)
+ value_states = repeat_kv(value, module.num_key_value_groups)
+
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
+ if attention_mask is not None:
+ attn_weights = attn_weights + attention_mask
+
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
+ attn_output = torch.matmul(attn_weights, value_states)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+
+ return attn_output, attn_weights
+
+
+@use_kernelized_func(apply_rotary_pos_emb)
+class AriaTextAttention(nn.Module):
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
+
+ def __init__(self, config: AriaTextConfig, layer_idx: int):
+ super().__init__()
+ self.config = config
+ self.layer_idx = layer_idx
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
+ self.scaling = self.head_dim**-0.5
+ self.attention_dropout = config.attention_dropout
+ self.is_causal = True
+
+ self.q_proj = nn.Linear(
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
+ )
+ self.k_proj = nn.Linear(
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
+ )
+ self.v_proj = nn.Linear(
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
+ )
+ self.o_proj = nn.Linear(
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
+ )
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
+ attention_mask: torch.Tensor | None = None,
+ past_key_values: Cache | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor, torch.Tensor]:
+ input_shape = hidden_states.shape[:-1]
+ hidden_shape = (*input_shape, -1, self.head_dim)
+
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+
+ cos, sin = position_embeddings
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
+
+ if past_key_values is not None:
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_states,
+ key_states,
+ value_states,
+ attention_mask,
+ dropout=0.0 if not self.training else self.attention_dropout,
+ scaling=self.scaling,
+ **kwargs,
+ )
+
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ attn_output = self.o_proj(attn_output)
+ return attn_output, attn_weights
+
+
+class AriaTextDecoderLayer(GradientCheckpointingLayer):
+ """
+ Aria Text Decoder Layer.
+
+ This class defines a single decoder layer in the language model, incorporating self-attention and Mixture of Experts (MoE) feed-forward network.
+
+ Args:
+ config (`AriaTextConfig`):
+ Configuration object for the text component of the model.
+ layer_idx (`int`):
+ Index of the layer.
+ """
+
+ def __init__(self, config: AriaTextConfig, layer_idx: int):
+ super().__init__()
+ self.hidden_size = config.hidden_size
+
+ self.self_attn = AriaTextAttention(config=config, layer_idx=layer_idx)
+ self.mlp = AriaTextMoELayer(config)
+ self.input_layernorm = AriaTextRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.post_attention_layernorm = AriaTextRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ use_cache: bool | None = False,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.Tensor:
+ residual = hidden_states
+ hidden_states = self.input_layernorm(hidden_states)
+ # Self Attention
+ hidden_states, _ = self.self_attn(
+ hidden_states=hidden_states,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ position_embeddings=position_embeddings,
+ **kwargs,
+ )
+ hidden_states = residual + hidden_states
+
+ # Fully Connected
+ residual = hidden_states
+ hidden_states = self.post_attention_layernorm(hidden_states)
+ hidden_states = self.mlp(hidden_states)
+ hidden_states = residual + hidden_states
+ return hidden_states
+
+
+@auto_docstring
+class AriaTextPreTrainedModel(PreTrainedModel):
+ config: AriaTextConfig
+ base_model_prefix = "model"
+ input_modalities = ("image", "text")
+ _no_split_modules = ["AriaTextDecoderLayer", "AriaGroupedExpertsGemm"]
+ supports_gradient_checkpointing = True
+ _skip_keys_device_placement = ["past_key_values"]
+ _supports_flash_attn = True
+ _supports_sdpa = True
+
+ _supports_attention_backend = True
+ _can_record_outputs = {
+ "hidden_states": AriaTextDecoderLayer,
+ "attentions": AriaTextAttention,
+ }
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ super()._init_weights(module)
+ if isinstance(module, AriaGroupedExpertsGemm):
+ init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
+
+
+@auto_docstring
+class AriaPreTrainedModel(PreTrainedModel):
+ config: AriaConfig
+ base_model_prefix = "model"
+ supports_gradient_checkpointing = True
+ _no_split_modules = ["AriaDecoderLayer"]
+ _skip_keys_device_placement = ["past_key_values"]
+ _supports_flash_attn = True
+ _supports_sdpa = True
+ _supports_flex_attn = True
+ _can_compile_fullgraph = False # MoE models don't work with torch.compile (dynamic slicing)
+ _supports_attention_backend = True
+ _can_record_outputs = {
+ "hidden_states": AriaTextDecoderLayer,
+ "attentions": AriaTextAttention,
+ }
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ super()._init_weights(module)
+ if isinstance(module, AriaProjector):
+ init.trunc_normal_(module.query, std=self.config.initializer_range)
+
+
+class AriaTextRotaryEmbedding(nn.Module):
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
+
+ def __init__(self, config: AriaTextConfig, device=None):
+ super().__init__()
+ self.max_seq_len_cached = config.max_position_embeddings
+ self.original_max_seq_len = config.max_position_embeddings
+
+ self.config = config
+
+ self.rope_type = self.config.rope_parameters["rope_type"]
+ rope_init_fn: Callable = self.compute_default_rope_parameters
+ if self.rope_type != "default":
+ rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
+ inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
+
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
+ self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
+
+ @staticmethod
+ def compute_default_rope_parameters(
+ config: AriaTextConfig | None = None,
+ device: Optional["torch.device"] = None,
+ seq_len: int | None = None,
+ ) -> tuple["torch.Tensor", float]:
+ """
+ Computes the inverse frequencies according to the original RoPE implementation
+ Args:
+ config ([`~transformers.PreTrainedConfig`]):
+ The model configuration.
+ device (`torch.device`):
+ The device to use for initialization of the inverse frequencies.
+ seq_len (`int`, *optional*):
+ The current sequence length. Unused for this type of RoPE.
+ Returns:
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
+ """
+ base = config.rope_parameters["rope_theta"]
+ dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
+
+ attention_factor = 1.0 # Unused in this type of RoPE
+
+ # Compute the inverse frequencies
+ inv_freq = 1.0 / (
+ base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
+ )
+ return inv_freq, attention_factor
+
+ @torch.no_grad()
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
+ def forward(self, x, position_ids):
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
+ position_ids_expanded = position_ids[:, None, :].float()
+
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
+ with maybe_autocast(device_type=device_type, enabled=False): # Force float32
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
+ emb = torch.cat((freqs, freqs), dim=-1)
+ cos = emb.cos() * self.attention_scaling
+ sin = emb.sin() * self.attention_scaling
+
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
+
+
+@auto_docstring
+class AriaTextModel(AriaTextPreTrainedModel):
+ def __init__(self, config: AriaTextConfig):
+ super().__init__(config)
+ self.padding_idx = config.pad_token_id
+ self.vocab_size = config.vocab_size
+
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
+ self.layers = nn.ModuleList(
+ [AriaTextDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
+ )
+ self.norm = AriaTextRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.rotary_emb = AriaTextRotaryEmbedding(config=config)
+ self.gradient_checkpointing = False
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @merge_with_config_defaults
+ @capture_outputs
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ use_cache: bool | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> BaseModelOutputWithPast:
+ if (input_ids is None) ^ (inputs_embeds is not None):
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
+
+ if inputs_embeds is None:
+ inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)
+
+ if use_cache and past_key_values is None:
+ past_key_values = DynamicCache(config=self.config)
+
+ if position_ids is None:
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
+ position_ids = position_ids.unsqueeze(0)
+
+ causal_mask = create_causal_mask(
+ config=self.config,
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ position_ids=position_ids,
+ )
+
+ hidden_states = inputs_embeds
+ position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
+
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
+ hidden_states = decoder_layer(
+ hidden_states,
+ attention_mask=causal_mask,
+ position_embeddings=position_embeddings,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ **kwargs,
+ )
+
+ hidden_states = self.norm(hidden_states)
+ return BaseModelOutputWithPast(
+ last_hidden_state=hidden_states,
+ past_key_values=past_key_values,
+ )
+
+
+@auto_docstring
+class AriaTextForCausalLM(AriaTextPreTrainedModel, GenerationMixin):
+ _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
+ _tp_plan = {"lm_head": "colwise_gather_output"}
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
+
+ def __init__(self, config: AriaTextConfig):
+ super().__init__(config)
+ self.model = AriaTextModel(config)
+ self.vocab_size = config.vocab_size
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ use_cache: bool | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> CausalLMOutputWithPast:
+ r"""
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, AriaTextForCausalLM
+
+ >>> model = AriaTextForCausalLM.from_pretrained("meta-aria_text/AriaText-2-7b-hf")
+ >>> tokenizer = AutoTokenizer.from_pretrained("meta-aria_text/AriaText-2-7b-hf")
+
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
+
+ >>> # Generate
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
+ ```"""
+ outputs: BaseModelOutputWithPast = self.model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ **kwargs,
+ )
+
+ hidden_states = outputs.last_hidden_state
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
+
+ return CausalLMOutputWithPast(
+ loss=loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ Base class for Aria causal language model (or autoregressive) outputs.
+ """
+)
+@dataclass
+class AriaCausalLMOutputWithPast(ModelOutput):
+ r"""
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
+ Language modeling loss (for next-token prediction).
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
+ past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
+ It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
+
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
+ `past_key_values` input) to speed up sequential decoding.
+ image_hidden_states (`torch.FloatTensor`, *optional*):
+ A `torch.FloatTensor` of size `(batch_size, num_images, sequence_length, hidden_size)`.
+ image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
+ """
+
+ loss: torch.FloatTensor | None = None
+ logits: torch.FloatTensor | None = None
+ past_key_values: Cache | None = None
+ hidden_states: tuple[torch.FloatTensor] | None = None
+ attentions: tuple[torch.FloatTensor] | None = None
+ image_hidden_states: torch.FloatTensor | None = None
+
+
+@auto_docstring(
+ custom_intro="""
+ Base class for Aria outputs, with hidden states and attentions.
+ """
+)
+@dataclass
+class AriaModelOutputWithPast(BaseModelOutputWithPast):
+ r"""
+ past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
+ It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
+
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
+ `past_key_values` input) to speed up sequential decoding.
+ image_hidden_states (`torch.FloatTensor`, *optional*):
+ A `torch.FloatTensor` of size `(batch_size, num_images, sequence_length, hidden_size)`.
+ image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
+ """
+
+ image_hidden_states: torch.FloatTensor | None = None
+
+
+@auto_docstring(
+ custom_intro="""
+ The Aria model which consists of a vision backbone and a language model, without a language modeling head.
+ """
+)
+class AriaModel(AriaPreTrainedModel):
+ def __init__(self, config: AriaConfig):
+ super().__init__(config)
+ self.vision_tower = AutoModel.from_config(config.vision_config)
+ self.multi_modal_projector = AriaProjector(config)
+ self.language_model = AutoModel.from_config(config.text_config)
+ self.post_init()
+
+ @merge_with_config_defaults
+ @can_return_tuple
+ @auto_docstring(
+ custom_intro="Obtains image last hidden states from the vision tower and apply multimodal projection."
+ )
+ def get_image_features(
+ self,
+ pixel_values: torch.FloatTensor,
+ pixel_mask: torch.FloatTensor | None = None,
+ vision_feature_layer: int | list[int] = -1,
+ output_hidden_states: bool | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutputWithPooling:
+ patch_attention_mask = self._create_patch_attention_mask(pixel_mask)
+ image_outputs = self.vision_tower(
+ pixel_values,
+ patch_attention_mask=patch_attention_mask,
+ output_hidden_states=True, # Ignore arg on purpose
+ return_dict=True,
+ **kwargs,
+ )
+ image_attn_mask = None
+ if patch_attention_mask is not None:
+ flattened_mask = patch_attention_mask.flatten(1)
+ image_attn_mask = torch.logical_not(flattened_mask)
+
+ selected_image_feature = image_outputs.hidden_states[vision_feature_layer]
+ image_outputs.pooler_output = self.multi_modal_projector(selected_image_feature, attn_mask=image_attn_mask)
+
+ return image_outputs
+
+ def get_placeholder_mask(
+ self, input_ids: torch.LongTensor, inputs_embeds: torch.FloatTensor, image_features: torch.FloatTensor
+ ):
+ """
+ Obtains multimodal placeholder mask from `input_ids` or `inputs_embeds`, and checks that the placeholder token count is
+ equal to the length of multimodal features. If the lengths are different, an error is raised.
+ """
+ if input_ids is None:
+ special_image_mask = inputs_embeds == self.get_input_embeddings()(
+ torch.tensor(self.config.image_token_id, dtype=torch.long, device=inputs_embeds.device)
+ )
+ special_image_mask = special_image_mask.all(-1)
+ else:
+ special_image_mask = input_ids == self.config.image_token_id
+
+ n_image_tokens = special_image_mask.sum()
+ n_image_features = image_features.shape[0] * image_features.shape[1]
+ special_image_mask = special_image_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
+ torch_compilable_check(
+ inputs_embeds[special_image_mask].numel() == image_features.numel(),
+ f"Image features and image tokens do not match, tokens: {n_image_tokens}, features: {n_image_features}",
+ )
+ return special_image_mask
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ pixel_values: torch.FloatTensor | None = None,
+ pixel_mask: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ use_cache: bool | None = None,
+ **kwargs: Unpack[FlashAttentionKwargs],
+ ) -> tuple | AriaModelOutputWithPast:
+ if inputs_embeds is None:
+ inputs_embeds = self.get_input_embeddings()(input_ids)
+
+ # 2. Merge text and images
+ if pixel_values is not None and inputs_embeds.shape[1] != 1:
+ image_features = self.get_image_features(
+ pixel_values=pixel_values,
+ pixel_mask=pixel_mask,
+ vision_feature_layer=self.config.vision_feature_layer,
+ return_dict=True,
+ ).pooler_output
+ image_features = image_features.to(inputs_embeds.device, inputs_embeds.dtype)
+ special_image_mask = self.get_placeholder_mask(
+ input_ids, inputs_embeds=inputs_embeds, image_features=image_features
+ )
+ inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)
+
+ outputs = self.language_model(
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ **kwargs,
+ )
+
+ return AriaModelOutputWithPast(
+ last_hidden_state=outputs.last_hidden_state,
+ past_key_values=outputs.past_key_values if use_cache else None,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ image_hidden_states=image_features if pixel_values is not None else None,
+ )
+
+ def _create_patch_attention_mask(self, pixel_mask):
+ if pixel_mask is None:
+ return None
+
+ patches_subgrid = pixel_mask.unfold(
+ dimension=1,
+ size=self.vision_tower.config.patch_size,
+ step=self.vision_tower.config.patch_size,
+ )
+ patches_subgrid = patches_subgrid.unfold(
+ dimension=2,
+ size=self.vision_tower.config.patch_size,
+ step=self.vision_tower.config.patch_size,
+ )
+ return (patches_subgrid.sum(dim=(-1, -2)) > 0).bool()
+
+
+@auto_docstring(
+ custom_intro="""
+ Aria model for conditional generation tasks.
+
+ This model combines a vision tower, a multi-modal projector, and a language model
+ to perform tasks that involve both image and text inputs.
+ """
+)
+class AriaForConditionalGeneration(AriaPreTrainedModel, GenerationMixin):
+ _tied_weights_keys = {"lm_head.weight": "model.language_model.embed_tokens.weight"}
+
+ def __init__(self, config: AriaConfig):
+ super().__init__(config)
+ self.model = AriaModel(config)
+ self.lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.vocab_size, bias=False)
+ self.post_init()
+
+ def get_output_embeddings(self) -> nn.Module:
+ return self.lm_head
+
+ @auto_docstring
+ def get_image_features(
+ self,
+ pixel_values: torch.FloatTensor,
+ pixel_mask: torch.FloatTensor | None = None,
+ vision_feature_layer: int | list[int] = -1,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutputWithPooling:
+ return self.model.get_image_features(
+ pixel_values=pixel_values,
+ pixel_mask=pixel_mask,
+ vision_feature_layer=vision_feature_layer,
+ **kwargs,
+ )
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ pixel_values: torch.FloatTensor | None = None,
+ pixel_mask: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ use_cache: bool | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | AriaCausalLMOutputWithPast:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
+ config.vocab_size]` or `model.image_token_id` (where `model` is your instance of `AriaForConditionalGeneration`).
+ Tokens with indices set to `model.image_token_id` are ignored (masked), the loss is only
+ computed for the tokens with labels in `[0, ..., config.vocab_size]`.
+
+ Example:
+
+ ```python
+ >>> import httpx
+ >>> from io import BytesIO
+ >>> import torch
+ >>> from PIL import Image
+ >>> from io import BytesIO
+
+ >>> from transformers import AutoProcessor, AutoModel
+ >>> from transformers.image_utils import load_image
+
+ >>> # Note that passing the image urls (instead of the actual pil images) to the processor is also possible
+ >>> image1 = load_image("https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg")
+ >>> image2 = load_image("https://cdn.britannica.com/59/94459-050-DBA42467/Skyline-Chicago.jpg")
+ >>> image3 = load_image("https://cdn.britannica.com/68/170868-050-8DDE8263/Golden-Gate-Bridge-San-Francisco.jpg")
+
+ >>> processor = AutoProcessor.from_pretrained("Rhymes-AI/Aria")
+ >>> model = AutoModel.from_pretrained("Rhymes-AI/Aria", dtype=torch.bfloat16, device_map="auto")
+
+ >>> # Create inputs
+ >>> messages = [
+ ... {
+ ... "role": "user",
+ ... "content": [
+ ... {"type": "image"},
+ ... {"type": "text", "text": "In this image, we can see the city of New York, and more specifically the Statue of Liberty."},
+ ... {"type": "image"},
+ ... {"type": "text", "text": "What can we see in this image?"},
+ ... ]
+ ... },
+ ... {
+ ... "role": "user",
+ ... "content": [
+ ... {"type": "image"},
+ ... {"type": "text", "text": "In which city is that bridge located?"},
+ ... ]
+ ... }
+ ... ]
+
+ >>> prompts = [processor.apply_chat_template([message], add_generation_prompt=True) for message in messages]
+ >>> images = [[image1, image2], [image3]]
+ >>> inputs = processor(text=prompts, images=images, padding=True, return_tensors="pt").to(model.device)
+
+ >>> # Generate
+ >>> generated_ids = model.generate(**inputs, max_new_tokens=256)
+ >>> generated_texts = processor.batch_decode(generated_ids, skip_special_tokens=True)
+
+ >>> print(generated_texts[0])
+ Assistant: There are buildings, trees, lights, and water visible in this image.
+
+ >>> print(generated_texts[1])
+ Assistant: The bridge is in San Francisco.
+ ```"""
+ outputs = self.model(
+ input_ids=input_ids,
+ pixel_values=pixel_values,
+ pixel_mask=pixel_mask,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ **kwargs,
+ )
+
+ hidden_states = outputs[0]
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(
+ logits=logits, labels=labels, vocab_size=self.config.text_config.vocab_size, **kwargs
+ )
+
+ return AriaCausalLMOutputWithPast(
+ loss=loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+ def prepare_inputs_for_generation(
+ self,
+ input_ids,
+ past_key_values=None,
+ inputs_embeds=None,
+ pixel_values=None,
+ pixel_mask=None,
+ attention_mask=None,
+ logits_to_keep=None,
+ is_first_iteration=False,
+ **kwargs,
+ ):
+ model_inputs = super().prepare_inputs_for_generation(
+ input_ids,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ logits_to_keep=logits_to_keep,
+ is_first_iteration=is_first_iteration,
+ **kwargs,
+ )
+
+ if is_first_iteration or not kwargs.get("use_cache", True):
+ # Pixel values are used only in the first iteration if available
+ # In subsequent iterations, they are already merged with text and cached
+ # NOTE: first iteration doesn't have to be prefill, it can be the first
+ # iteration with a question and cached system prompt (continue generate from cache)
+ model_inputs["pixel_values"] = pixel_values
+ model_inputs["pixel_mask"] = pixel_mask
+
+ return model_inputs
+
+
+__all__ = [
+ "AriaForConditionalGeneration",
+ "AriaPreTrainedModel",
+ "AriaTextPreTrainedModel",
+ "AriaTextModel",
+ "AriaModel",
+ "AriaTextForCausalLM",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/modular_aria.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/modular_aria.py
new file mode 100644
index 0000000000000000000000000000000000000000..7e50fe3812fa731741e20e3fa11d1b42f3c5e380
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/modular_aria.py
@@ -0,0 +1,1156 @@
+# Copyright 2024 The Rhymes-AI Teams Authors and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import torch
+from huggingface_hub.dataclasses import strict
+from torch import nn
+from torchvision.transforms.v2 import functional as tvF
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...cache_utils import Cache
+from ...configuration_utils import PreTrainedConfig
+from ...image_processing_backends import TorchvisionBackend
+from ...image_processing_utils import BatchFeature, get_patch_output_size, select_best_resolution
+from ...image_transforms import divide_to_patches
+from ...image_utils import (
+ ChannelDimension,
+ ImageInput,
+ PILImageResampling,
+ SizeDict,
+ get_image_size,
+)
+from ...modeling_flash_attention_utils import FlashAttentionKwargs
+from ...modeling_outputs import BaseModelOutputWithPooling
+from ...modeling_utils import PreTrainedModel
+from ...processing_utils import ImagesKwargs, MultiModalData, ProcessingKwargs, ProcessorMixin, Unpack
+from ...tokenization_python import PreTokenizedInput, TextInput
+from ...utils import (
+ TensorType,
+ TransformersKwargs,
+ auto_docstring,
+ can_return_tuple,
+ logging,
+)
+from ..auto import CONFIG_MAPPING, AutoConfig, AutoTokenizer
+from ..llama.configuration_llama import LlamaConfig
+from ..llama.modeling_llama import (
+ LlamaAttention,
+ LlamaDecoderLayer,
+ LlamaForCausalLM,
+ LlamaMLP,
+ LlamaModel,
+ LlamaPreTrainedModel,
+ LlamaRMSNorm,
+)
+from ..llava.modeling_llava import (
+ LlavaCausalLMOutputWithPast,
+ LlavaForConditionalGeneration,
+ LlavaModel,
+ LlavaModelOutputWithPast,
+)
+
+
+logger = logging.get_logger(__name__)
+
+
+def sequential_experts_gemm(token_states, expert_weights, tokens_per_expert):
+ """
+ Compute the matrix multiplication (GEMM) for each expert sequentially. This approach is computationally inefficient, especially when dealing with a large number of experts.
+
+ Args:
+ token_states (torch.Tensor): Input tensor of shape (num_tokens, in_features).
+ expert_weights (torch.Tensor): Weight tensor of shape (num_experts, in_features, out_features).
+ tokens_per_expert (torch.Tensor): Number of tokens assigned to each expert.
+
+ Returns:
+ torch.Tensor: Output tensor of shape (num_tokens, out_features).
+ """
+ num_tokens = token_states.shape[0]
+ out_features = expert_weights.shape[-1]
+ output = torch.zeros(num_tokens, out_features, dtype=token_states.dtype, device=token_states.device)
+
+ cumsum_num_tokens = torch.cumsum(tokens_per_expert, dim=0)
+ # Insert zero at the beginning for offset index's convenience
+ zero_tensor = torch.zeros(1, dtype=torch.long, device=cumsum_num_tokens.device)
+ cumsum_num_tokens = torch.cat((zero_tensor, cumsum_num_tokens))
+
+ for expert_num in range(expert_weights.shape[0]):
+ start = cumsum_num_tokens[expert_num]
+ end = cumsum_num_tokens[expert_num + 1]
+ tokens = token_states[start:end]
+
+ out = torch.matmul(tokens, expert_weights[expert_num])
+ output[start:end] = out
+ return output
+
+
+@auto_docstring(checkpoint="rhymes-ai/Aria")
+@strict
+class AriaTextConfig(LlamaConfig):
+ r"""
+ moe_num_experts (`int`, *optional*, defaults to 8):
+ The number of experts in the MoE layer.
+ moe_topk (`int`, *optional*, defaults to 2):
+ The number of top experts to route to for each token.
+ moe_num_shared_experts (`int`, *optional*, defaults to 2):
+ The number of shared experts.
+ """
+
+ model_type = "aria_text"
+ base_config_key = "text_config"
+ base_model_tp_plan = {
+ "layers.*.self_attn.q_proj": "colwise",
+ "layers.*.self_attn.k_proj": "colwise",
+ "layers.*.self_attn.v_proj": "colwise",
+ "layers.*.self_attn.o_proj": "rowwise",
+ "layers.*.mlp.shared_experts.gate_proj": "colwise",
+ "layers.*.mlp.shared_experts.up_proj": "colwise",
+ "layers.*.mlp.shared_experts.down_proj": "rowwise",
+ }
+
+ intermediate_size: int = 4096
+ moe_num_experts: int = 8
+ moe_topk: int = 2
+ moe_num_shared_experts: int = 2
+ pad_token_id: int | None = 2
+
+
+@auto_docstring(checkpoint="rhymes-ai/Aria")
+@strict
+class AriaConfig(PreTrainedConfig):
+ r"""
+ projector_patch_to_query_dict (`dict`, *optional*):
+ Mapping of patch sizes to query dimensions.
+ """
+
+ model_type = "aria"
+ attribute_map = {
+ "image_token_id": "image_token_index",
+ }
+ sub_configs = {"text_config": AriaTextConfig, "vision_config": AutoConfig}
+
+ vision_config: dict | PreTrainedConfig | None = None
+ text_config: dict | AriaTextConfig | None = None
+ vision_feature_layer: int | list[int] = -1
+ projector_patch_to_query_dict: dict | None = None
+ image_token_index: int = 9
+ initializer_range: float = 0.02
+ tie_word_embeddings: bool = False
+
+ def __post_init__(self, **kwargs):
+ # Convert the keys and values of projector_patch_to_query_dict to integers
+ # This ensures consistency even if they were provided as strings
+ if self.projector_patch_to_query_dict is None:
+ self.projector_patch_to_query_dict = {
+ 1225: 128,
+ 4900: 256,
+ }
+ self.projector_patch_to_query_dict = {int(k): int(v) for k, v in self.projector_patch_to_query_dict.items()}
+ self.max_value_projector_patch_to_query_dict = max(self.projector_patch_to_query_dict.values())
+
+ if isinstance(self.vision_config, dict):
+ self.vision_config["model_type"] = "idefics3_vision"
+ self.vision_config = CONFIG_MAPPING[self.vision_config["model_type"]](**self.vision_config)
+ elif self.vision_config is None:
+ self.vision_config = CONFIG_MAPPING["idefics3_vision"]()
+
+ if isinstance(self.text_config, dict) and "model_type" in self.text_config:
+ self.text_config = AriaTextConfig(**self.text_config)
+ elif self.text_config is None:
+ self.text_config = AriaTextConfig()
+
+ super().__post_init__(**kwargs)
+
+
+class AriaTextRMSNorm(LlamaRMSNorm):
+ pass
+
+
+class AriaProjectorMLP(nn.Module):
+ """
+ Feed-Forward Network module for the Aria Projector.
+
+ Args:
+ in_features (`int`):
+ Input embedding dimension.
+ hidden_features (`int`):
+ Hidden dimension of the feed-forward network.
+ output_dim (`int`):
+ Output dimension.
+ """
+
+ def __init__(self, in_features, hidden_features, output_dim):
+ super().__init__()
+ self.linear_in = nn.Linear(in_features, hidden_features, bias=False)
+ self.linear_out = nn.Linear(hidden_features, output_dim, bias=False)
+ self.act = ACT2FN["gelu_new"]
+
+ def forward(self, hidden_states):
+ hidden_states = self.act(self.linear_in(hidden_states))
+ hidden_states = self.linear_out(hidden_states)
+ return hidden_states
+
+
+class AriaCrossAttention(nn.Module):
+ """
+ Aria Cross-Attention module.
+
+ Args:
+ config (`AriaConfig`):
+ The configuration to use.
+ """
+
+ def __init__(self, config: AriaConfig, dropout_rate: float = 0):
+ super().__init__()
+ hidden_size = config.vision_config.hidden_size
+ num_heads = config.vision_config.num_attention_heads
+ self.num_heads = num_heads
+ self.q_proj = nn.Linear(hidden_size, hidden_size, bias=False)
+ self.k_proj = nn.Linear(hidden_size, hidden_size, bias=False)
+ self.v_proj = nn.Linear(hidden_size, hidden_size, bias=False)
+
+ # Original code here: https://github.com/rhymes-ai/Aria/blob/719ff4e52b727443cba3793b0e27fe64e0244fe1/aria/model/projector.py#L48
+ self.multihead_attn = nn.MultiheadAttention(hidden_size, num_heads, batch_first=True)
+ self.linear = nn.Linear(hidden_size, hidden_size)
+ self.dropout = nn.Dropout(dropout_rate)
+
+ self.layer_norm = nn.LayerNorm(hidden_size)
+ self.layer_norm_kv = nn.LayerNorm(hidden_size)
+
+ def forward(self, key_value_states, hidden_states, attn_mask=None):
+ """
+ Forward pass of the AriaCrossAttention module.
+
+ Args:
+ key_value_states (`torch.Tensor`):
+ Input tensor for key and value.
+ hidden_states (`torch.Tensor`):
+ Input tensor for query.
+ attn_mask (`torch.Tensor`, *optional*, defaults to None):
+ Attention mask.
+
+ Returns:
+ torch.Tensor:
+ Output tensor after cross-attention.
+ """
+ query = self.q_proj(self.layer_norm(hidden_states))
+
+ key_value_states = self.layer_norm_kv(key_value_states)
+ key = self.k_proj(key_value_states)
+ value = self.v_proj(key_value_states)
+
+ attn_output, _ = self.multihead_attn(query, key, value, attn_mask=attn_mask)
+
+ attn_output = self.dropout(self.linear(attn_output))
+
+ return attn_output
+
+
+class AriaProjector(nn.Module):
+ """
+ Aria Projector module.
+
+ This module projects vision features into the language model's embedding space, enabling interaction between vision and language components.
+
+ Args:
+ config (`AriaConfig`):
+ Configuration object for the model.
+ """
+
+ def __init__(
+ self,
+ config: AriaConfig,
+ ):
+ super().__init__()
+
+ self.patch_to_query_dict = config.projector_patch_to_query_dict
+ self.in_features = config.vision_config.hidden_size
+ self.num_heads = config.vision_config.num_attention_heads
+ self.kv_dim = config.vision_config.hidden_size
+ self.hidden_features = config.text_config.hidden_size
+ self.output_dim = config.text_config.hidden_size
+
+ self.query = nn.Parameter(torch.zeros(config.max_value_projector_patch_to_query_dict, self.in_features))
+
+ self.cross_attn = AriaCrossAttention(config)
+
+ self.layer_norm = nn.LayerNorm(self.in_features)
+ self.feed_forward = AriaProjectorMLP(self.in_features, self.hidden_features, self.output_dim)
+
+ def forward(self, key_value_states: torch.Tensor, attn_mask: torch.Tensor | None = None):
+ """
+ Forward pass of the Projector module.
+
+ Args:
+ key_value_states (`torch.Tensor`):
+ Input tensor of shape (batch_size, num_patches, kv_dim).
+ attn_mask (`torch.Tensor`, *optional*, default is None):
+ Attention mask.
+
+ Returns:
+ `torch.Tensor`: Output tensor of shape (batch_size, query_number, output_dim).
+ """
+ batch_size, num_patches = key_value_states.shape[0], key_value_states.shape[1]
+
+ if num_patches not in self.patch_to_query_dict:
+ raise KeyError(
+ f"Number of patches {num_patches} not found in patch_to_query_dict amongst possible values {self.patch_to_query_dict.keys()}."
+ )
+ query_num = self.patch_to_query_dict[num_patches]
+
+ queries = self.query[:query_num].unsqueeze(0).repeat(batch_size, 1, 1)
+
+ if attn_mask is not None:
+ attn_mask = attn_mask.repeat_interleave(self.num_heads, 0)
+ attn_mask = attn_mask.unsqueeze(1).expand(-1, queries.size(1), -1)
+
+ attention_out = self.cross_attn(key_value_states, queries, attn_mask=attn_mask)
+
+ out = self.feed_forward(self.layer_norm(attention_out))
+
+ return out
+
+
+class AriaImageProcessorKwargs(ImagesKwargs, total=False):
+ r"""
+ max_image_size (`int`, *optional*, defaults to `self.max_image_size`):
+ Maximum image size. Must be either 490 or 980.
+ min_image_size (`int`, *optional*, defaults to `self.min_image_size`):
+ Minimum image size. Images smaller than this in any dimension will be scaled up.
+ split_resolutions (`list[list[int]]`, *optional*, defaults to `self.split_resolutions`):
+ A list of possible resolutions as (height, width) pairs for splitting high-resolution images into patches.
+ split_image (`bool`, *optional*, defaults to `self.split_image`):
+ Whether to split the image into patches using the best matching resolution from `split_resolutions`.
+ """
+
+ max_image_size: int
+ min_image_size: int
+ split_resolutions: list[list[int]]
+ split_image: bool
+
+
+@auto_docstring
+class AriaImageProcessor(TorchvisionBackend):
+ model_input_names = ["pixel_values", "pixel_mask", "num_crops"]
+ valid_kwargs = AriaImageProcessorKwargs
+
+ resample = PILImageResampling.BICUBIC
+ image_mean = [0.5, 0.5, 0.5]
+ image_std = [0.5, 0.5, 0.5]
+ max_image_size = 980
+ min_image_size = 336
+ split_image = False
+ split_resolutions = None
+ do_convert_rgb = True
+ do_rescale = True
+ do_normalize = True
+
+ def __init__(self, **kwargs: Unpack[AriaImageProcessorKwargs]):
+ if kwargs.get("split_resolutions") is None:
+ default_resolutions = [(1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (2, 4), (2, 3), (2, 2), (2, 1), (3, 1), (3, 2), (4, 1), (4, 2), (5, 1), (6, 1), (7, 1), (8, 1)] # fmt: skip
+ kwargs["split_resolutions"] = [[el[0] * 490, el[1] * 490] for el in default_resolutions]
+ super().__init__(**kwargs)
+
+ def _get_padding_size(self, original_resolution: tuple, target_resolution: tuple) -> list[int]:
+ """Get padding size for patching, returns [left, top, right, bottom] for tvF.pad."""
+ original_height, original_width = original_resolution
+ target_height, target_width = target_resolution
+ paste_x, r_x = divmod(target_width - original_width, 2)
+ paste_y, r_y = divmod(target_height - original_height, 2)
+ return [paste_x, paste_y, paste_x + r_x, paste_y + r_y]
+
+ def _resize_for_patching(
+ self,
+ image: "torch.Tensor",
+ target_resolution: tuple,
+ resample: "PILImageResampling | tvF.InterpolationMode | int | None",
+ ) -> "torch.Tensor":
+ """Resize an image to a target resolution while maintaining aspect ratio."""
+ new_height, new_width = get_patch_output_size(
+ image, target_resolution, input_data_format=ChannelDimension.FIRST
+ )
+ return self.resize(image, SizeDict(height=new_height, width=new_width), resample)
+
+ def _pad_for_patching(
+ self,
+ image: "torch.Tensor",
+ target_resolution: tuple,
+ ) -> "torch.Tensor":
+ """Pad an image to a target resolution while maintaining aspect ratio."""
+ new_resolution = get_patch_output_size(image, target_resolution, input_data_format=ChannelDimension.FIRST)
+ padding = self._get_padding_size(new_resolution, target_resolution)
+ return tvF.pad(image, padding=padding)
+
+ def get_image_patches(
+ self,
+ image: "torch.Tensor",
+ grid_pinpoints: list[list[int]],
+ patch_size: int,
+ resample: "PILImageResampling | tvF.InterpolationMode | int | None",
+ ) -> list["torch.Tensor"]:
+ """
+ Process an image with variable resolutions by dividing it into patches.
+
+ Args:
+ image (`torch.Tensor`):
+ The input image to be processed (channels-first format).
+ grid_pinpoints (`list[list[int]]`):
+ A list of possible resolutions as (height, width) pairs.
+ patch_size (`int`):
+ Size of each square patch to divide the image into.
+ resample (`PILImageResampling | tvF.InterpolationMode | int | None`):
+ Resampling filter to use when resizing.
+
+ Returns:
+ `list[torch.Tensor]`: A list of image patches in channels-first format.
+ """
+ if not isinstance(grid_pinpoints, list):
+ raise TypeError("grid_pinpoints must be a list of possible resolutions.")
+
+ image_size = get_image_size(image, channel_dim=ChannelDimension.FIRST)
+ best_resolution = select_best_resolution(image_size, grid_pinpoints)
+ resized_image = self._resize_for_patching(image, best_resolution, resample)
+ padded_image = self._pad_for_patching(resized_image, best_resolution)
+ patches = divide_to_patches(padded_image, patch_size=patch_size)
+ return patches
+
+ def _preprocess(
+ self,
+ images: list["torch.Tensor"],
+ do_rescale: bool,
+ rescale_factor: float,
+ do_normalize: bool,
+ image_mean: float | list[float] | None,
+ image_std: float | list[float] | None,
+ disable_grouping: bool | None,
+ return_tensors: str | TensorType | None,
+ max_image_size: int = 980,
+ min_image_size: int = 336,
+ split_resolutions: list[list[int]] | None = None,
+ split_image: bool = False,
+ resample: "PILImageResampling | tvF.InterpolationMode | int | None" = None,
+ **kwargs,
+ ) -> BatchFeature:
+ if max_image_size not in [490, 980]:
+ raise ValueError("max_image_size must be either 490 or 980")
+
+ pixel_masks = []
+ processed_crops = []
+ num_crops = None
+
+ for image in images:
+ if split_image:
+ crop_images = self.get_image_patches(image, split_resolutions, max_image_size, resample)
+ else:
+ crop_images = [image]
+
+ if num_crops is None or len(crop_images) > num_crops:
+ num_crops = len(crop_images)
+
+ for crop_image in crop_images:
+ h, w = crop_image.shape[-2], crop_image.shape[-1]
+ scale = max_image_size / max(h, w)
+ if w >= h:
+ new_h = max(int(h * scale), min_image_size)
+ new_w = max_image_size
+ else:
+ new_h = max_image_size
+ new_w = max(int(w * scale), min_image_size)
+
+ crop_image = self.resize(crop_image, SizeDict(height=new_h, width=new_w), resample)
+
+ padding_bottom = max_image_size - new_h
+ padding_right = max_image_size - new_w
+ crop_image = tvF.pad(crop_image, [0, 0, padding_right, padding_bottom])
+
+ pixel_mask = torch.zeros((max_image_size, max_image_size), dtype=torch.bool)
+ pixel_mask[:new_h, :new_w] = True
+ pixel_masks.append(pixel_mask)
+ processed_crops.append(crop_image)
+
+ stacked_images = torch.stack(processed_crops, dim=0)
+ stacked_images = self.rescale_and_normalize(
+ stacked_images, do_rescale, rescale_factor, do_normalize, image_mean, image_std
+ )
+ stacked_masks = torch.stack(pixel_masks, dim=0)
+
+ return BatchFeature(
+ data={
+ "pixel_values": stacked_images,
+ "pixel_mask": stacked_masks,
+ "num_crops": num_crops,
+ },
+ tensor_type=return_tensors,
+ )
+
+ def get_number_of_image_patches(self, height: int, width: int, images_kwargs=None):
+ """
+ A utility that returns number of image patches for a given image size.
+
+ Args:
+ height (`int`):
+ Height of the input image.
+ width (`int`):
+ Width of the input image.
+ images_kwargs (`dict`, *optional*):
+ Any kwargs to override defaults of the image processor.
+
+ Returns:
+ `int`: Number of patches per image.
+ """
+ split_image = images_kwargs.get("split_image", self.split_image)
+ max_image_size = images_kwargs.get("max_image_size", self.max_image_size)
+
+ resized_height, resized_width = select_best_resolution((height, width), self.split_resolutions)
+ num_patches = 1 if not split_image else resized_height // max_image_size * resized_width // max_image_size
+ return num_patches
+
+
+class AriaImagesKwargs(ImagesKwargs, total=False):
+ """
+ split_image (`bool`, *optional*, defaults to `False`):
+ Whether to split large images into multiple crops. When enabled, images exceeding the maximum size are
+ divided into overlapping crops that are processed separately and then combined. This allows processing
+ of very high-resolution images that exceed the model's input size limits.
+ max_image_size (`int`, *optional*, defaults to `980`):
+ Maximum image size (in pixels) for a single image crop. Images larger than this will be split into
+ multiple crops when `split_image=True`, or resized if splitting is disabled. This parameter controls
+ the maximum resolution of individual image patches processed by the model.
+ min_image_size (`int`, *optional*):
+ Minimum image size (in pixels) for a single image crop. Images smaller than this will be upscaled to
+ meet the minimum requirement. If not specified, images are processed at their original size (subject
+ to the maximum size constraint).
+ """
+
+ split_image: bool
+ max_image_size: int
+ min_image_size: int
+
+
+class AriaProcessorKwargs(ProcessingKwargs, total=False):
+ images_kwargs: AriaImagesKwargs
+
+ _defaults = {
+ "text_kwargs": {
+ "padding": False,
+ "return_mm_token_type_ids": False,
+ },
+ "images_kwargs": {
+ "max_image_size": 980,
+ "split_image": False,
+ },
+ "return_tensors": TensorType.PYTORCH,
+ }
+
+
+@auto_docstring
+class AriaProcessor(ProcessorMixin):
+ def __init__(
+ self,
+ image_processor=None,
+ tokenizer: AutoTokenizer | str = None,
+ chat_template: str | None = None,
+ size_conversion: dict[float | int, int] | None = None,
+ ):
+ r"""
+ size_conversion (`Dict`, *optional*):
+ A dictionary indicating size conversions for images.
+ """
+ if size_conversion is None:
+ size_conversion = {490: 128, 980: 256}
+ self.size_conversion = {int(k): v for k, v in size_conversion.items()}
+
+ self.image_token = tokenizer.image_token
+ self.image_token_id = tokenizer.image_token_id
+ if tokenizer is not None and tokenizer.pad_token is None:
+ tokenizer.pad_token = tokenizer.unk_token
+
+ super().__init__(image_processor, tokenizer, chat_template=chat_template)
+
+ @auto_docstring
+ def __call__(
+ self,
+ text: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput],
+ images: ImageInput | None = None,
+ **kwargs: Unpack[AriaProcessorKwargs],
+ ) -> BatchFeature:
+ r"""
+ Returns:
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
+ - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
+ `None`).
+ - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
+ - **pixel_mask** -- Pixel mask to be fed to a model. Returned when `images` is not `None`.
+ """
+ output_kwargs = self._merge_kwargs(
+ AriaProcessorKwargs,
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
+ **kwargs,
+ )
+
+ if isinstance(text, str):
+ text = [text]
+ elif not isinstance(text, list) and not isinstance(text[0], str):
+ raise TypeError("Invalid input text. Please provide a string, or a list of strings")
+
+ if images is not None:
+ image_inputs = self.image_processor(images, **output_kwargs["images_kwargs"])
+ # expand the image_token according to the num_crops and tokens per image
+ tokens_per_image = self.size_conversion[image_inputs.pixel_values.shape[2]]
+ prompt_strings = []
+ num_crops = image_inputs.pop("num_crops") * tokens_per_image
+ for sample in text:
+ sample = sample.replace(self.tokenizer.image_token, self.tokenizer.image_token * num_crops)
+ prompt_strings.append(sample)
+
+ else:
+ image_inputs = {}
+ prompt_strings = text
+
+ return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None)
+ return_mm_token_type_ids = output_kwargs["text_kwargs"].pop("return_mm_token_type_ids", False)
+ text_inputs = self.tokenizer(prompt_strings, **output_kwargs["text_kwargs"], return_tensors=None)
+ self._check_special_mm_tokens(prompt_strings, text_inputs, modalities=["image"])
+
+ if return_mm_token_type_ids:
+ text_inputs["mm_token_type_ids"] = self.create_mm_token_type_ids(text_inputs["input_ids"])
+ return BatchFeature(data={**text_inputs, **image_inputs}, tensor_type=return_tensors)
+
+ def _get_num_multimodal_tokens(self, image_sizes=None, **kwargs):
+ """
+ Computes the number of placeholder tokens needed for multimodal inputs with the given sizes.
+ Args:
+ image_sizes (`list[list[int]]`, *optional*):
+ The input sizes formatted as (height, width) per each image.
+ Returns:
+ `MultiModalData`: A `MultiModalData` object holding number of tokens per each of the provided
+ input modalities, along with other useful data.
+ """
+
+ vision_data = {}
+ if image_sizes is not None:
+ images_kwargs = AriaProcessorKwargs._defaults.get("images_kwargs", {})
+ images_kwargs.update(kwargs)
+
+ max_size = images_kwargs.get("max_image_size", None) or self.image_processor.max_image_size
+ num_image_patches = [
+ self.image_processor.get_number_of_image_patches(*image_size, images_kwargs)
+ for image_size in image_sizes
+ ]
+ num_image_tokens = [self.size_conversion[max_size] * num_patches for num_patches in num_image_patches]
+ vision_data.update({"num_image_tokens": num_image_tokens, "num_image_patches": num_image_patches})
+
+ return MultiModalData(**vision_data)
+
+ @property
+ def model_input_names(self):
+ tokenizer_input_names = self.tokenizer.model_input_names
+ image_processor_input_names = self.image_processor.model_input_names
+
+ # Remove `num_crops`, it is popped and used only when processing. Make a copy of list when removing
+ # otherwise `self.image_processor.model_input_names` is also modified
+ image_processor_input_names = [name for name in image_processor_input_names if name != "num_crops"]
+ return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
+
+
+class AriaSharedExpertsMLP(LlamaMLP):
+ """
+ Shared Expert MLP for shared experts.
+
+ Unlike routed experts, shared experts process all tokens without routing.
+ This class reconfigures the intermediate size in comparison to the LlamaMLP.
+
+ Args:
+ config (`AriaTextConfig`): Configuration object for the Aria language model.
+ """
+
+ def __init__(self, config: AriaTextConfig):
+ super().__init__(config)
+ self.intermediate_size = config.intermediate_size * config.moe_num_shared_experts
+
+
+class AriaGroupedExpertsGemm(nn.Module):
+ """
+ Grouped GEMM (General Matrix Multiplication) module for efficient expert computation.
+ This module utilizes the grouped_gemm library (https://github.com/fanshiqing/grouped_gemm)
+ for optimized performance. If the grouped_gemm library is not installed, it gracefully
+ falls back to a sequential GEMM implementation, which may be slower but ensures
+ functionality.
+
+ Args:
+ in_features (`int`):
+ Number of input features.
+ out_features (`int`):
+ Number of output features.
+ groups (`int`):
+ Number of expert groups.
+ """
+
+ def __init__(self, in_features, out_features, groups):
+ super().__init__()
+ self.in_features = in_features
+ self.out_features = out_features
+ self.groups = groups
+ self.weight = nn.Parameter(torch.empty(groups, in_features, out_features))
+
+ def forward(self, input, tokens_per_expert):
+ """
+ Perform grouped matrix multiplication.
+
+ Args:
+ input (`torch.Tensor`):
+ Input tensor of shape (num_tokens, in_features).
+ tokens_per_expert (`torch.Tensor`):
+ Number of tokens assigned to each expert.
+
+ Returns:
+ torch.Tensor: Output tensor of shape (num_tokens, out_features).
+ """
+ return sequential_experts_gemm(
+ input,
+ self.weight,
+ tokens_per_expert.cpu(),
+ )
+
+
+class AriaExperts(nn.Module):
+ def __init__(self, config: AriaTextConfig) -> None:
+ super().__init__()
+ self.config = config
+ self.fc1 = AriaGroupedExpertsGemm(config.hidden_size, config.intermediate_size * 2, config.moe_num_experts)
+ self.fc2 = AriaGroupedExpertsGemm(config.intermediate_size, config.hidden_size, config.moe_num_experts)
+
+ def route_tokens_to_experts(self, router_logits):
+ top_logits, top_indices = torch.topk(router_logits, k=self.config.moe_topk, dim=1)
+ scores = nn.functional.softmax(top_logits, dim=-1)
+ return top_indices, scores
+
+ def forward(self, hidden_states, router_logits) -> torch.Tensor:
+ top_k_index, top_k_weights = self.route_tokens_to_experts(router_logits)
+ original_dtype = top_k_index.dtype
+ tokens_per_expert = torch.histc(
+ top_k_index.flatten().to(torch.float32),
+ bins=self.config.moe_num_experts,
+ min=0,
+ max=self.config.moe_num_experts - 1,
+ ).to(original_dtype)
+ indices = top_k_index
+
+ flatten_indices = indices.view(-1)
+ sorted_indices = torch.argsort(flatten_indices)
+ permuted_tokens = hidden_states.index_select(0, sorted_indices // self.config.moe_topk)
+
+ fc1_output = self.fc1(permuted_tokens, tokens_per_expert)
+ projection, gate = torch.chunk(fc1_output, 2, dim=-1)
+ fc1_output = nn.functional.silu(projection) * gate
+ expert_output = self.fc2(fc1_output, tokens_per_expert)
+
+ unpermuted_tokens = torch.zeros(
+ (top_k_weights.shape[0] * self.config.moe_topk, expert_output.size(1)),
+ dtype=expert_output.dtype,
+ device=expert_output.device,
+ )
+ unpermuted_tokens.index_copy_(0, sorted_indices, expert_output)
+ unpermuted_tokens = unpermuted_tokens.view(-1, self.config.moe_topk, expert_output.size(1))
+
+ output = (unpermuted_tokens * top_k_weights.unsqueeze(-1)).sum(dim=1)
+ return output
+
+
+class AriaTextMoELayer(nn.Module):
+ def __init__(self, config: AriaTextConfig):
+ super().__init__()
+ self.router = nn.Linear(config.hidden_size, config.moe_num_experts, bias=False)
+ self.experts = AriaExperts(config)
+ self.shared_experts = AriaSharedExpertsMLP(config)
+ self.config = config
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ original_shape = hidden_states.shape
+ hidden_states = hidden_states.view(-1, hidden_states.size(-1))
+ router_logits = self.router(hidden_states)
+ expert_output = self.experts(hidden_states, router_logits).view(original_shape)
+ shared_expert_output = self.shared_experts(hidden_states.view(original_shape))
+ return expert_output + shared_expert_output
+
+
+class AriaTextAttention(LlamaAttention):
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
+
+
+class AriaTextDecoderLayer(LlamaDecoderLayer):
+ """
+ Aria Text Decoder Layer.
+
+ This class defines a single decoder layer in the language model, incorporating self-attention and Mixture of Experts (MoE) feed-forward network.
+
+ Args:
+ config (`AriaTextConfig`):
+ Configuration object for the text component of the model.
+ layer_idx (`int`):
+ Index of the layer.
+ """
+
+ def __init__(self, config: AriaTextConfig, layer_idx: int):
+ super().__init__(config, layer_idx)
+ self.mlp = AriaTextMoELayer(config)
+
+
+@auto_docstring
+class AriaTextPreTrainedModel(PreTrainedModel):
+ config: AriaTextConfig
+ base_model_prefix = "model"
+ input_modalities = ("image", "text")
+ _no_split_modules = ["AriaTextDecoderLayer", "AriaGroupedExpertsGemm"]
+ supports_gradient_checkpointing = True
+ _skip_keys_device_placement = ["past_key_values"]
+ _supports_flash_attn = True
+ _supports_sdpa = True
+
+ _supports_attention_backend = True
+ _can_record_outputs = {
+ "hidden_states": AriaTextDecoderLayer,
+ "attentions": AriaTextAttention,
+ }
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ super()._init_weights(module)
+ if isinstance(module, AriaGroupedExpertsGemm):
+ init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
+
+
+class AriaPreTrainedModel(LlamaPreTrainedModel):
+ config: AriaConfig
+ base_model_prefix = "model"
+ _can_compile_fullgraph = False # MoE models don't work with torch.compile (dynamic slicing)
+ _supports_attention_backend = True
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ PreTrainedModel._init_weights(self, module)
+ if isinstance(module, AriaProjector):
+ init.trunc_normal_(module.query, std=self.config.initializer_range)
+
+
+class AriaTextModel(LlamaModel):
+ def __init__(self, config: AriaTextConfig):
+ super().__init__(config)
+ self.layers = nn.ModuleList(
+ [AriaTextDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
+ )
+ self.gradient_checkpointing = False
+ self.post_init()
+
+
+class AriaTextForCausalLM(AriaTextPreTrainedModel, LlamaForCausalLM):
+ _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
+
+ def __init__(self, config: AriaTextConfig):
+ super().__init__(config)
+ self.model = AriaTextModel(config)
+ self.vocab_size = config.vocab_size
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(self, **super_kwargs):
+ super().forward(self, **super_kwargs)
+
+
+class AriaCausalLMOutputWithPast(LlavaCausalLMOutputWithPast):
+ pass
+
+
+class AriaModelOutputWithPast(LlavaModelOutputWithPast):
+ pass
+
+
+class AriaModel(LlavaModel):
+ def __init__(self, config: AriaConfig):
+ super().__init__(config)
+ self.multi_modal_projector = AriaProjector(config)
+
+ def _create_patch_attention_mask(self, pixel_mask):
+ if pixel_mask is None:
+ return None
+
+ patches_subgrid = pixel_mask.unfold(
+ dimension=1,
+ size=self.vision_tower.config.patch_size,
+ step=self.vision_tower.config.patch_size,
+ )
+ patches_subgrid = patches_subgrid.unfold(
+ dimension=2,
+ size=self.vision_tower.config.patch_size,
+ step=self.vision_tower.config.patch_size,
+ )
+ return (patches_subgrid.sum(dim=(-1, -2)) > 0).bool()
+
+ def get_image_features(
+ self,
+ pixel_values: torch.FloatTensor,
+ pixel_mask: torch.FloatTensor | None = None,
+ vision_feature_layer: int | list[int] = -1,
+ output_hidden_states: bool | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutputWithPooling:
+ patch_attention_mask = self._create_patch_attention_mask(pixel_mask)
+ image_outputs = self.vision_tower(
+ pixel_values,
+ patch_attention_mask=patch_attention_mask,
+ output_hidden_states=True, # Ignore arg on purpose
+ return_dict=True,
+ **kwargs,
+ )
+ image_attn_mask = None
+ if patch_attention_mask is not None:
+ flattened_mask = patch_attention_mask.flatten(1)
+ image_attn_mask = torch.logical_not(flattened_mask)
+
+ selected_image_feature = image_outputs.hidden_states[vision_feature_layer]
+ image_outputs.pooler_output = self.multi_modal_projector(selected_image_feature, attn_mask=image_attn_mask)
+
+ return image_outputs
+
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ pixel_values: torch.FloatTensor | None = None,
+ pixel_mask: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ use_cache: bool | None = None,
+ **kwargs: Unpack[FlashAttentionKwargs],
+ ) -> tuple | AriaModelOutputWithPast:
+ if inputs_embeds is None:
+ inputs_embeds = self.get_input_embeddings()(input_ids)
+
+ # 2. Merge text and images
+ if pixel_values is not None and inputs_embeds.shape[1] != 1:
+ image_features = self.get_image_features(
+ pixel_values=pixel_values,
+ pixel_mask=pixel_mask,
+ vision_feature_layer=self.config.vision_feature_layer,
+ return_dict=True,
+ ).pooler_output
+ image_features = image_features.to(inputs_embeds.device, inputs_embeds.dtype)
+ special_image_mask = self.get_placeholder_mask(
+ input_ids, inputs_embeds=inputs_embeds, image_features=image_features
+ )
+ inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)
+
+ outputs = self.language_model(
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ **kwargs,
+ )
+
+ return AriaModelOutputWithPast(
+ last_hidden_state=outputs.last_hidden_state,
+ past_key_values=outputs.past_key_values if use_cache else None,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ image_hidden_states=image_features if pixel_values is not None else None,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ Aria model for conditional generation tasks.
+
+ This model combines a vision tower, a multi-modal projector, and a language model
+ to perform tasks that involve both image and text inputs.
+ """
+)
+class AriaForConditionalGeneration(LlavaForConditionalGeneration):
+ _tied_weights_keys = {"lm_head.weight": "model.language_model.embed_tokens.weight"}
+
+ @auto_docstring
+ def get_image_features(
+ self,
+ pixel_values: torch.FloatTensor,
+ pixel_mask: torch.FloatTensor | None = None,
+ vision_feature_layer: int | list[int] = -1,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutputWithPooling:
+ return self.model.get_image_features(
+ pixel_values=pixel_values,
+ pixel_mask=pixel_mask,
+ vision_feature_layer=vision_feature_layer,
+ **kwargs,
+ )
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ pixel_values: torch.FloatTensor | None = None,
+ pixel_mask: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ use_cache: bool | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | AriaCausalLMOutputWithPast:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
+ config.vocab_size]` or `model.image_token_id` (where `model` is your instance of `AriaForConditionalGeneration`).
+ Tokens with indices set to `model.image_token_id` are ignored (masked), the loss is only
+ computed for the tokens with labels in `[0, ..., config.vocab_size]`.
+
+ Example:
+
+ ```python
+ >>> import httpx
+ >>> from io import BytesIO
+ >>> import torch
+ >>> from PIL import Image
+ >>> from io import BytesIO
+
+ >>> from transformers import AutoProcessor, AutoModel
+ >>> from transformers.image_utils import load_image
+
+ >>> # Note that passing the image urls (instead of the actual pil images) to the processor is also possible
+ >>> image1 = load_image("https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg")
+ >>> image2 = load_image("https://cdn.britannica.com/59/94459-050-DBA42467/Skyline-Chicago.jpg")
+ >>> image3 = load_image("https://cdn.britannica.com/68/170868-050-8DDE8263/Golden-Gate-Bridge-San-Francisco.jpg")
+
+ >>> processor = AutoProcessor.from_pretrained("Rhymes-AI/Aria")
+ >>> model = AutoModel.from_pretrained("Rhymes-AI/Aria", dtype=torch.bfloat16, device_map="auto")
+
+ >>> # Create inputs
+ >>> messages = [
+ ... {
+ ... "role": "user",
+ ... "content": [
+ ... {"type": "image"},
+ ... {"type": "text", "text": "In this image, we can see the city of New York, and more specifically the Statue of Liberty."},
+ ... {"type": "image"},
+ ... {"type": "text", "text": "What can we see in this image?"},
+ ... ]
+ ... },
+ ... {
+ ... "role": "user",
+ ... "content": [
+ ... {"type": "image"},
+ ... {"type": "text", "text": "In which city is that bridge located?"},
+ ... ]
+ ... }
+ ... ]
+
+ >>> prompts = [processor.apply_chat_template([message], add_generation_prompt=True) for message in messages]
+ >>> images = [[image1, image2], [image3]]
+ >>> inputs = processor(text=prompts, images=images, padding=True, return_tensors="pt").to(model.device)
+
+ >>> # Generate
+ >>> generated_ids = model.generate(**inputs, max_new_tokens=256)
+ >>> generated_texts = processor.batch_decode(generated_ids, skip_special_tokens=True)
+
+ >>> print(generated_texts[0])
+ Assistant: There are buildings, trees, lights, and water visible in this image.
+
+ >>> print(generated_texts[1])
+ Assistant: The bridge is in San Francisco.
+ ```"""
+ outputs = self.model(
+ input_ids=input_ids,
+ pixel_values=pixel_values,
+ pixel_mask=pixel_mask,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ **kwargs,
+ )
+
+ hidden_states = outputs[0]
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(
+ logits=logits, labels=labels, vocab_size=self.config.text_config.vocab_size, **kwargs
+ )
+
+ return AriaCausalLMOutputWithPast(
+ loss=loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+ def prepare_inputs_for_generation(
+ self,
+ input_ids,
+ past_key_values=None,
+ inputs_embeds=None,
+ pixel_values=None,
+ pixel_mask=None,
+ attention_mask=None,
+ logits_to_keep=None,
+ is_first_iteration=False,
+ **kwargs,
+ ):
+ model_inputs = super().prepare_inputs_for_generation(
+ input_ids,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ logits_to_keep=logits_to_keep,
+ is_first_iteration=is_first_iteration,
+ **kwargs,
+ )
+
+ if is_first_iteration or not kwargs.get("use_cache", True):
+ # Pixel values are used only in the first iteration if available
+ # In subsequent iterations, they are already merged with text and cached
+ # NOTE: first iteration doesn't have to be prefill, it can be the first
+ # iteration with a question and cached system prompt (continue generate from cache)
+ model_inputs["pixel_values"] = pixel_values
+ model_inputs["pixel_mask"] = pixel_mask
+
+ return model_inputs
+
+
+__all__ = [
+ "AriaConfig",
+ "AriaTextConfig",
+ "AriaImageProcessor",
+ "AriaProcessor",
+ "AriaForConditionalGeneration",
+ "AriaPreTrainedModel",
+ "AriaTextPreTrainedModel",
+ "AriaTextModel",
+ "AriaModel",
+ "AriaTextForCausalLM",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/processing_aria.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/processing_aria.py
new file mode 100644
index 0000000000000000000000000000000000000000..8c9fa8188c81a9cf725d8938e33e5ec4a6be1a66
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/aria/processing_aria.py
@@ -0,0 +1,177 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/aria/modular_aria.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_aria.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2024 The Rhymes-AI Teams Authors and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from ...image_processing_utils import BatchFeature
+from ...image_utils import ImageInput
+from ...processing_utils import ImagesKwargs, MultiModalData, ProcessingKwargs, ProcessorMixin, Unpack
+from ...tokenization_python import PreTokenizedInput, TextInput
+from ...utils import TensorType, auto_docstring
+from ..auto import AutoTokenizer
+
+
+class AriaImagesKwargs(ImagesKwargs, total=False):
+ """
+ split_image (`bool`, *optional*, defaults to `False`):
+ Whether to split large images into multiple crops. When enabled, images exceeding the maximum size are
+ divided into overlapping crops that are processed separately and then combined. This allows processing
+ of very high-resolution images that exceed the model's input size limits.
+ max_image_size (`int`, *optional*, defaults to `980`):
+ Maximum image size (in pixels) for a single image crop. Images larger than this will be split into
+ multiple crops when `split_image=True`, or resized if splitting is disabled. This parameter controls
+ the maximum resolution of individual image patches processed by the model.
+ min_image_size (`int`, *optional*):
+ Minimum image size (in pixels) for a single image crop. Images smaller than this will be upscaled to
+ meet the minimum requirement. If not specified, images are processed at their original size (subject
+ to the maximum size constraint).
+ """
+
+ split_image: bool
+ max_image_size: int
+ min_image_size: int
+
+
+class AriaProcessorKwargs(ProcessingKwargs, total=False):
+ images_kwargs: AriaImagesKwargs
+
+ _defaults = {
+ "text_kwargs": {
+ "padding": False,
+ "return_mm_token_type_ids": False,
+ },
+ "images_kwargs": {
+ "max_image_size": 980,
+ "split_image": False,
+ },
+ "return_tensors": TensorType.PYTORCH,
+ }
+
+
+@auto_docstring
+class AriaProcessor(ProcessorMixin):
+ def __init__(
+ self,
+ image_processor=None,
+ tokenizer: AutoTokenizer | str = None,
+ chat_template: str | None = None,
+ size_conversion: dict[float | int, int] | None = None,
+ ):
+ r"""
+ size_conversion (`Dict`, *optional*):
+ A dictionary indicating size conversions for images.
+ """
+ if size_conversion is None:
+ size_conversion = {490: 128, 980: 256}
+ self.size_conversion = {int(k): v for k, v in size_conversion.items()}
+
+ self.image_token = tokenizer.image_token
+ self.image_token_id = tokenizer.image_token_id
+ if tokenizer is not None and tokenizer.pad_token is None:
+ tokenizer.pad_token = tokenizer.unk_token
+
+ super().__init__(image_processor, tokenizer, chat_template=chat_template)
+
+ @auto_docstring
+ def __call__(
+ self,
+ text: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput],
+ images: ImageInput | None = None,
+ **kwargs: Unpack[AriaProcessorKwargs],
+ ) -> BatchFeature:
+ r"""
+ Returns:
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
+ - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
+ `None`).
+ - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
+ - **pixel_mask** -- Pixel mask to be fed to a model. Returned when `images` is not `None`.
+ """
+ output_kwargs = self._merge_kwargs(
+ AriaProcessorKwargs,
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
+ **kwargs,
+ )
+
+ if isinstance(text, str):
+ text = [text]
+ elif not isinstance(text, list) and not isinstance(text[0], str):
+ raise TypeError("Invalid input text. Please provide a string, or a list of strings")
+
+ if images is not None:
+ image_inputs = self.image_processor(images, **output_kwargs["images_kwargs"])
+ # expand the image_token according to the num_crops and tokens per image
+ tokens_per_image = self.size_conversion[image_inputs.pixel_values.shape[2]]
+ prompt_strings = []
+ num_crops = image_inputs.pop("num_crops") * tokens_per_image
+ for sample in text:
+ sample = sample.replace(self.tokenizer.image_token, self.tokenizer.image_token * num_crops)
+ prompt_strings.append(sample)
+
+ else:
+ image_inputs = {}
+ prompt_strings = text
+
+ return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None)
+ return_mm_token_type_ids = output_kwargs["text_kwargs"].pop("return_mm_token_type_ids", False)
+ text_inputs = self.tokenizer(prompt_strings, **output_kwargs["text_kwargs"], return_tensors=None)
+ self._check_special_mm_tokens(prompt_strings, text_inputs, modalities=["image"])
+
+ if return_mm_token_type_ids:
+ text_inputs["mm_token_type_ids"] = self.create_mm_token_type_ids(text_inputs["input_ids"])
+ return BatchFeature(data={**text_inputs, **image_inputs}, tensor_type=return_tensors)
+
+ def _get_num_multimodal_tokens(self, image_sizes=None, **kwargs):
+ """
+ Computes the number of placeholder tokens needed for multimodal inputs with the given sizes.
+ Args:
+ image_sizes (`list[list[int]]`, *optional*):
+ The input sizes formatted as (height, width) per each image.
+ Returns:
+ `MultiModalData`: A `MultiModalData` object holding number of tokens per each of the provided
+ input modalities, along with other useful data.
+ """
+
+ vision_data = {}
+ if image_sizes is not None:
+ images_kwargs = AriaProcessorKwargs._defaults.get("images_kwargs", {})
+ images_kwargs.update(kwargs)
+
+ max_size = images_kwargs.get("max_image_size", None) or self.image_processor.max_image_size
+ num_image_patches = [
+ self.image_processor.get_number_of_image_patches(*image_size, images_kwargs)
+ for image_size in image_sizes
+ ]
+ num_image_tokens = [self.size_conversion[max_size] * num_patches for num_patches in num_image_patches]
+ vision_data.update({"num_image_tokens": num_image_tokens, "num_image_patches": num_image_patches})
+
+ return MultiModalData(**vision_data)
+
+ @property
+ def model_input_names(self):
+ tokenizer_input_names = self.tokenizer.model_input_names
+ image_processor_input_names = self.image_processor.model_input_names
+
+ # Remove `num_crops`, it is popped and used only when processing. Make a copy of list when removing
+ # otherwise `self.image_processor.model_input_names` is also modified
+ image_processor_input_names = [name for name in image_processor_input_names if name != "num_crops"]
+ return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
+
+
+__all__ = ["AriaProcessor"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/autoformer/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/autoformer/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..78f23566d65449af9fed646ca6a5c82ccfdd17f7
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/autoformer/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/autoformer/__pycache__/configuration_autoformer.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/autoformer/__pycache__/configuration_autoformer.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3485a8c074a8afe7d1f7d1d7dfa4e56c59a87a8b
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/autoformer/__pycache__/configuration_autoformer.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bert/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bert/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..54a46312ad9153f2d8c3bf1a3029a3254efab791
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bert/__init__.py
@@ -0,0 +1,28 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_bert import *
+ from .modeling_bert import *
+ from .tokenization_bert import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bert/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bert/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0b6386ec59b5b7b814a828d34c5d980d4587ac12
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bert/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bert/__pycache__/configuration_bert.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bert/__pycache__/configuration_bert.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..997b0992bf58ddfcf6914e83c208bc723e1f5f76
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bert/__pycache__/configuration_bert.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bert/__pycache__/modeling_bert.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bert/__pycache__/modeling_bert.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..085bfae955b75bea61cee718a0fc79fcbd78ce9c
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bert/__pycache__/modeling_bert.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bert/__pycache__/tokenization_bert.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bert/__pycache__/tokenization_bert.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c8380f958214511eae29587edc6239b211c022e3
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bert/__pycache__/tokenization_bert.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bert/__pycache__/tokenization_bert_legacy.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bert/__pycache__/tokenization_bert_legacy.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d1499ee7a30ada0f2e9c99621ae8a47fb8c38ff0
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bert/__pycache__/tokenization_bert_legacy.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bert/configuration_bert.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bert/configuration_bert.py
new file mode 100644
index 0000000000000000000000000000000000000000..1e3f288a820d0001fe5b2f7b3684f91a9b03cd2e
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bert/configuration_bert.py
@@ -0,0 +1,66 @@
+# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
+# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""BERT model configuration"""
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring
+
+
+@auto_docstring(checkpoint="google-bert/bert-base-uncased")
+@strict
+class BertConfig(PreTrainedConfig):
+ r"""
+ Examples:
+
+ ```python
+ >>> from transformers import BertConfig, BertModel
+
+ >>> # Initializing a BERT google-bert/bert-base-uncased style configuration
+ >>> configuration = BertConfig()
+
+ >>> # Initializing a model (with random weights) from the google-bert/bert-base-uncased style configuration
+ >>> model = BertModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "bert"
+
+ vocab_size: int = 30522
+ hidden_size: int = 768
+ num_hidden_layers: int = 12
+ num_attention_heads: int = 12
+ intermediate_size: int = 3072
+ hidden_act: str = "gelu"
+ hidden_dropout_prob: float | int = 0.1
+ attention_probs_dropout_prob: float | int = 0.1
+ max_position_embeddings: int = 512
+ type_vocab_size: int = 2
+ initializer_range: float = 0.02
+ layer_norm_eps: float = 1e-12
+ pad_token_id: int | None = 0
+ use_cache: bool = True
+ classifier_dropout: float | int | None = None
+ is_decoder: bool = False
+ add_cross_attention: bool = False
+ bos_token_id: int | None = None
+ eos_token_id: int | list[int] | None = None
+ tie_word_embeddings: bool = True
+
+
+__all__ = ["BertConfig"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bert/modeling_bert.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bert/modeling_bert.py
new file mode 100644
index 0000000000000000000000000000000000000000..18b5ba223fa06f8fb758e9af3eaa765c117cc718
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bert/modeling_bert.py
@@ -0,0 +1,1394 @@
+# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
+# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch BERT model."""
+
+from collections.abc import Callable
+from dataclasses import dataclass
+
+import torch
+from torch import nn
+from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...cache_utils import Cache, DynamicCache, EncoderDecoderCache
+from ...generation import GenerationMixin
+from ...masking_utils import create_bidirectional_mask, create_causal_mask
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import (
+ BaseModelOutputWithPastAndCrossAttentions,
+ BaseModelOutputWithPoolingAndCrossAttentions,
+ CausalLMOutputWithCrossAttentions,
+ MaskedLMOutput,
+ MultipleChoiceModelOutput,
+ NextSentencePredictorOutput,
+ QuestionAnsweringModelOutput,
+ SequenceClassifierOutput,
+ TokenClassifierOutput,
+)
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
+from ...processing_utils import Unpack
+from ...pytorch_utils import apply_chunking_to_forward
+from ...utils import ModelOutput, TransformersKwargs, auto_docstring, logging
+from ...utils.generic import can_return_tuple, merge_with_config_defaults
+from ...utils.output_capturing import capture_outputs
+from .configuration_bert import BertConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+class BertEmbeddings(nn.Module):
+ """Construct the embeddings from word, position and token_type embeddings."""
+
+ def __init__(self, config):
+ super().__init__()
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
+ self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
+ self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
+
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
+ self.register_buffer(
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
+ )
+ self.register_buffer(
+ "token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False
+ )
+
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ past_key_values_length: int = 0,
+ ) -> torch.Tensor:
+ if input_ids is not None:
+ input_shape = input_ids.size()
+ else:
+ input_shape = inputs_embeds.size()[:-1]
+
+ batch_size, seq_length = input_shape
+
+ if position_ids is None:
+ position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length]
+
+ # Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
+ # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
+ # issue #5664
+ if token_type_ids is None:
+ if hasattr(self, "token_type_ids"):
+ # NOTE: We assume either pos ids to have bsz == 1 (broadcastable) or bsz == effective bsz (input_shape[0])
+ buffered_token_type_ids = self.token_type_ids.expand(position_ids.shape[0], -1)
+ buffered_token_type_ids = torch.gather(buffered_token_type_ids, dim=1, index=position_ids)
+ token_type_ids = buffered_token_type_ids.expand(batch_size, seq_length)
+ else:
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
+
+ if inputs_embeds is None:
+ inputs_embeds = self.word_embeddings(input_ids)
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
+ embeddings = inputs_embeds + token_type_embeddings
+
+ position_embeddings = self.position_embeddings(position_ids)
+ embeddings = embeddings + position_embeddings
+
+ embeddings = self.LayerNorm(embeddings)
+ embeddings = self.dropout(embeddings)
+ return embeddings
+
+
+def eager_attention_forward(
+ module: nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: torch.Tensor | None,
+ scaling: float | None = None,
+ dropout: float = 0.0,
+ **kwargs: Unpack[TransformersKwargs],
+):
+ if scaling is None:
+ scaling = query.size(-1) ** -0.5
+
+ # Take the dot product between "query" and "key" to get the raw attention scores.
+ attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
+
+ if attention_mask is not None:
+ attn_weights = attn_weights + attention_mask
+
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
+
+ attn_output = torch.matmul(attn_weights, value)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+
+ return attn_output, attn_weights
+
+
+class BertSelfAttention(nn.Module):
+ def __init__(self, config, is_causal=False, layer_idx=None):
+ super().__init__()
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
+ raise ValueError(
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
+ f"heads ({config.num_attention_heads})"
+ )
+ self.config = config
+
+ self.num_attention_heads = config.num_attention_heads
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
+ self.scaling = self.attention_head_size**-0.5
+
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
+
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
+
+ self.is_decoder = config.is_decoder
+ self.is_causal = is_causal
+ self.layer_idx = layer_idx
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.FloatTensor | None = None,
+ past_key_values: Cache | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor]:
+ input_shape = hidden_states.shape[:-1]
+ hidden_shape = (*input_shape, -1, self.attention_head_size)
+
+ # get all proj
+ query_layer = self.query(hidden_states).view(*hidden_shape).transpose(1, 2)
+ key_layer = self.key(hidden_states).view(*hidden_shape).transpose(1, 2)
+ value_layer = self.value(hidden_states).view(*hidden_shape).transpose(1, 2)
+
+ if past_key_values is not None:
+ # decoder-only bert can have a simple dynamic cache for example
+ current_past_key_values = past_key_values
+ if isinstance(past_key_values, EncoderDecoderCache):
+ current_past_key_values = past_key_values.self_attention_cache
+
+ # save all key/value_layer to cache to be re-used for fast auto-regressive generation
+ key_layer, value_layer = current_past_key_values.update(key_layer, value_layer, self.layer_idx)
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_layer,
+ key_layer,
+ value_layer,
+ attention_mask,
+ dropout=0.0 if not self.training else self.dropout.p,
+ scaling=self.scaling,
+ **kwargs,
+ )
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ return attn_output, attn_weights
+
+
+class BertCrossAttention(nn.Module):
+ def __init__(self, config, is_causal=False, layer_idx=None):
+ super().__init__()
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
+ raise ValueError(
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
+ f"heads ({config.num_attention_heads})"
+ )
+ self.config = config
+
+ self.num_attention_heads = config.num_attention_heads
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
+ self.scaling = self.attention_head_size**-0.5
+
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
+
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
+
+ self.is_causal = is_causal
+ self.layer_idx = layer_idx
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ past_key_values: EncoderDecoderCache | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor]:
+ # determine input shapes
+ input_shape = hidden_states.shape[:-1]
+
+ hidden_shape = (*input_shape, -1, self.attention_head_size)
+
+ # get query proj
+ query_layer = self.query(hidden_states).view(hidden_shape).transpose(1, 2)
+
+ is_updated = past_key_values.is_updated.get(self.layer_idx) if past_key_values is not None else False
+ if past_key_values is not None and is_updated:
+ # reuse k,v, cross_attentions
+ key_layer = past_key_values.cross_attention_cache.layers[self.layer_idx].keys
+ value_layer = past_key_values.cross_attention_cache.layers[self.layer_idx].values
+ else:
+ kv_shape = (*encoder_hidden_states.shape[:-1], -1, self.attention_head_size)
+ key_layer = self.key(encoder_hidden_states).view(kv_shape).transpose(1, 2)
+ value_layer = self.value(encoder_hidden_states).view(kv_shape).transpose(1, 2)
+
+ if past_key_values is not None:
+ # save all states to the cache
+ key_layer, value_layer = past_key_values.cross_attention_cache.update(
+ key_layer, value_layer, self.layer_idx
+ )
+ # set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls
+ past_key_values.is_updated[self.layer_idx] = True
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_layer,
+ key_layer,
+ value_layer,
+ attention_mask,
+ dropout=0.0 if not self.training else self.dropout.p,
+ scaling=self.scaling,
+ **kwargs,
+ )
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ return attn_output, attn_weights
+
+
+class BertSelfOutput(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
+ return hidden_states
+
+
+class BertAttention(nn.Module):
+ def __init__(self, config, is_causal=False, layer_idx=None, is_cross_attention=False):
+ super().__init__()
+ self.is_cross_attention = is_cross_attention
+ attention_class = BertCrossAttention if is_cross_attention else BertSelfAttention
+ self.self = attention_class(config, is_causal=is_causal, layer_idx=layer_idx)
+ self.output = BertSelfOutput(config)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.FloatTensor | None = None,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ encoder_attention_mask: torch.FloatTensor | None = None,
+ past_key_values: Cache | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor]:
+ attention_mask = attention_mask if not self.is_cross_attention else encoder_attention_mask
+ attention_output, attn_weights = self.self(
+ hidden_states,
+ encoder_hidden_states=encoder_hidden_states,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ **kwargs,
+ )
+ attention_output = self.output(attention_output, hidden_states)
+ return attention_output, attn_weights
+
+
+class BertIntermediate(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
+ if isinstance(config.hidden_act, str):
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
+ else:
+ self.intermediate_act_fn = config.hidden_act
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.intermediate_act_fn(hidden_states)
+ return hidden_states
+
+
+class BertOutput(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
+ return hidden_states
+
+
+class BertLayer(GradientCheckpointingLayer):
+ def __init__(self, config, layer_idx=None):
+ super().__init__()
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
+ self.seq_len_dim = 1
+ self.attention = BertAttention(config, is_causal=config.is_decoder, layer_idx=layer_idx)
+ self.is_decoder = config.is_decoder
+ self.add_cross_attention = config.add_cross_attention
+ if self.add_cross_attention:
+ if not self.is_decoder:
+ raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
+ self.crossattention = BertAttention(
+ config,
+ is_causal=False,
+ layer_idx=layer_idx,
+ is_cross_attention=True,
+ )
+ self.intermediate = BertIntermediate(config)
+ self.output = BertOutput(config)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.FloatTensor | None = None,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ encoder_attention_mask: torch.FloatTensor | None = None,
+ past_key_values: Cache | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.Tensor:
+ self_attention_output, _ = self.attention(
+ hidden_states,
+ attention_mask,
+ past_key_values=past_key_values,
+ **kwargs,
+ )
+ attention_output = self_attention_output
+
+ if self.is_decoder and encoder_hidden_states is not None:
+ if not hasattr(self, "crossattention"):
+ raise ValueError(
+ f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
+ " by setting `config.add_cross_attention=True`"
+ )
+
+ cross_attention_output, _ = self.crossattention(
+ self_attention_output,
+ None, # attention_mask
+ encoder_hidden_states,
+ encoder_attention_mask,
+ past_key_values=past_key_values,
+ **kwargs,
+ )
+ attention_output = cross_attention_output
+
+ layer_output = apply_chunking_to_forward(
+ self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
+ )
+ return layer_output
+
+ def feed_forward_chunk(self, attention_output):
+ intermediate_output = self.intermediate(attention_output)
+ layer_output = self.output(intermediate_output, attention_output)
+ return layer_output
+
+
+class BertEncoder(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.layer = nn.ModuleList([BertLayer(config, layer_idx=i) for i in range(config.num_hidden_layers)])
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.FloatTensor | None = None,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ encoder_attention_mask: torch.FloatTensor | None = None,
+ past_key_values: Cache | None = None,
+ use_cache: bool | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | BaseModelOutputWithPastAndCrossAttentions:
+ for i, layer_module in enumerate(self.layer):
+ hidden_states = layer_module(
+ hidden_states,
+ attention_mask,
+ encoder_hidden_states, # as a positional argument for gradient checkpointing
+ encoder_attention_mask=encoder_attention_mask,
+ past_key_values=past_key_values,
+ **kwargs,
+ )
+
+ return BaseModelOutputWithPastAndCrossAttentions(
+ last_hidden_state=hidden_states,
+ past_key_values=past_key_values if use_cache else None,
+ )
+
+
+class BertPooler(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.activation = nn.Tanh()
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ # We "pool" the model by simply taking the hidden state corresponding
+ # to the first token.
+ first_token_tensor = hidden_states[:, 0]
+ pooled_output = self.dense(first_token_tensor)
+ pooled_output = self.activation(pooled_output)
+ return pooled_output
+
+
+class BertPredictionHeadTransform(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ if isinstance(config.hidden_act, str):
+ self.transform_act_fn = ACT2FN[config.hidden_act]
+ else:
+ self.transform_act_fn = config.hidden_act
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.transform_act_fn(hidden_states)
+ hidden_states = self.LayerNorm(hidden_states)
+ return hidden_states
+
+
+class BertLMPredictionHead(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.transform = BertPredictionHeadTransform(config)
+
+ # The output weights are the same as the input embeddings, but there is
+ # an output-only bias for each token.
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=True)
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
+
+ def forward(self, hidden_states):
+ hidden_states = self.transform(hidden_states)
+ hidden_states = self.decoder(hidden_states)
+ return hidden_states
+
+
+class BertOnlyMLMHead(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.predictions = BertLMPredictionHead(config)
+
+ def forward(self, sequence_output: torch.Tensor) -> torch.Tensor:
+ prediction_scores = self.predictions(sequence_output)
+ return prediction_scores
+
+
+class BertOnlyNSPHead(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.seq_relationship = nn.Linear(config.hidden_size, 2)
+
+ def forward(self, pooled_output):
+ seq_relationship_score = self.seq_relationship(pooled_output)
+ return seq_relationship_score
+
+
+class BertPreTrainingHeads(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.predictions = BertLMPredictionHead(config)
+ self.seq_relationship = nn.Linear(config.hidden_size, 2)
+
+ def forward(self, sequence_output, pooled_output):
+ prediction_scores = self.predictions(sequence_output)
+ seq_relationship_score = self.seq_relationship(pooled_output)
+ return prediction_scores, seq_relationship_score
+
+
+@auto_docstring
+class BertPreTrainedModel(PreTrainedModel):
+ config_class = BertConfig
+ base_model_prefix = "bert"
+ supports_gradient_checkpointing = True
+ _supports_flash_attn = True
+ _supports_sdpa = True
+ _supports_flex_attn = True
+ _supports_attention_backend = True
+ _can_record_outputs = {
+ "hidden_states": BertLayer,
+ "attentions": BertSelfAttention,
+ "cross_attentions": BertCrossAttention,
+ }
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ """Initialize the weights"""
+ super()._init_weights(module)
+ if isinstance(module, BertLMPredictionHead):
+ init.zeros_(module.bias)
+ elif isinstance(module, BertEmbeddings):
+ init.copy_(module.position_ids, torch.arange(module.position_ids.shape[-1]).expand((1, -1)))
+ init.zeros_(module.token_type_ids)
+
+
+@auto_docstring(
+ custom_intro="""
+ Output type of [`BertForPreTraining`].
+ """
+)
+@dataclass
+class BertForPreTrainingOutput(ModelOutput):
+ r"""
+ loss (*optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
+ Total loss as the sum of the masked language modeling loss and the next sequence prediction
+ (classification) loss.
+ prediction_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
+ seq_relationship_logits (`torch.FloatTensor` of shape `(batch_size, 2)`):
+ Prediction scores of the next sequence prediction (classification) head (scores of True/False continuation
+ before SoftMax).
+ """
+
+ loss: torch.FloatTensor | None = None
+ prediction_logits: torch.FloatTensor | None = None
+ seq_relationship_logits: torch.FloatTensor | None = None
+ hidden_states: tuple[torch.FloatTensor] | None = None
+ attentions: tuple[torch.FloatTensor] | None = None
+
+
+@auto_docstring(
+ custom_intro="""
+ The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
+ cross-attention is added between the self-attention layers, following the architecture described in [Attention is
+ all you need](https://huggingface.co/papers/1706.03762) by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
+ Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
+
+ To behave as an decoder the model needs to be initialized with the `is_decoder` argument of the configuration set
+ to `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and
+ `add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass.
+ """
+)
+class BertModel(BertPreTrainedModel):
+ _no_split_modules = ["BertEmbeddings", "BertLayer"]
+
+ def __init__(self, config, add_pooling_layer=True):
+ r"""
+ add_pooling_layer (bool, *optional*, defaults to `True`):
+ Whether to add a pooling layer
+ """
+ super().__init__(config)
+ self.config = config
+ self.gradient_checkpointing = False
+
+ self.embeddings = BertEmbeddings(config)
+ self.encoder = BertEncoder(config)
+
+ self.pooler = BertPooler(config) if add_pooling_layer else None
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.embeddings.word_embeddings
+
+ def set_input_embeddings(self, value):
+ self.embeddings.word_embeddings = value
+
+ @merge_with_config_defaults
+ @capture_outputs
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ token_type_ids: torch.Tensor | None = None,
+ position_ids: torch.Tensor | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ encoder_hidden_states: torch.Tensor | None = None,
+ encoder_attention_mask: torch.Tensor | None = None,
+ past_key_values: Cache | None = None,
+ use_cache: bool | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | BaseModelOutputWithPoolingAndCrossAttentions:
+ if (input_ids is None) ^ (inputs_embeds is not None):
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
+
+ if self.config.is_decoder:
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
+ else:
+ use_cache = False
+
+ if use_cache and past_key_values is None:
+ past_key_values = (
+ EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache(config=self.config))
+ if encoder_hidden_states is not None or self.config.is_encoder_decoder
+ else DynamicCache(config=self.config)
+ )
+
+ past_key_values_length = past_key_values.get_seq_length() if past_key_values is not None else 0
+
+ embedding_output = self.embeddings(
+ input_ids=input_ids,
+ position_ids=position_ids,
+ token_type_ids=token_type_ids,
+ inputs_embeds=inputs_embeds,
+ past_key_values_length=past_key_values_length,
+ )
+
+ attention_mask, encoder_attention_mask = self._create_attention_masks(
+ attention_mask=attention_mask,
+ encoder_attention_mask=encoder_attention_mask,
+ embedding_output=embedding_output,
+ encoder_hidden_states=encoder_hidden_states,
+ past_key_values=past_key_values,
+ )
+
+ encoder_outputs = self.encoder(
+ embedding_output,
+ attention_mask=attention_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ position_ids=position_ids,
+ **kwargs,
+ )
+ sequence_output = encoder_outputs.last_hidden_state
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
+
+ return BaseModelOutputWithPoolingAndCrossAttentions(
+ last_hidden_state=sequence_output,
+ pooler_output=pooled_output,
+ past_key_values=encoder_outputs.past_key_values,
+ )
+
+ def _create_attention_masks(
+ self,
+ attention_mask,
+ encoder_attention_mask,
+ embedding_output,
+ encoder_hidden_states,
+ past_key_values,
+ ):
+ if self.config.is_decoder:
+ attention_mask = create_causal_mask(
+ config=self.config,
+ inputs_embeds=embedding_output,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ )
+ else:
+ attention_mask = create_bidirectional_mask(
+ config=self.config,
+ inputs_embeds=embedding_output,
+ attention_mask=attention_mask,
+ )
+
+ if encoder_attention_mask is not None:
+ encoder_attention_mask = create_bidirectional_mask(
+ config=self.config,
+ inputs_embeds=embedding_output,
+ attention_mask=encoder_attention_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ )
+
+ return attention_mask, encoder_attention_mask
+
+
+@auto_docstring(
+ custom_intro="""
+ Bert Model with two heads on top as done during the pretraining: a `masked language modeling` head and a `next
+ sentence prediction (classification)` head.
+ """
+)
+class BertForPreTraining(BertPreTrainedModel):
+ _tied_weights_keys = {
+ "cls.predictions.decoder.weight": "bert.embeddings.word_embeddings.weight",
+ "cls.predictions.decoder.bias": "cls.predictions.bias",
+ }
+
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.bert = BertModel(config)
+ self.cls = BertPreTrainingHeads(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_output_embeddings(self):
+ return self.cls.predictions.decoder
+
+ def set_output_embeddings(self, new_embeddings):
+ self.cls.predictions.decoder = new_embeddings
+ self.cls.predictions.bias = new_embeddings.bias
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ token_type_ids: torch.Tensor | None = None,
+ position_ids: torch.Tensor | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ labels: torch.Tensor | None = None,
+ next_sentence_label: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | BertForPreTrainingOutput:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked),
+ the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
+ next_sentence_label (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the next sequence prediction (classification) loss. Input should be a sequence
+ pair (see `input_ids` docstring) Indices should be in `[0, 1]`:
+
+ - 0 indicates sequence B is a continuation of sequence A,
+ - 1 indicates sequence B is a random sequence.
+
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, BertForPreTraining
+ >>> import torch
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
+ >>> model = BertForPreTraining.from_pretrained("google-bert/bert-base-uncased")
+
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
+ >>> outputs = model(**inputs)
+
+ >>> prediction_logits = outputs.prediction_logits
+ >>> seq_relationship_logits = outputs.seq_relationship_logits
+ ```
+ """
+ outputs = self.bert(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ return_dict=True,
+ **kwargs,
+ )
+
+ sequence_output, pooled_output = outputs[:2]
+ prediction_scores, seq_relationship_score = self.cls(sequence_output, pooled_output)
+
+ total_loss = None
+ if labels is not None and next_sentence_label is not None:
+ loss_fct = CrossEntropyLoss()
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
+ next_sentence_loss = loss_fct(seq_relationship_score.view(-1, 2), next_sentence_label.view(-1))
+ total_loss = masked_lm_loss + next_sentence_loss
+
+ return BertForPreTrainingOutput(
+ loss=total_loss,
+ prediction_logits=prediction_scores,
+ seq_relationship_logits=seq_relationship_score,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ Bert Model with a `language modeling` head on top for CLM fine-tuning.
+ """
+)
+class BertLMHeadModel(BertPreTrainedModel, GenerationMixin):
+ _tied_weights_keys = {
+ "cls.predictions.decoder.weight": "bert.embeddings.word_embeddings.weight",
+ "cls.predictions.decoder.bias": "cls.predictions.bias",
+ }
+
+ def __init__(self, config):
+ super().__init__(config)
+
+ if not config.is_decoder:
+ logger.warning("If you want to use `BertLMHeadModel` as a standalone, add `is_decoder=True.`")
+
+ self.bert = BertModel(config, add_pooling_layer=False)
+ self.cls = BertOnlyMLMHead(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_output_embeddings(self):
+ return self.cls.predictions.decoder
+
+ def set_output_embeddings(self, new_embeddings):
+ self.cls.predictions.decoder = new_embeddings
+ self.cls.predictions.bias = new_embeddings.bias
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ token_type_ids: torch.Tensor | None = None,
+ position_ids: torch.Tensor | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ encoder_hidden_states: torch.Tensor | None = None,
+ encoder_attention_mask: torch.Tensor | None = None,
+ labels: torch.Tensor | None = None,
+ past_key_values: Cache | None = None,
+ use_cache: bool | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | CausalLMOutputWithCrossAttentions:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
+ `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
+ ignored (masked), the loss is only computed for the tokens with labels n `[0, ..., config.vocab_size]`
+ """
+ if labels is not None:
+ use_cache = False
+
+ outputs: BaseModelOutputWithPoolingAndCrossAttentions = self.bert(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ return_dict=True,
+ **kwargs,
+ )
+
+ hidden_states = outputs.last_hidden_state
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
+ logits = self.cls(hidden_states[:, slice_indices, :])
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
+
+ return CausalLMOutputWithCrossAttentions(
+ loss=loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ cross_attentions=outputs.cross_attentions,
+ )
+
+
+@auto_docstring
+class BertForMaskedLM(BertPreTrainedModel):
+ _tied_weights_keys = {
+ "cls.predictions.decoder.weight": "bert.embeddings.word_embeddings.weight",
+ "cls.predictions.decoder.bias": "cls.predictions.bias",
+ }
+
+ def __init__(self, config):
+ super().__init__(config)
+
+ if config.is_decoder:
+ logger.warning(
+ "If you want to use `BertForMaskedLM` make sure `config.is_decoder=False` for "
+ "bi-directional self-attention."
+ )
+
+ self.bert = BertModel(config, add_pooling_layer=False)
+ self.cls = BertOnlyMLMHead(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_output_embeddings(self):
+ return self.cls.predictions.decoder
+
+ def set_output_embeddings(self, new_embeddings):
+ self.cls.predictions.decoder = new_embeddings
+ self.cls.predictions.bias = new_embeddings.bias
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ token_type_ids: torch.Tensor | None = None,
+ position_ids: torch.Tensor | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ encoder_hidden_states: torch.Tensor | None = None,
+ encoder_attention_mask: torch.Tensor | None = None,
+ labels: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | MaskedLMOutput:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
+ """
+ outputs = self.bert(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ return_dict=True,
+ **kwargs,
+ )
+
+ sequence_output = outputs[0]
+ prediction_scores = self.cls(sequence_output)
+
+ masked_lm_loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss() # -100 index = padding token
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
+
+ return MaskedLMOutput(
+ loss=masked_lm_loss,
+ logits=prediction_scores,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ Bert Model with a `next sentence prediction (classification)` head on top.
+ """
+)
+class BertForNextSentencePrediction(BertPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.bert = BertModel(config)
+ self.cls = BertOnlyNSPHead(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ token_type_ids: torch.Tensor | None = None,
+ position_ids: torch.Tensor | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ labels: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | NextSentencePredictorOutput:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair
+ (see `input_ids` docstring). Indices should be in `[0, 1]`:
+
+ - 0 indicates sequence B is a continuation of sequence A,
+ - 1 indicates sequence B is a random sequence.
+
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, BertForNextSentencePrediction
+ >>> import torch
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
+ >>> model = BertForNextSentencePrediction.from_pretrained("google-bert/bert-base-uncased")
+
+ >>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
+ >>> next_sentence = "The sky is blue due to the shorter wavelength of blue light."
+ >>> encoding = tokenizer(prompt, next_sentence, return_tensors="pt")
+
+ >>> outputs = model(**encoding, labels=torch.LongTensor([1]))
+ >>> logits = outputs.logits
+ >>> assert logits[0, 0] < logits[0, 1] # next sentence was random
+ ```
+ """
+
+ outputs = self.bert(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ return_dict=True,
+ **kwargs,
+ )
+
+ pooled_output = outputs[1]
+
+ seq_relationship_scores = self.cls(pooled_output)
+
+ next_sentence_loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ next_sentence_loss = loss_fct(seq_relationship_scores.view(-1, 2), labels.view(-1))
+
+ return NextSentencePredictorOutput(
+ loss=next_sentence_loss,
+ logits=seq_relationship_scores,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ Bert Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled
+ output) e.g. for GLUE tasks.
+ """
+)
+class BertForSequenceClassification(BertPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+ self.config = config
+
+ self.bert = BertModel(config)
+ classifier_dropout = (
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
+ )
+ self.dropout = nn.Dropout(classifier_dropout)
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ token_type_ids: torch.Tensor | None = None,
+ position_ids: torch.Tensor | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ labels: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | SequenceClassifierOutput:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+ outputs = self.bert(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ return_dict=True,
+ **kwargs,
+ )
+
+ pooled_output = outputs[1]
+
+ pooled_output = self.dropout(pooled_output)
+ logits = self.classifier(pooled_output)
+
+ loss = None
+ if labels is not None:
+ if self.config.problem_type is None:
+ if self.num_labels == 1:
+ self.config.problem_type = "regression"
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
+ self.config.problem_type = "single_label_classification"
+ else:
+ self.config.problem_type = "multi_label_classification"
+
+ if self.config.problem_type == "regression":
+ loss_fct = MSELoss()
+ if self.num_labels == 1:
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
+ else:
+ loss = loss_fct(logits, labels)
+ elif self.config.problem_type == "single_label_classification":
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+ elif self.config.problem_type == "multi_label_classification":
+ loss_fct = BCEWithLogitsLoss()
+ loss = loss_fct(logits, labels)
+
+ return SequenceClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+class BertForMultipleChoice(BertPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.bert = BertModel(config)
+ classifier_dropout = (
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
+ )
+ self.dropout = nn.Dropout(classifier_dropout)
+ self.classifier = nn.Linear(config.hidden_size, 1)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ token_type_ids: torch.Tensor | None = None,
+ position_ids: torch.Tensor | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ labels: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | MultipleChoiceModelOutput:
+ r"""
+ input_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input-ids)
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
+ 1]`:
+
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ position_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
+ config.max_position_embeddings - 1]`.
+
+ [What are position IDs?](../glossary#position-ids)
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_choices, sequence_length, hidden_size)`, *optional*):
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
+ model's internal embedding lookup matrix.
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
+ num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
+ `input_ids` above)
+ """
+ num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
+
+ input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
+ attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
+ token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
+ position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
+ inputs_embeds = (
+ inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
+ if inputs_embeds is not None
+ else None
+ )
+
+ outputs = self.bert(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ return_dict=True,
+ **kwargs,
+ )
+
+ pooled_output = outputs[1]
+
+ pooled_output = self.dropout(pooled_output)
+ logits = self.classifier(pooled_output)
+ reshaped_logits = logits.view(-1, num_choices)
+
+ loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(reshaped_logits, labels)
+
+ return MultipleChoiceModelOutput(
+ loss=loss,
+ logits=reshaped_logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+class BertForTokenClassification(BertPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+
+ self.bert = BertModel(config, add_pooling_layer=False)
+ classifier_dropout = (
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
+ )
+ self.dropout = nn.Dropout(classifier_dropout)
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ token_type_ids: torch.Tensor | None = None,
+ position_ids: torch.Tensor | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ labels: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | TokenClassifierOutput:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
+ """
+ outputs = self.bert(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ return_dict=True,
+ **kwargs,
+ )
+
+ sequence_output = outputs[0]
+
+ sequence_output = self.dropout(sequence_output)
+ logits = self.classifier(sequence_output)
+
+ loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+
+ return TokenClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+class BertForQuestionAnswering(BertPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+
+ self.bert = BertModel(config, add_pooling_layer=False)
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ token_type_ids: torch.Tensor | None = None,
+ position_ids: torch.Tensor | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ start_positions: torch.Tensor | None = None,
+ end_positions: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | QuestionAnsweringModelOutput:
+ outputs = self.bert(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ return_dict=True,
+ **kwargs,
+ )
+
+ sequence_output = outputs[0]
+
+ logits = self.qa_outputs(sequence_output)
+ start_logits, end_logits = logits.split(1, dim=-1)
+ start_logits = start_logits.squeeze(-1).contiguous()
+ end_logits = end_logits.squeeze(-1).contiguous()
+
+ total_loss = None
+ if start_positions is not None and end_positions is not None:
+ # If we are on multi-GPU, split add a dimension
+ if len(start_positions.size()) > 1:
+ start_positions = start_positions.squeeze(-1)
+ if len(end_positions.size()) > 1:
+ end_positions = end_positions.squeeze(-1)
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
+ ignored_index = start_logits.size(1)
+ start_positions = start_positions.clamp(0, ignored_index)
+ end_positions = end_positions.clamp(0, ignored_index)
+
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
+ start_loss = loss_fct(start_logits, start_positions)
+ end_loss = loss_fct(end_logits, end_positions)
+ total_loss = (start_loss + end_loss) / 2
+
+ return QuestionAnsweringModelOutput(
+ loss=total_loss,
+ start_logits=start_logits,
+ end_logits=end_logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+__all__ = [
+ "BertForMaskedLM",
+ "BertForMultipleChoice",
+ "BertForNextSentencePrediction",
+ "BertForPreTraining",
+ "BertForQuestionAnswering",
+ "BertForSequenceClassification",
+ "BertForTokenClassification",
+ "BertLayer",
+ "BertLMHeadModel",
+ "BertModel",
+ "BertPreTrainedModel",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bert/tokenization_bert.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bert/tokenization_bert.py
new file mode 100644
index 0000000000000000000000000000000000000000..47cb639fab40cfbfb9749230dc6b5c94d35d8b8d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bert/tokenization_bert.py
@@ -0,0 +1,140 @@
+# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Tokenization classes for Bert."""
+
+import collections
+
+from tokenizers import Tokenizer, decoders, normalizers, pre_tokenizers, processors
+from tokenizers.models import WordPiece
+
+from ...tokenization_utils_tokenizers import TokenizersBackend
+from ...utils import logging
+
+
+logger = logging.get_logger(__name__)
+
+VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"}
+
+
+def load_vocab(vocab_file):
+ """Loads a vocabulary file into a dictionary."""
+ vocab = collections.OrderedDict()
+ with open(vocab_file, "r", encoding="utf-8") as reader:
+ tokens = reader.readlines()
+ for index, token in enumerate(tokens):
+ token = token.rstrip("\n")
+ vocab[token] = index
+ return vocab
+
+
+class BertTokenizer(TokenizersBackend):
+ r"""
+ Construct a BERT tokenizer (backed by HuggingFace's tokenizers library). Based on WordPiece.
+
+ This tokenizer inherits from [`TokenizersBackend`] which contains most of the main methods. Users should refer to
+ this superclass for more information regarding those methods.
+
+ Args:
+ vocab (`str` or `dict[str, int]`, *optional*):
+ Custom vocabulary dictionary. If not provided, vocabulary is loaded from `vocab_file`.
+ do_lower_case (`bool`, *optional*, defaults to `True`):
+ Whether or not to lowercase the input when tokenizing.
+ unk_token (`str`, *optional*, defaults to `"[UNK]"`):
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
+ token instead.
+ sep_token (`str`, *optional*, defaults to `"[SEP]"`):
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
+ sequence classification or for a text and a question for question answering. It is also used as the last
+ token of a sequence built with special tokens.
+ pad_token (`str`, *optional*, defaults to `"[PAD]"`):
+ The token used for padding, for example when batching sequences of different lengths.
+ cls_token (`str`, *optional*, defaults to `"[CLS]"`):
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
+ mask_token (`str`, *optional*, defaults to `"[MASK]"`):
+ The token used for masking values. This is the token used when training this model with masked language
+ modeling. This is the token which the model will try to predict.
+ tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
+ Whether or not to tokenize Chinese characters.
+ strip_accents (`bool`, *optional*):
+ Whether or not to strip all accents. If this option is not specified, then it will be determined by the
+ value for `lowercase` (as in the original BERT).
+ """
+
+ vocab_files_names = VOCAB_FILES_NAMES
+ model_input_names = ["input_ids", "token_type_ids", "attention_mask"]
+ model = WordPiece
+
+ def __init__(
+ self,
+ vocab: str | dict[str, int] | None = None,
+ do_lower_case: bool = True,
+ unk_token: str = "[UNK]",
+ sep_token: str = "[SEP]",
+ pad_token: str = "[PAD]",
+ cls_token: str = "[CLS]",
+ mask_token: str = "[MASK]",
+ tokenize_chinese_chars: bool = True,
+ strip_accents: bool | None = None,
+ **kwargs,
+ ):
+ self.do_lower_case = do_lower_case
+ self.tokenize_chinese_chars = tokenize_chinese_chars
+ self.strip_accents = strip_accents
+ if vocab is None:
+ vocab = {
+ str(pad_token): 0,
+ str(unk_token): 1,
+ str(cls_token): 2,
+ str(sep_token): 3,
+ str(mask_token): 4,
+ }
+ self._vocab = vocab
+ self._tokenizer = Tokenizer(WordPiece(self._vocab, unk_token=str(unk_token)))
+ self._tokenizer.normalizer = normalizers.BertNormalizer(
+ clean_text=True,
+ handle_chinese_chars=tokenize_chinese_chars,
+ strip_accents=strip_accents,
+ lowercase=do_lower_case,
+ )
+ self._tokenizer.pre_tokenizer = pre_tokenizers.BertPreTokenizer()
+ self._tokenizer.decoder = decoders.WordPiece(prefix="##")
+ super().__init__(
+ do_lower_case=do_lower_case,
+ unk_token=unk_token,
+ sep_token=sep_token,
+ pad_token=pad_token,
+ cls_token=cls_token,
+ mask_token=mask_token,
+ tokenize_chinese_chars=tokenize_chinese_chars,
+ strip_accents=strip_accents,
+ **kwargs,
+ )
+
+ cls_token_id = self.cls_token_id if self.cls_token_id is not None else 2
+ sep_token_id = self.sep_token_id if self.sep_token_id is not None else 3
+
+ self._tokenizer.post_processor = processors.TemplateProcessing(
+ single=f"{str(self.cls_token)}:0 $A:0 {str(self.sep_token)}:0",
+ pair=f"{str(self.cls_token)}:0 $A:0 {str(self.sep_token)}:0 $B:1 {str(self.sep_token)}:1",
+ special_tokens=[
+ (str(self.cls_token), cls_token_id),
+ (str(self.sep_token), sep_token_id),
+ ],
+ )
+
+
+__all__ = ["BertTokenizer"]
+
+BertTokenizerFast = BertTokenizer
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bert/tokenization_bert_legacy.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bert/tokenization_bert_legacy.py
new file mode 100644
index 0000000000000000000000000000000000000000..cb96aa3eb29eee725edda716d00c8e56240c4e1e
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bert/tokenization_bert_legacy.py
@@ -0,0 +1,476 @@
+# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Tokenization classes for Bert."""
+
+import collections
+import os
+import unicodedata
+
+from ...tokenization_python import PreTrainedTokenizer, _is_control, _is_punctuation, _is_whitespace
+from ...utils import logging
+
+
+logger = logging.get_logger(__name__)
+
+VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt"}
+
+
+def load_vocab(vocab_file):
+ """Loads a vocabulary file into a dictionary."""
+ vocab = collections.OrderedDict()
+ with open(vocab_file, "r", encoding="utf-8") as reader:
+ tokens = reader.readlines()
+ for index, token in enumerate(tokens):
+ token = token.rstrip("\n")
+ vocab[token] = index
+ return vocab
+
+
+def whitespace_tokenize(text):
+ """Runs basic whitespace cleaning and splitting on a piece of text."""
+ text = text.strip()
+ if not text:
+ return []
+ tokens = text.split()
+ return tokens
+
+
+class BertTokenizerLegacy(PreTrainedTokenizer):
+ r"""
+ Construct a BERT tokenizer. Based on WordPiece.
+
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
+ this superclass for more information regarding those methods.
+
+ Args:
+ vocab_file (`str`):
+ File containing the vocabulary.
+ do_lower_case (`bool`, *optional*, defaults to `True`):
+ Whether or not to lowercase the input when tokenizing.
+ do_basic_tokenize (`bool`, *optional*, defaults to `True`):
+ Whether or not to do basic tokenization before WordPiece.
+ never_split (`Iterable`, *optional*):
+ Collection of tokens which will never be split during tokenization. Only has an effect when
+ `do_basic_tokenize=True`
+ unk_token (`str`, *optional*, defaults to `"[UNK]"`):
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
+ token instead.
+ sep_token (`str`, *optional*, defaults to `"[SEP]"`):
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
+ sequence classification or for a text and a question for question answering. It is also used as the last
+ token of a sequence built with special tokens.
+ pad_token (`str`, *optional*, defaults to `"[PAD]"`):
+ The token used for padding, for example when batching sequences of different lengths.
+ cls_token (`str`, *optional*, defaults to `"[CLS]"`):
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
+ mask_token (`str`, *optional*, defaults to `"[MASK]"`):
+ The token used for masking values. This is the token used when training this model with masked language
+ modeling. This is the token which the model will try to predict.
+ tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
+ Whether or not to tokenize Chinese characters.
+
+ This should likely be deactivated for Japanese (see this
+ [issue](https://github.com/huggingface/transformers/issues/328)).
+ strip_accents (`bool`, *optional*):
+ Whether or not to strip all accents. If this option is not specified, then it will be determined by the
+ value for `lowercase` (as in the original BERT).
+ clean_up_tokenization_spaces (`bool`, *optional*, defaults to `True`):
+ Whether or not to cleanup spaces after decoding, cleanup consists in removing potential artifacts like
+ extra spaces.
+ """
+
+ vocab_files_names = VOCAB_FILES_NAMES
+
+ def __init__(
+ self,
+ vocab_file,
+ do_lower_case=True,
+ do_basic_tokenize=True,
+ never_split=None,
+ unk_token="[UNK]",
+ sep_token="[SEP]",
+ pad_token="[PAD]",
+ cls_token="[CLS]",
+ mask_token="[MASK]",
+ tokenize_chinese_chars=True,
+ strip_accents=None,
+ clean_up_tokenization_spaces=True,
+ **kwargs,
+ ):
+ if not os.path.isfile(vocab_file):
+ raise ValueError(
+ f"Can't find a vocabulary file at path '{vocab_file}'. To load the vocabulary from a Google pretrained"
+ " model use `tokenizer = BertTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`"
+ )
+ self.vocab = load_vocab(vocab_file)
+ self.ids_to_tokens = collections.OrderedDict([(ids, tok) for tok, ids in self.vocab.items()])
+ self.do_basic_tokenize = do_basic_tokenize
+ if do_basic_tokenize:
+ self.basic_tokenizer = BasicTokenizer(
+ do_lower_case=do_lower_case,
+ never_split=never_split,
+ tokenize_chinese_chars=tokenize_chinese_chars,
+ strip_accents=strip_accents,
+ )
+
+ self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab, unk_token=str(unk_token))
+
+ super().__init__(
+ do_lower_case=do_lower_case,
+ do_basic_tokenize=do_basic_tokenize,
+ never_split=never_split,
+ unk_token=unk_token,
+ sep_token=sep_token,
+ pad_token=pad_token,
+ cls_token=cls_token,
+ mask_token=mask_token,
+ tokenize_chinese_chars=tokenize_chinese_chars,
+ strip_accents=strip_accents,
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
+ **kwargs,
+ )
+
+ @property
+ def do_lower_case(self):
+ return self.basic_tokenizer.do_lower_case
+
+ @property
+ def vocab_size(self):
+ return len(self.vocab)
+
+ def get_vocab(self):
+ return dict(self.vocab, **self.added_tokens_encoder)
+
+ def _tokenize(self, text, split_special_tokens=False):
+ split_tokens = []
+ if self.do_basic_tokenize:
+ for token in self.basic_tokenizer.tokenize(
+ text, never_split=self.all_special_tokens if not split_special_tokens else None
+ ):
+ # If the token is part of the never_split set
+ if token in self.basic_tokenizer.never_split:
+ split_tokens.append(token)
+ else:
+ split_tokens += self.wordpiece_tokenizer.tokenize(token)
+ else:
+ split_tokens = self.wordpiece_tokenizer.tokenize(text)
+ return split_tokens
+
+ def _convert_token_to_id(self, token):
+ """Converts a token (str) in an id using the vocab."""
+ return self.vocab.get(token, self.vocab.get(self.unk_token))
+
+ def _convert_id_to_token(self, index):
+ """Converts an index (integer) in a token (str) using the vocab."""
+ return self.ids_to_tokens.get(index, self.unk_token)
+
+ def convert_tokens_to_string(self, tokens):
+ """Converts a sequence of tokens (string) in a single string."""
+ out_string = " ".join(tokens).replace(" ##", "").strip()
+ return out_string
+
+ def build_inputs_with_special_tokens(
+ self, token_ids_0: list[int], token_ids_1: list[int] | None = None
+ ) -> list[int]:
+ """
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
+ adding special tokens. A BERT sequence has the following format:
+
+ - single sequence: `[CLS] X [SEP]`
+ - pair of sequences: `[CLS] A [SEP] B [SEP]`
+
+ Args:
+ token_ids_0 (`List[int]`):
+ List of IDs to which the special tokens will be added.
+ token_ids_1 (`List[int]`, *optional*):
+ Optional second list of IDs for sequence pairs.
+
+ Returns:
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
+ """
+ if token_ids_1 is None:
+ return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
+ cls = [self.cls_token_id]
+ sep = [self.sep_token_id]
+ return cls + token_ids_0 + sep + token_ids_1 + sep
+
+ def get_special_tokens_mask(
+ self, token_ids_0: list[int], token_ids_1: list[int] | None = None, already_has_special_tokens: bool = False
+ ) -> list[int]:
+ """
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
+ special tokens using the tokenizer `prepare_for_model` method.
+
+ Args:
+ token_ids_0 (`List[int]`):
+ List of IDs.
+ token_ids_1 (`List[int]`, *optional*):
+ Optional second list of IDs for sequence pairs.
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
+ Whether or not the token list is already formatted with special tokens for the model.
+
+ Returns:
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
+ """
+
+ if already_has_special_tokens:
+ return super().get_special_tokens_mask(
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
+ )
+
+ if token_ids_1 is not None:
+ return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
+ return [1] + ([0] * len(token_ids_0)) + [1]
+
+ def save_vocabulary(self, save_directory: str, filename_prefix: str | None = None) -> tuple[str]:
+ index = 0
+ if os.path.isdir(save_directory):
+ vocab_file = os.path.join(
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
+ )
+ else:
+ vocab_file = (filename_prefix + "-" if filename_prefix else "") + save_directory
+ with open(vocab_file, "w", encoding="utf-8") as writer:
+ for token, token_index in sorted(self.vocab.items(), key=lambda kv: kv[1]):
+ if index != token_index:
+ logger.warning(
+ f"Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive."
+ " Please check that the vocabulary is not corrupted!"
+ )
+ index = token_index
+ writer.write(token + "\n")
+ index += 1
+ return (vocab_file,)
+
+
+class BasicTokenizer:
+ """
+ Constructs a BasicTokenizer that will run basic tokenization (punctuation splitting, lower casing, etc.).
+
+ Args:
+ do_lower_case (`bool`, *optional*, defaults to `True`):
+ Whether or not to lowercase the input when tokenizing.
+ never_split (`Iterable`, *optional*):
+ Collection of tokens which will never be split during tokenization. Only has an effect when
+ `do_basic_tokenize=True`
+ tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
+ Whether or not to tokenize Chinese characters.
+
+ This should likely be deactivated for Japanese (see this
+ [issue](https://github.com/huggingface/transformers/issues/328)).
+ strip_accents (`bool`, *optional*):
+ Whether or not to strip all accents. If this option is not specified, then it will be determined by the
+ value for `lowercase` (as in the original BERT).
+ do_split_on_punc (`bool`, *optional*, defaults to `True`):
+ In some instances we want to skip the basic punctuation splitting so that later tokenization can capture
+ the full context of the words, such as contractions.
+ """
+
+ def __init__(
+ self,
+ do_lower_case=True,
+ never_split=None,
+ tokenize_chinese_chars=True,
+ strip_accents=None,
+ do_split_on_punc=True,
+ ):
+ if never_split is None:
+ never_split = []
+ self.do_lower_case = do_lower_case
+ self.never_split = set(never_split)
+ self.tokenize_chinese_chars = tokenize_chinese_chars
+ self.strip_accents = strip_accents
+ self.do_split_on_punc = do_split_on_punc
+
+ def tokenize(self, text, never_split=None):
+ """
+ Basic Tokenization of a piece of text. For sub-word tokenization, see WordPieceTokenizer.
+
+ Args:
+ never_split (`List[str]`, *optional*)
+ Kept for backward compatibility purposes. Now implemented directly at the base class level (see
+ [`PreTrainedTokenizer.tokenize`]) List of token not to split.
+ """
+ # union() returns a new set by concatenating the two sets.
+ never_split = self.never_split.union(set(never_split)) if never_split else self.never_split
+ text = self._clean_text(text)
+
+ # This was added on November 1st, 2018 for the multilingual and Chinese
+ # models. This is also applied to the English models now, but it doesn't
+ # matter since the English models were not trained on any Chinese data
+ # and generally don't have any Chinese data in them (there are Chinese
+ # characters in the vocabulary because Wikipedia does have some Chinese
+ # words in the English Wikipedia.).
+ if self.tokenize_chinese_chars:
+ text = self._tokenize_chinese_chars(text)
+ # prevents treating the same character with different unicode codepoints as different characters
+ unicode_normalized_text = unicodedata.normalize("NFC", text)
+ orig_tokens = whitespace_tokenize(unicode_normalized_text)
+ split_tokens = []
+ for token in orig_tokens:
+ if token not in never_split:
+ if self.do_lower_case:
+ token = token.lower()
+ if self.strip_accents is not False:
+ token = self._run_strip_accents(token)
+ elif self.strip_accents:
+ token = self._run_strip_accents(token)
+ split_tokens.extend(self._run_split_on_punc(token, never_split))
+
+ output_tokens = whitespace_tokenize(" ".join(split_tokens))
+ return output_tokens
+
+ def _run_strip_accents(self, text):
+ """Strips accents from a piece of text."""
+ text = unicodedata.normalize("NFD", text)
+ output = []
+ for char in text:
+ cat = unicodedata.category(char)
+ if cat == "Mn":
+ continue
+ output.append(char)
+ return "".join(output)
+
+ def _run_split_on_punc(self, text, never_split=None):
+ """Splits punctuation on a piece of text."""
+ if not self.do_split_on_punc or (never_split is not None and text in never_split):
+ return [text]
+ chars = list(text)
+ i = 0
+ start_new_word = True
+ output = []
+ while i < len(chars):
+ char = chars[i]
+ if _is_punctuation(char):
+ output.append([char])
+ start_new_word = True
+ else:
+ if start_new_word:
+ output.append([])
+ start_new_word = False
+ output[-1].append(char)
+ i += 1
+
+ return ["".join(x) for x in output]
+
+ def _tokenize_chinese_chars(self, text):
+ """Adds whitespace around any CJK character."""
+ output = []
+ for char in text:
+ cp = ord(char)
+ if self._is_chinese_char(cp):
+ output.append(" ")
+ output.append(char)
+ output.append(" ")
+ else:
+ output.append(char)
+ return "".join(output)
+
+ def _is_chinese_char(self, cp):
+ """Checks whether CP is the codepoint of a CJK character."""
+ # This defines a "chinese character" as anything in the CJK Unicode block:
+ # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
+ #
+ # Note that the CJK Unicode block is NOT all Japanese and Korean characters,
+ # despite its name. The modern Korean Hangul alphabet is a different block,
+ # as is Japanese Hiragana and Katakana. Those alphabets are used to write
+ # space-separated words, so they are not treated specially and handled
+ # like the all of the other languages.
+ if (
+ (cp >= 0x4E00 and cp <= 0x9FFF)
+ or (cp >= 0x3400 and cp <= 0x4DBF)
+ or (cp >= 0x20000 and cp <= 0x2A6DF)
+ or (cp >= 0x2A700 and cp <= 0x2B73F)
+ or (cp >= 0x2B740 and cp <= 0x2B81F)
+ or (cp >= 0x2B820 and cp <= 0x2CEAF)
+ or (cp >= 0xF900 and cp <= 0xFAFF)
+ or (cp >= 0x2F800 and cp <= 0x2FA1F)
+ ):
+ return True
+
+ return False
+
+ def _clean_text(self, text):
+ """Performs invalid character removal and whitespace cleanup on text."""
+ output = []
+ for char in text:
+ cp = ord(char)
+ if cp == 0 or cp == 0xFFFD or _is_control(char):
+ continue
+ if _is_whitespace(char):
+ output.append(" ")
+ else:
+ output.append(char)
+ return "".join(output)
+
+
+class WordpieceTokenizer:
+ """Runs WordPiece tokenization."""
+
+ def __init__(self, vocab, unk_token, max_input_chars_per_word=100):
+ self.vocab = vocab
+ self.unk_token = unk_token
+ self.max_input_chars_per_word = max_input_chars_per_word
+
+ def tokenize(self, text):
+ """
+ Tokenizes a piece of text into its word pieces. This uses a greedy longest-match-first algorithm to perform
+ tokenization using the given vocabulary.
+
+ For example, `input = "unaffable"` will return as output `["un", "##aff", "##able"]`.
+
+ Args:
+ text: A single token or whitespace separated tokens. This should have
+ already been passed through *BasicTokenizer*.
+
+ Returns:
+ A list of wordpiece tokens.
+ """
+
+ output_tokens = []
+ for token in whitespace_tokenize(text):
+ chars = list(token)
+ if len(chars) > self.max_input_chars_per_word:
+ output_tokens.append(self.unk_token)
+ continue
+
+ is_bad = False
+ start = 0
+ sub_tokens = []
+ while start < len(chars):
+ end = len(chars)
+ cur_substr = None
+ while start < end:
+ substr = "".join(chars[start:end])
+ if start > 0:
+ substr = "##" + substr
+ if substr in self.vocab:
+ cur_substr = substr
+ break
+ end -= 1
+ if cur_substr is None:
+ is_bad = True
+ break
+ sub_tokens.append(cur_substr)
+ start = end
+
+ if is_bad:
+ output_tokens.append(self.unk_token)
+ else:
+ output_tokens.extend(sub_tokens)
+ return output_tokens
+
+
+__all__ = ["BasicTokenizer", "BertTokenizerLegacy", "WordpieceTokenizer"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bertweet/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bertweet/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..432622f1595d1a0d8bb1b3c9b9774b7d1e387d3e
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bertweet/__init__.py
@@ -0,0 +1,26 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .tokenization_bertweet import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bertweet/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bertweet/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..76bca74ffb9ee37eb1cd6cbbfc9c6a86ad00127e
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bertweet/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bertweet/__pycache__/tokenization_bertweet.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bertweet/__pycache__/tokenization_bertweet.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..eb2bceb5df0e2c74343ac3022b1782dbc1f9dec5
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bertweet/__pycache__/tokenization_bertweet.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bertweet/tokenization_bertweet.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bertweet/tokenization_bertweet.py
new file mode 100644
index 0000000000000000000000000000000000000000..95e9f46787e8fb087e0bd1bac400f10a172e4710
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bertweet/tokenization_bertweet.py
@@ -0,0 +1,698 @@
+# Copyright (c) 2020, VinAI Research and the HuggingFace Inc. team.
+# Copyright 2018 The Open AI Team Authors and The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Tokenization classes for BERTweet"""
+
+import html
+import os
+import re
+
+import regex
+
+from ...tokenization_python import PreTrainedTokenizer
+from ...utils import logging
+
+
+logger = logging.get_logger(__name__)
+
+VOCAB_FILES_NAMES = {
+ "vocab_file": "vocab.txt",
+ "merges_file": "bpe.codes",
+}
+
+
+def get_pairs(word):
+ """
+ Return set of symbol pairs in a word.
+
+ Word is represented as tuple of symbols (symbols being variable-length strings).
+ """
+ pairs = set()
+ prev_char = word[0]
+ for char in word[1:]:
+ pairs.add((prev_char, char))
+ prev_char = char
+
+ pairs = set(pairs)
+ return pairs
+
+
+class BertweetTokenizer(PreTrainedTokenizer):
+ """
+ Constructs a BERTweet tokenizer, using Byte-Pair-Encoding.
+
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
+ this superclass for more information regarding those methods.
+
+ Args:
+ vocab_file (`str`):
+ Path to the vocabulary file.
+ merges_file (`str`):
+ Path to the merges file.
+ normalization (`bool`, *optional*, defaults to `False`):
+ Whether or not to apply a normalization preprocess.
+ bos_token (`str`, *optional*, defaults to `""`):
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
+
+
+
+ When building a sequence using special tokens, this is not the token that is used for the beginning of
+ sequence. The token used is the `cls_token`.
+
+
+
+ eos_token (`str`, *optional*, defaults to `""`):
+ The end of sequence token.
+
+
+
+ When building a sequence using special tokens, this is not the token that is used for the end of sequence.
+ The token used is the `sep_token`.
+
+
+
+ sep_token (`str`, *optional*, defaults to `""`):
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
+ sequence classification or for a text and a question for question answering. It is also used as the last
+ token of a sequence built with special tokens.
+ cls_token (`str`, *optional*, defaults to `""`):
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
+ unk_token (`str`, *optional*, defaults to `""`):
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
+ token instead.
+ pad_token (`str`, *optional*, defaults to `""`):
+ The token used for padding, for example when batching sequences of different lengths.
+ mask_token (`str`, *optional*, defaults to `""`):
+ The token used for masking values. This is the token used when training this model with masked language
+ modeling. This is the token which the model will try to predict.
+ """
+
+ vocab_files_names = VOCAB_FILES_NAMES
+
+ def __init__(
+ self,
+ vocab_file,
+ merges_file,
+ normalization=False,
+ bos_token="",
+ eos_token="",
+ sep_token="",
+ cls_token="",
+ unk_token="",
+ pad_token="",
+ mask_token="",
+ **kwargs,
+ ):
+ try:
+ from emoji import demojize
+
+ self.demojizer = demojize
+ except ImportError:
+ logger.warning(
+ "emoji is not installed, thus not converting emoticons or emojis into text. Install emoji: pip3"
+ " install emoji==0.6.0"
+ )
+ self.demojizer = None
+
+ self.vocab_file = vocab_file
+ self.merges_file = merges_file
+
+ self.encoder = {}
+ self.encoder[str(bos_token)] = 0
+ self.encoder[str(pad_token)] = 1
+ self.encoder[str(eos_token)] = 2
+ self.encoder[str(unk_token)] = 3
+
+ self.add_from_file(vocab_file)
+
+ self.decoder = {v: k for k, v in self.encoder.items()}
+
+ with open(merges_file, encoding="utf-8") as merges_handle:
+ merges = merges_handle.read().split("\n")[:-1]
+ merges = [tuple(merge.split()[:-1]) for merge in merges]
+ self.bpe_ranks = dict(zip(merges, range(len(merges))))
+ self.cache = {}
+
+ self.normalization = normalization
+ self.tweetPreprocessor = TweetTokenizer()
+ self.special_puncts = {"’": "'", "…": "..."}
+
+ super().__init__(
+ normalization=normalization,
+ bos_token=bos_token,
+ eos_token=eos_token,
+ sep_token=sep_token,
+ cls_token=cls_token,
+ unk_token=unk_token,
+ pad_token=pad_token,
+ mask_token=mask_token,
+ # Configure patterns instead of overriding methods
+ token_type_ids_pattern="all_zeros", # BERTweet doesn't use token type IDs
+ token_type_ids_include_special_tokens=True,
+ special_tokens_pattern="cls_double_sep", # X Y
+ **kwargs,
+ )
+
+ @property
+ def vocab_size(self):
+ return len(self.encoder)
+
+ def get_vocab(self):
+ return dict(self.encoder, **self.added_tokens_encoder)
+
+ def bpe(self, token):
+ if token in self.cache:
+ return self.cache[token]
+ word = tuple(token)
+ word = tuple(list(word[:-1]) + [word[-1] + ""])
+ pairs = get_pairs(word)
+
+ if not pairs:
+ return token
+
+ while True:
+ bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
+ if bigram not in self.bpe_ranks:
+ break
+ first, second = bigram
+ new_word = []
+ i = 0
+ while i < len(word):
+ try:
+ j = word.index(first, i)
+ except ValueError:
+ new_word.extend(word[i:])
+ break
+ else:
+ new_word.extend(word[i:j])
+ i = j
+
+ if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
+ new_word.append(first + second)
+ i += 2
+ else:
+ new_word.append(word[i])
+ i += 1
+ new_word = tuple(new_word)
+ word = new_word
+ if len(word) == 1:
+ break
+ else:
+ pairs = get_pairs(word)
+ word = "@@ ".join(word)
+ word = word[:-4]
+ self.cache[token] = word
+ return word
+
+ def _tokenize(self, text):
+ """Tokenize a string."""
+ if self.normalization: # Perform Tweet normalization before performing BPE
+ text = self.normalizeTweet(text)
+
+ split_tokens = []
+ words = re.findall(r"\S+\n?", text)
+ for token in words:
+ split_tokens.extend(list(self.bpe(token).split(" ")))
+ return split_tokens
+
+ def normalizeTweet(self, tweet):
+ """
+ Normalize a raw Tweet
+ """
+ for punct in self.special_puncts:
+ tweet = tweet.replace(punct, self.special_puncts[punct])
+
+ tokens = self.tweetPreprocessor.tokenize(tweet)
+ normTweet = " ".join([self.normalizeToken(token) for token in tokens])
+
+ normTweet = (
+ normTweet.replace("cannot ", "can not ")
+ .replace("n't ", " n't ")
+ .replace("n 't ", " n't ")
+ .replace("ca n't", "can't")
+ .replace("ai n't", "ain't")
+ )
+ normTweet = (
+ normTweet.replace("'m ", " 'm ")
+ .replace("'re ", " 're ")
+ .replace("'s ", " 's ")
+ .replace("'ll ", " 'll ")
+ .replace("'d ", " 'd ")
+ .replace("'ve ", " 've ")
+ )
+ normTweet = (
+ normTweet.replace(" p . m .", " p.m.")
+ .replace(" p . m ", " p.m ")
+ .replace(" a . m .", " a.m.")
+ .replace(" a . m ", " a.m ")
+ )
+
+ return " ".join(normTweet.split())
+
+ def normalizeToken(self, token):
+ """
+ Normalize tokens in a Tweet
+ """
+ lowercased_token = token.lower()
+ if token.startswith("@"):
+ return "@USER"
+ elif lowercased_token.startswith("http") or lowercased_token.startswith("www"):
+ return "HTTPURL"
+ elif len(token) == 1:
+ if token in self.special_puncts:
+ return self.special_puncts[token]
+ if self.demojizer is not None:
+ return self.demojizer(token)
+ else:
+ return token
+ else:
+ return token
+
+ def _convert_token_to_id(self, token):
+ """Converts a token (str) in an id using the vocab."""
+ return self.encoder.get(token, self.encoder.get(self.unk_token))
+
+ def _convert_id_to_token(self, index):
+ """Converts an index (integer) in a token (str) using the vocab."""
+ return self.decoder.get(index, self.unk_token)
+
+ def convert_tokens_to_string(self, tokens):
+ """Converts a sequence of tokens (string) in a single string."""
+ out_string = " ".join(tokens).replace("@@ ", "").strip()
+ return out_string
+
+ # def decode(self, token_ids, skip_special_tokens=False, clean_up_tokenization_spaces=True):
+ # filtered_tokens = ' '.join(self.convert_ids_to_tokens(token_ids, skip_special_tokens=skip_special_tokens))
+ # tokens_generated_so_far = re.sub('(@@ )', '', string=filtered_tokens)
+ # tokens_generated_so_far = re.sub('(@@ ?$)', '', string=tokens_generated_so_far)
+ # return ''.join(tokens_generated_so_far)
+
+ def save_vocabulary(self, save_directory: str, filename_prefix: str | None = None) -> tuple[str, ...]:
+ """
+ Save the vocabulary and merges files to a directory.
+ """
+ if not os.path.isdir(save_directory):
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
+ return ()
+
+ vocab_files_names = getattr(self, "vocab_files_names", {})
+ prefix = f"{filename_prefix}-" if filename_prefix else ""
+
+ # Save vocabulary in the format expected by add_from_file:
+ # Exclude special tokens (IDs 0-3) as they are added in __init__ before add_from_file
+ vocab_file = os.path.join(save_directory, prefix + vocab_files_names.get("vocab_file", "vocab.txt"))
+ with open(vocab_file, "w", encoding="utf-8") as f:
+ for token, token_id in sorted(self.encoder.items(), key=lambda kv: kv[1]):
+ # Only save tokens with ID >= 4, as IDs 0-3 are reserved for special tokens
+ if token_id >= 4:
+ f.write(f"{token} {token_id}\n")
+
+ # Save BPE merges
+ merge_file = os.path.join(save_directory, prefix + vocab_files_names.get("merges_file", "bpe.codes"))
+ with open(merge_file, "w", encoding="utf-8") as writer:
+ writer.writelines(
+ " ".join(bpe_tokens) + "\n"
+ for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1])
+ )
+
+ return (vocab_file, merge_file)
+
+ def add_from_file(self, f):
+ """
+ Loads a pre-existing dictionary from a text file and adds its symbols to this instance.
+ """
+ if isinstance(f, str):
+ try:
+ with open(f, "r", encoding="utf-8") as fd:
+ self.add_from_file(fd)
+ except FileNotFoundError as fnfe:
+ raise fnfe
+ except UnicodeError:
+ raise Exception(f"Incorrect encoding detected in {f}, please rebuild the dataset")
+ return
+
+ lines = f.readlines()
+ for lineTmp in lines:
+ line = lineTmp.strip()
+ idx = line.rfind(" ")
+ if idx == -1:
+ raise ValueError("Incorrect dictionary format, expected ' '")
+ word = line[:idx]
+ self.encoder[word] = len(self.encoder)
+
+
+# Natural Language Toolkit: Twitter Tokenizer
+#
+# Copyright (C) 2001-2020 NLTK Project
+# Author: Christopher Potts
+# Ewan Klein (modifications)
+# Pierpaolo Pantone <> (modifications)
+# URL: http://nltk.org/
+# For license information, see LICENSE.TXT
+#
+
+
+"""
+Twitter-aware tokenizer, designed to be flexible and easy to adapt to new domains and tasks. The basic logic is this:
+
+1. The tuple regex_strings defines a list of regular expression strings.
+
+2. The regex_strings strings are put, in order, into a compiled regular expression object called word_re.
+
+3. The tokenization is done by word_re.findall(s), where s is the user-supplied string, inside the tokenize() method of
+ the class Tokenizer.
+
+4. When instantiating Tokenizer objects, there is a single option: preserve_case. By default, it is set to True. If it
+ is set to False, then the tokenizer will lowercase everything except for emoticons.
+
+"""
+
+
+######################################################################
+#
+# import regex # https://github.com/nltk/nltk/issues/2409
+# import html
+#
+######################################################################
+# The following strings are components in the regular expression
+# that is used for tokenizing. It's important that phone_number
+# appears first in the final regex (since it can contain whitespace).
+# It also could matter that tags comes after emoticons, due to the
+# possibility of having text like
+#
+# <:| and some text >:)
+#
+# Most importantly, the final element should always be last, since it
+# does a last ditch whitespace-based tokenization of whatever is left.
+
+# ToDo: Update with http://en.wikipedia.org/wiki/List_of_emoticons ?
+
+# This particular element is used in a couple ways, so we define it
+# with a name:
+# docstyle-ignore
+EMOTICONS = r"""
+ (?:
+ [<>]?
+ [:;=8] # eyes
+ [\-o\*\']? # optional nose
+ [\)\]\(\[dDpP/\:\}\{@\|\\] # mouth
+ |
+ [\)\]\(\[dDpP/\:\}\{@\|\\] # mouth
+ [\-o\*\']? # optional nose
+ [:;=8] # eyes
+ [<>]?
+ |
+ <3 # heart
+ )"""
+
+# URL pattern due to John Gruber, modified by Tom Winzig. See
+# https://gist.github.com/winzig/8894715
+# docstyle-ignore
+URLS = r""" # Capture 1: entire matched URL
+ (?:
+ https?: # URL protocol and colon
+ (?:
+ /{1,3} # 1-3 slashes
+ | # or
+ [a-z0-9%] # Single letter or digit or '%'
+ # (Trying not to match e.g. "URI::Escape")
+ )
+ | # or
+ # looks like domain name followed by a slash:
+ [a-z0-9.\-]+[.]
+ (?:[a-z]{2,13})
+ /
+ )
+ (?: # One or more:
+ [^\s()<>{}\[\]]+ # Run of non-space, non-()<>{}[]
+ | # or
+ \([^\s()]*?\([^\s()]+\)[^\s()]*?\) # balanced parens, one level deep: (...(...)...)
+ |
+ \([^\s]+?\) # balanced parens, non-recursive: (...)
+ )+
+ (?: # End with:
+ \([^\s()]*?\([^\s()]+\)[^\s()]*?\) # balanced parens, one level deep: (...(...)...)
+ |
+ \([^\s]+?\) # balanced parens, non-recursive: (...)
+ | # or
+ [^\s`!()\[\]{};:'".,<>?«»“”‘’] # not a space or one of these punct chars
+ )
+ | # OR, the following to match naked domains:
+ (?:
+ (?\s]+>""",
+ # ASCII Arrows
+ r"""[\-]+>|<[\-]+""",
+ # Twitter username:
+ r"""(?:@[\w_]+)""",
+ # Twitter hashtags:
+ r"""(?:\#+[\w_]+[\w\'_\-]*[\w_]+)""",
+ # email addresses
+ r"""[\w.+-]+@[\w-]+\.(?:[\w-]\.?)+[\w-]""",
+ # docstyle-ignore
+ # Remaining word types:
+ r"""
+ (?:[^\W\d_](?:[^\W\d_]|['\-_])+[^\W\d_]) # Words with apostrophes or dashes.
+ |
+ (?:[+\-]?\d+[,/.:-]\d+[+\-]?) # Numbers, including fractions, decimals.
+ |
+ (?:[\w_]+) # Words without apostrophes or dashes.
+ |
+ (?:\.(?:\s*\.){1,}) # Ellipsis dots.
+ |
+ (?:\S) # Everything else that isn't whitespace.
+ """,
+)
+
+######################################################################
+# This is the core tokenizing regex:
+
+WORD_RE = regex.compile(r"""(%s)""" % "|".join(REGEXPS), regex.VERBOSE | regex.I | regex.UNICODE)
+
+# WORD_RE performs poorly on these patterns:
+HANG_RE = regex.compile(r"([^a-zA-Z0-9])\1{3,}")
+
+# The emoticon string gets its own regex so that we can preserve case for
+# them as needed:
+EMOTICON_RE = regex.compile(EMOTICONS, regex.VERBOSE | regex.I | regex.UNICODE)
+
+# These are for regularizing HTML entities to Unicode:
+ENT_RE = regex.compile(r"&(#?(x?))([^&;\s]+);")
+
+
+######################################################################
+# Functions for converting html entities
+######################################################################
+
+
+def _str_to_unicode(text, encoding=None, errors="strict"):
+ if encoding is None:
+ encoding = "utf-8"
+ if isinstance(text, bytes):
+ return text.decode(encoding, errors)
+ return text
+
+
+def _replace_html_entities(text, keep=(), remove_illegal=True, encoding="utf-8"):
+ """
+ Remove entities from text by converting them to their corresponding unicode character.
+
+ Args:
+ text:
+ A unicode string or a byte string encoded in the given *encoding* (which defaults to 'utf-8').
+ keep (list):
+ List of entity names which should not be replaced. This supports both numeric entities (`nnnn;` and
+ `hhhh;`) and named entities (such as ` ` or `>`).
+ remove_illegal (bool):
+ If `True`, entities that can't be converted are removed. Otherwise, entities that can't be converted are
+ kept "as is".
+ Returns: A unicode string with the entities removed.
+
+ See https://github.com/scrapy/w3lib/blob/master/w3lib/html.py
+
+ Examples:
+
+ ```python
+ >>> from nltk.tokenize.casual import _replace_html_entities
+
+ >>> _replace_html_entities(b"Price: £100")
+ 'Price: \\xa3100'
+
+ >>> print(_replace_html_entities(b"Price: £100"))
+ Price: £100
+ ```"""
+
+ def _convert_entity(match):
+ entity_body = match.group(3)
+ if match.group(1):
+ try:
+ if match.group(2):
+ number = int(entity_body, 16)
+ else:
+ number = int(entity_body, 10)
+ # Numeric character references in the 80-9F range are typically
+ # interpreted by browsers as representing the characters mapped
+ # to bytes 80-9F in the Windows-1252 encoding. For more info
+ # see: https://en.wikipedia.org/wiki/ISO/IEC_8859-1#Similar_character_sets
+ if 0x80 <= number <= 0x9F:
+ return bytes((number,)).decode("cp1252")
+ except ValueError:
+ number = None
+ else:
+ if entity_body in keep:
+ return match.group(0)
+ else:
+ number = html.entities.name2codepoint.get(entity_body)
+ if number is not None:
+ try:
+ return chr(number)
+ except (ValueError, OverflowError):
+ pass
+
+ return "" if remove_illegal else match.group(0)
+
+ return ENT_RE.sub(_convert_entity, _str_to_unicode(text, encoding))
+
+
+######################################################################
+
+
+class TweetTokenizer:
+ r"""
+ Examples:
+
+ ```python
+ >>> # Tokenizer for tweets.
+ >>> from nltk.tokenize import TweetTokenizer
+
+ >>> tknzr = TweetTokenizer()
+ >>> s0 = "This is a cooool #dummysmiley: :-) :-P <3 and some arrows < > -> <--"
+ >>> tknzr.tokenize(s0)
+ ['This', 'is', 'a', 'cooool', '#dummysmiley', ':', ':-)', ':-P', '<3', 'and', 'some', 'arrows', '<', '>', '->', '<--']
+
+ >>> # Examples using *strip_handles* and *reduce_len parameters*:
+ >>> tknzr = TweetTokenizer(strip_handles=True, reduce_len=True)
+ >>> s1 = "@remy: This is waaaaayyyy too much for you!!!!!!"
+ >>> tknzr.tokenize(s1)
+ [':', 'This', 'is', 'waaayyy', 'too', 'much', 'for', 'you', '!', '!', '!']
+ ```"""
+
+ def __init__(self, preserve_case=True, reduce_len=False, strip_handles=False):
+ self.preserve_case = preserve_case
+ self.reduce_len = reduce_len
+ self.strip_handles = strip_handles
+
+ def tokenize(self, text):
+ """
+ Args:
+ text: str
+
+ Returns: list(str) A tokenized list of strings; concatenating this list returns the original string if
+ `preserve_case=False`
+ """
+ # Fix HTML character entities:
+ text = _replace_html_entities(text)
+ # Remove username handles
+ if self.strip_handles:
+ text = remove_handles(text)
+ # Normalize word lengthening
+ if self.reduce_len:
+ text = reduce_lengthening(text)
+ # Shorten problematic sequences of characters
+ safe_text = HANG_RE.sub(r"\1\1\1", text)
+ # Tokenize:
+ words = WORD_RE.findall(safe_text)
+ # Possibly alter the case, but avoid changing emoticons like :D into :d:
+ if not self.preserve_case:
+ words = [x if EMOTICON_RE.search(x) else x.lower() for x in words]
+ return words
+
+
+######################################################################
+# Normalization Functions
+######################################################################
+
+
+def reduce_lengthening(text):
+ """
+ Replace repeated character sequences of length 3 or greater with sequences of length 3.
+ """
+ pattern = regex.compile(r"(.)\1{2,}")
+ return pattern.sub(r"\1\1\1", text)
+
+
+def remove_handles(text):
+ """
+ Remove Twitter username handles from text.
+ """
+ pattern = regex.compile(
+ r"(?>> from transformers import BioGptModel, BioGptConfig
+
+ >>> # Initializing a BioGPT microsoft/biogpt style configuration
+ >>> configuration = BioGptConfig()
+
+ >>> # Initializing a model from the microsoft/biogpt style configuration
+ >>> model = BioGptModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "biogpt"
+
+ vocab_size: int = 42384
+ hidden_size: int = 1024
+ num_hidden_layers: int = 24
+ num_attention_heads: int = 16
+ intermediate_size: int = 4096
+ hidden_act: str = "gelu"
+ hidden_dropout_prob: float | int = 0.1
+ attention_probs_dropout_prob: float | int = 0.1
+ max_position_embeddings: int = 1024
+ initializer_range: float = 0.02
+ layer_norm_eps: float = 1e-12
+ scale_embedding: bool = True
+ use_cache: bool = True
+ layerdrop: float | int = 0.0
+ activation_dropout: float | int = 0.0
+ pad_token_id: int | None = 1
+ bos_token_id: int | None = 0
+ eos_token_id: int | list[int] | None = 2
+ tie_word_embeddings: bool = True
+
+
+__all__ = ["BioGptConfig"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/biogpt/modeling_biogpt.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/biogpt/modeling_biogpt.py
new file mode 100644
index 0000000000000000000000000000000000000000..0629ab8f6ff92af4a31f29d25d6fb41a45c5d4d7
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/biogpt/modeling_biogpt.py
@@ -0,0 +1,677 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/biogpt/modular_biogpt.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_biogpt.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2022 The HuggingFace Team and Microsoft Research AI4Science All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import math
+from collections.abc import Callable
+
+import torch
+import torch.nn as nn
+from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
+
+from ...activations import ACT2FN
+from ...cache_utils import Cache, DynamicCache, EncoderDecoderCache
+from ...generation import GenerationMixin
+from ...masking_utils import create_causal_mask
+from ...modeling_flash_attention_utils import FlashAttentionKwargs
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import (
+ BaseModelOutputWithPastAndCrossAttentions,
+ CausalLMOutputWithCrossAttentions,
+ SequenceClassifierOutputWithPast,
+ TokenClassifierOutput,
+)
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, logging
+from ...utils.generic import merge_with_config_defaults
+from ...utils.output_capturing import capture_outputs
+from .configuration_biogpt import BioGptConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+class BioGptLearnedPositionalEmbedding(nn.Embedding):
+ """
+ This module learns positional embeddings up to a fixed maximum size.
+ """
+
+ def __init__(self, num_embeddings: int, embedding_dim: int):
+ # BIOGPT is set up so that if padding_idx is specified then offset the embedding ids by 2
+ # and adjust num_embeddings appropriately. Other models don't have this hack
+ self.offset = 2
+ super().__init__(num_embeddings + self.offset, embedding_dim)
+
+ def forward(
+ self,
+ attention_mask: torch.LongTensor,
+ past_key_values_length: int = 0,
+ position_ids: torch.LongTensor | None = None,
+ ):
+ """`input_ids_shape` is expected to be [bsz x seqlen]."""
+
+ if position_ids is None:
+ position_ids = torch.cumsum(attention_mask, dim=1)
+ position_ids = (position_ids * attention_mask - 1).long()
+ # cut positions if `past_key_values_length` is > 0
+ position_ids = position_ids[:, past_key_values_length:]
+
+ return super().forward(position_ids + self.offset)
+
+
+class BioGptScaledWordEmbedding(nn.Embedding):
+ """
+ This module overrides nn.Embeddings' forward by multiplying with embeddings scale.
+ """
+
+ def __init__(self, num_embeddings: int, embedding_dim: int, padding_idx: int, embed_scale: float | None = 1.0):
+ super().__init__(num_embeddings, embedding_dim, padding_idx)
+ self.embed_scale = embed_scale
+
+ def forward(self, input_ids: torch.Tensor):
+ return super().forward(input_ids) * self.embed_scale
+
+
+def eager_attention_forward(
+ module: nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: torch.Tensor | None,
+ scaling: float | None = None,
+ dropout: float = 0.0,
+ **kwargs: Unpack[TransformersKwargs],
+):
+ if scaling is None:
+ scaling = query.size(-1) ** -0.5
+
+ # Take the dot product between "query" and "key" to get the raw attention scores.
+ attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
+
+ if attention_mask is not None:
+ attn_weights = attn_weights + attention_mask
+
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
+
+ attn_output = torch.matmul(attn_weights, value)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+
+ return attn_output, attn_weights
+
+
+class BioGptAttention(nn.Module):
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
+
+ def __init__(
+ self,
+ embed_dim: int,
+ num_heads: int,
+ dropout: float = 0.0,
+ is_decoder: bool = False,
+ bias: bool = True,
+ is_causal: bool = False,
+ config: BioGptConfig | None = None,
+ layer_idx: int | None = None,
+ ):
+ super().__init__()
+ self.embed_dim = embed_dim
+ self.num_heads = num_heads
+ self.dropout = dropout
+ self.head_dim = embed_dim // num_heads
+ self.config = config
+
+ if (self.head_dim * num_heads) != self.embed_dim:
+ raise ValueError(
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
+ f" and `num_heads`: {num_heads})."
+ )
+ self.scaling = self.head_dim**-0.5
+ self.is_decoder = is_decoder
+ self.is_causal = is_causal
+ self.layer_idx = layer_idx
+ if layer_idx is None and self.is_decoder:
+ logger.warning_once(
+ f"Instantiating a decoder {self.__class__.__name__} without passing `layer_idx` is not recommended and "
+ "will lead to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
+ "when creating this class."
+ )
+
+ self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
+ self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ key_value_states: torch.Tensor | None = None,
+ past_key_values: Cache | None = None,
+ attention_mask: torch.Tensor | None = None,
+ # TODO: we need a refactor so that the different attention modules can get their specific kwargs
+ # ATM, we have mixed things encoder, decoder, and encoder-decoder attn
+ **kwargs: Unpack[FlashAttentionKwargs],
+ ) -> tuple[torch.Tensor, torch.Tensor | None]:
+ """Input shape: Batch x Time x Channel"""
+
+ # if key_value_states are provided this layer is used as a cross-attention layer
+ # for the decoder
+ is_cross_attention = key_value_states is not None
+
+ # determine input shapes
+ input_shape = hidden_states.shape[:-1]
+
+ hidden_shape = (*input_shape, -1, self.head_dim)
+
+ # get query proj
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+
+ is_updated = False
+ if past_key_values is not None:
+ if isinstance(past_key_values, EncoderDecoderCache):
+ is_updated = past_key_values.is_updated.get(self.layer_idx)
+ if is_cross_attention:
+ # after the first generated id, we can subsequently re-use all key/value_states from cache
+ curr_past_key_values = past_key_values.cross_attention_cache
+ else:
+ curr_past_key_values = past_key_values.self_attention_cache
+ else:
+ curr_past_key_values = past_key_values
+
+ current_states = key_value_states if is_cross_attention else hidden_states
+ if is_cross_attention and past_key_values is not None and is_updated:
+ # reuse k,v, cross_attentions
+ key_states = curr_past_key_values.layers[self.layer_idx].keys
+ value_states = curr_past_key_values.layers[self.layer_idx].values
+ else:
+ key_states = self.k_proj(current_states)
+ value_states = self.v_proj(current_states)
+ kv_shape = (*current_states.shape[:-1], -1, self.head_dim)
+ key_states = key_states.view(kv_shape).transpose(1, 2)
+ value_states = value_states.view(kv_shape).transpose(1, 2)
+
+ if past_key_values is not None:
+ key_states, value_states = curr_past_key_values.update(key_states, value_states, self.layer_idx)
+ # set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls
+ if is_cross_attention and isinstance(past_key_values, EncoderDecoderCache):
+ past_key_values.is_updated[self.layer_idx] = True
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_states,
+ key_states,
+ value_states,
+ attention_mask,
+ dropout=0.0 if not self.training else self.dropout,
+ scaling=self.scaling,
+ **kwargs,
+ )
+
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ attn_output = self.out_proj(attn_output)
+
+ return attn_output, attn_weights
+
+
+class BioGptDecoderLayer(GradientCheckpointingLayer):
+ def __init__(self, config: BioGptConfig, layer_idx: int | None = None):
+ super().__init__()
+ self.embed_dim = config.hidden_size
+
+ self.self_attn = BioGptAttention(
+ embed_dim=self.embed_dim,
+ num_heads=config.num_attention_heads,
+ dropout=config.attention_probs_dropout_prob,
+ is_decoder=True,
+ is_causal=True,
+ config=config,
+ layer_idx=layer_idx,
+ )
+ self.dropout = config.hidden_dropout_prob
+ self.activation_fn = ACT2FN[config.hidden_act]
+ self.activation_dropout = config.activation_dropout
+
+ self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
+
+ self.fc1 = nn.Linear(self.embed_dim, config.intermediate_size)
+ self.fc2 = nn.Linear(config.intermediate_size, self.embed_dim)
+ self.final_layer_norm = nn.LayerNorm(self.embed_dim)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor | None = None,
+ past_key_values: Cache | None = None,
+ use_cache: bool | None = True,
+ position_ids: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.Tensor:
+ """
+ Args:
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
+ attention_mask (`torch.FloatTensor`): attention mask of size
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
+ past_key_values (`Cache`): cached past key and value projection states
+ """
+ residual = hidden_states
+
+ hidden_states = self.self_attn_layer_norm(hidden_states)
+
+ # Self Attention
+ hidden_states, _ = self.self_attn(
+ hidden_states=hidden_states,
+ past_key_values=past_key_values,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ **kwargs,
+ )
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
+ hidden_states = residual + hidden_states
+
+ # Fully Connected
+ residual = hidden_states
+ hidden_states = self.final_layer_norm(hidden_states)
+ hidden_states = self.fc1(hidden_states)
+ hidden_states = self.activation_fn(hidden_states)
+ hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
+ hidden_states = self.fc2(hidden_states)
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
+ hidden_states = residual + hidden_states
+
+ return hidden_states
+
+
+@auto_docstring
+class BioGptPreTrainedModel(PreTrainedModel):
+ config: BioGptConfig
+ base_model_prefix = "biogpt"
+ supports_gradient_checkpointing = True
+ _supports_flash_attn = True
+ _supports_sdpa = True
+ _supports_flex_attn = True
+ _can_compile_fullgraph = True
+ _can_record_outputs = {
+ "hidden_states": BioGptDecoderLayer,
+ "attentions": BioGptAttention,
+ }
+
+
+@auto_docstring
+class BioGptModel(BioGptPreTrainedModel):
+ def __init__(self, config: BioGptConfig):
+ super().__init__(config)
+ self.config = config
+ self.layerdrop = config.layerdrop
+ self.dropout = config.hidden_dropout_prob
+ self.embed_dim = config.hidden_size
+ self.padding_idx = config.pad_token_id
+ embed_scale = math.sqrt(config.hidden_size) if config.scale_embedding else 1.0
+
+ self.embed_tokens = BioGptScaledWordEmbedding(
+ config.vocab_size, self.embed_dim, self.padding_idx, embed_scale=embed_scale
+ )
+ self.embed_positions = BioGptLearnedPositionalEmbedding(config.max_position_embeddings, self.embed_dim)
+
+ self.layers = nn.ModuleList([BioGptDecoderLayer(config, layer_idx=i) for i in range(config.num_hidden_layers)])
+ self.layer_norm = nn.LayerNorm(self.embed_dim)
+
+ self.gradient_checkpointing = False
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @merge_with_config_defaults
+ @capture_outputs
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ past_key_values: Cache | None = None,
+ use_cache: bool | None = None,
+ position_ids: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutputWithPastAndCrossAttentions:
+ if (input_ids is None) ^ (inputs_embeds is not None):
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
+
+ if inputs_embeds is None:
+ inputs_embeds = self.embed_tokens(input_ids)
+
+ # initialize past_key_values
+ if use_cache and past_key_values is None:
+ past_key_values = DynamicCache(config=self.config)
+
+ batch_size, seq_length = inputs_embeds.size()[:-1]
+ past_key_values_length = past_key_values.get_seq_length() if past_key_values is not None else 0
+
+ if attention_mask is None:
+ # required mask seq length can be calculated via length of past cache
+ mask_seq_length = past_key_values_length + seq_length
+ attention_mask = torch.ones(batch_size, mask_seq_length, device=inputs_embeds.device)
+
+ self_attn_cache = past_key_values
+
+ causal_mask = create_causal_mask(
+ config=self.config,
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ past_key_values=self_attn_cache,
+ )
+
+ # embed positions
+ if position_ids is None:
+ position_ids = torch.arange(seq_length, device=inputs_embeds.device) + past_key_values_length
+ position_ids = position_ids.unsqueeze(0)
+
+ positions = self.embed_positions(attention_mask, past_key_values_length, position_ids=position_ids)
+ hidden_states = inputs_embeds + positions
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
+
+ for idx, decoder_layer in enumerate(self.layers):
+ if self.training:
+ dropout_probability = torch.rand([])
+ if dropout_probability < self.layerdrop:
+ continue
+
+ hidden_states = decoder_layer(
+ hidden_states,
+ attention_mask=causal_mask,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ position_ids=position_ids,
+ **kwargs,
+ )
+
+ hidden_states = self.layer_norm(hidden_states)
+
+ return BaseModelOutputWithPastAndCrossAttentions(
+ last_hidden_state=hidden_states,
+ past_key_values=past_key_values,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ BioGPT Model with a `language modeling` head on top for CLM fine-tuning.
+ """
+)
+class BioGptForCausalLM(BioGptPreTrainedModel, GenerationMixin):
+ _tied_weights_keys = {"output_projection.weight": "biogpt.embed_tokens.weight"}
+
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.biogpt = BioGptModel(config)
+ self.output_projection = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_output_embeddings(self):
+ return self.output_projection
+
+ def set_output_embeddings(self, new_embeddings):
+ self.output_projection = new_embeddings
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ past_key_values: Cache | None = None,
+ labels: torch.LongTensor | None = None,
+ use_cache: bool | None = None,
+ position_ids: torch.LongTensor | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | CausalLMOutputWithCrossAttentions:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
+ `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
+ are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
+ """
+ outputs = self.biogpt(
+ input_ids,
+ attention_mask=attention_mask,
+ inputs_embeds=inputs_embeds,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ position_ids=position_ids,
+ **kwargs,
+ )
+
+ hidden_states = outputs[0]
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
+ logits = self.output_projection(hidden_states[:, slice_indices, :])
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
+
+ return CausalLMOutputWithCrossAttentions(
+ loss=loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ cross_attentions=outputs.cross_attentions,
+ )
+
+
+@auto_docstring
+class BioGptForTokenClassification(BioGptPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+
+ self.biogpt = BioGptModel(config)
+ if hasattr(config, "classifier_dropout") and config.classifier_dropout is not None:
+ classifier_dropout = config.classifier_dropout
+ else:
+ classifier_dropout = config.hidden_dropout_prob
+ self.dropout = nn.Dropout(classifier_dropout)
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
+
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ use_cache: bool | None = None,
+ position_ids: torch.LongTensor | None = None,
+ **kwargs,
+ ) -> tuple | TokenClassifierOutput:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+ transformer_outputs = self.biogpt(
+ input_ids,
+ past_key_values=past_key_values,
+ attention_mask=attention_mask,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ position_ids=position_ids,
+ **kwargs,
+ )
+
+ hidden_states = transformer_outputs[0]
+ hidden_states = self.dropout(hidden_states)
+ logits = self.classifier(hidden_states)
+
+ loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ if attention_mask is not None:
+ active_loss = attention_mask.view(-1) == 1
+ active_logits = logits.view(-1, self.num_labels)
+ active_labels = torch.where(
+ active_loss, labels.view(-1), torch.tensor(loss_fct.ignore_index).type_as(labels)
+ )
+ loss = loss_fct(active_logits, active_labels)
+ else:
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+
+ return TokenClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=transformer_outputs.hidden_states,
+ attentions=transformer_outputs.attentions,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ The BioGpt Model transformer with a sequence classification head on top (linear layer).
+
+ [`BioGptForSequenceClassification`] uses the last token in order to do the classification, as other causal models
+ (e.g. GPT-2) do.
+
+ Since it does classification on the last token, it is required to know the position of the last token. If a
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
+ each row of the batch).
+ """
+)
+class BioGptForSequenceClassification(BioGptPreTrainedModel):
+ def __init__(self, config: BioGptConfig):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+ self.biogpt = BioGptModel(config)
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ use_cache: bool | None = None,
+ position_ids: torch.LongTensor | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ **kwargs,
+ ) -> tuple | SequenceClassifierOutputWithPast:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+ transformer_outputs = self.biogpt(
+ input_ids,
+ past_key_values=past_key_values,
+ attention_mask=attention_mask,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ position_ids=position_ids,
+ **kwargs,
+ )
+ hidden_states = transformer_outputs[0]
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
+ logits = self.score(hidden_states[:, slice_indices, :])
+
+ if input_ids is not None:
+ batch_size, sequence_length = input_ids.shape[:2]
+ else:
+ batch_size, sequence_length = inputs_embeds.shape[:2]
+
+ if self.config.pad_token_id is None:
+ sequence_length = -1
+ else:
+ if input_ids is not None:
+ sequence_length = (torch.ne(input_ids, self.config.pad_token_id).sum(-1) - 1).to(logits.device)
+ else:
+ sequence_length = -1
+ logger.warning_once(
+ f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
+ "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
+ )
+
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_length]
+
+ loss = None
+ if labels is not None:
+ if self.config.problem_type is None:
+ if self.num_labels == 1:
+ self.config.problem_type = "regression"
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
+ self.config.problem_type = "single_label_classification"
+ else:
+ self.config.problem_type = "multi_label_classification"
+
+ if self.config.problem_type == "regression":
+ loss_fct = MSELoss()
+ if self.num_labels == 1:
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
+ else:
+ loss = loss_fct(pooled_logits, labels)
+ elif self.config.problem_type == "single_label_classification":
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
+ elif self.config.problem_type == "multi_label_classification":
+ loss_fct = BCEWithLogitsLoss()
+ loss = loss_fct(pooled_logits, labels)
+
+ return SequenceClassifierOutputWithPast(
+ loss=loss,
+ logits=pooled_logits,
+ past_key_values=transformer_outputs.past_key_values,
+ hidden_states=transformer_outputs.hidden_states,
+ attentions=transformer_outputs.attentions,
+ )
+
+ def get_input_embeddings(self):
+ return self.biogpt.embed_tokens
+
+ def set_input_embeddings(self, value):
+ self.biogpt.embed_tokens = value
+
+
+__all__ = [
+ "BioGptForCausalLM",
+ "BioGptForTokenClassification",
+ "BioGptForSequenceClassification",
+ "BioGptModel",
+ "BioGptPreTrainedModel",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/biogpt/modular_biogpt.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/biogpt/modular_biogpt.py
new file mode 100644
index 0000000000000000000000000000000000000000..82d636f30b235e74de4e6b3ffe51a0c388d28c23
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/biogpt/modular_biogpt.py
@@ -0,0 +1,509 @@
+# Copyright 2022 The HuggingFace Team and Microsoft Research AI4Science All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch BioGPT model."""
+
+import math
+
+import torch
+import torch.nn as nn
+from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
+
+from ...activations import ACT2FN
+from ...cache_utils import Cache, DynamicCache
+from ...generation import GenerationMixin
+from ...masking_utils import create_causal_mask
+from ...modeling_outputs import (
+ BaseModelOutputWithPastAndCrossAttentions,
+ CausalLMOutputWithCrossAttentions,
+ SequenceClassifierOutputWithPast,
+ TokenClassifierOutput,
+)
+from ...modeling_utils import PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import (
+ TransformersKwargs,
+ auto_docstring,
+ can_return_tuple,
+ logger,
+)
+from ...utils.generic import merge_with_config_defaults
+from ...utils.output_capturing import capture_outputs
+from ..bart.modeling_bart import (
+ BartAttention,
+ BartDecoderLayer,
+ BartScaledWordEmbedding,
+)
+from ..opt.modeling_opt import OPTLearnedPositionalEmbedding
+from .configuration_biogpt import BioGptConfig
+
+
+class BioGptLearnedPositionalEmbedding(OPTLearnedPositionalEmbedding):
+ def forward(
+ self,
+ attention_mask: torch.LongTensor,
+ past_key_values_length: int = 0,
+ position_ids: torch.LongTensor | None = None,
+ ):
+ """`input_ids_shape` is expected to be [bsz x seqlen]."""
+ return super().forward(attention_mask, past_key_values_length, position_ids)
+
+
+class BioGptScaledWordEmbedding(BartScaledWordEmbedding):
+ pass
+
+
+class BioGptAttention(BartAttention):
+ pass
+
+
+class BioGptDecoderLayer(BartDecoderLayer):
+ def __init__(self, config: BioGptConfig, layer_idx: int | None = None):
+ super().__init__(config)
+ self.embed_dim = config.hidden_size
+
+ self.self_attn = BioGptAttention(
+ embed_dim=self.embed_dim,
+ num_heads=config.num_attention_heads,
+ dropout=config.attention_probs_dropout_prob,
+ is_decoder=True,
+ is_causal=True,
+ config=config,
+ layer_idx=layer_idx,
+ )
+ self.dropout = config.hidden_dropout_prob
+ self.activation_fn = ACT2FN[config.hidden_act]
+
+ self.fc1 = nn.Linear(self.embed_dim, config.intermediate_size)
+ self.fc2 = nn.Linear(config.intermediate_size, self.embed_dim)
+
+ del self.encoder_attn
+ del self.encoder_attn_layer_norm
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor | None = None,
+ past_key_values: Cache | None = None,
+ use_cache: bool | None = True,
+ position_ids: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.Tensor:
+ """
+ Args:
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
+ attention_mask (`torch.FloatTensor`): attention mask of size
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
+ past_key_values (`Cache`): cached past key and value projection states
+ """
+ residual = hidden_states
+
+ hidden_states = self.self_attn_layer_norm(hidden_states)
+
+ # Self Attention
+ hidden_states, _ = self.self_attn(
+ hidden_states=hidden_states,
+ past_key_values=past_key_values,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ **kwargs,
+ )
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
+ hidden_states = residual + hidden_states
+
+ # Fully Connected
+ residual = hidden_states
+ hidden_states = self.final_layer_norm(hidden_states)
+ hidden_states = self.fc1(hidden_states)
+ hidden_states = self.activation_fn(hidden_states)
+ hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
+ hidden_states = self.fc2(hidden_states)
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
+ hidden_states = residual + hidden_states
+
+ return hidden_states
+
+
+@auto_docstring
+class BioGptPreTrainedModel(PreTrainedModel):
+ config: BioGptConfig
+ base_model_prefix = "biogpt"
+ supports_gradient_checkpointing = True
+ _supports_flash_attn = True
+ _supports_sdpa = True
+ _supports_flex_attn = True
+ _can_compile_fullgraph = True
+ _can_record_outputs = {
+ "hidden_states": BioGptDecoderLayer,
+ "attentions": BioGptAttention,
+ }
+
+
+@auto_docstring
+class BioGptModel(BioGptPreTrainedModel):
+ def __init__(self, config: BioGptConfig):
+ super().__init__(config)
+ self.config = config
+ self.layerdrop = config.layerdrop
+ self.dropout = config.hidden_dropout_prob
+ self.embed_dim = config.hidden_size
+ self.padding_idx = config.pad_token_id
+ embed_scale = math.sqrt(config.hidden_size) if config.scale_embedding else 1.0
+
+ self.embed_tokens = BioGptScaledWordEmbedding(
+ config.vocab_size, self.embed_dim, self.padding_idx, embed_scale=embed_scale
+ )
+ self.embed_positions = BioGptLearnedPositionalEmbedding(config.max_position_embeddings, self.embed_dim)
+
+ self.layers = nn.ModuleList([BioGptDecoderLayer(config, layer_idx=i) for i in range(config.num_hidden_layers)])
+ self.layer_norm = nn.LayerNorm(self.embed_dim)
+
+ self.gradient_checkpointing = False
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @merge_with_config_defaults
+ @capture_outputs
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ past_key_values: Cache | None = None,
+ use_cache: bool | None = None,
+ position_ids: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutputWithPastAndCrossAttentions:
+ if (input_ids is None) ^ (inputs_embeds is not None):
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
+
+ if inputs_embeds is None:
+ inputs_embeds = self.embed_tokens(input_ids)
+
+ # initialize past_key_values
+ if use_cache and past_key_values is None:
+ past_key_values = DynamicCache(config=self.config)
+
+ batch_size, seq_length = inputs_embeds.size()[:-1]
+ past_key_values_length = past_key_values.get_seq_length() if past_key_values is not None else 0
+
+ if attention_mask is None:
+ # required mask seq length can be calculated via length of past cache
+ mask_seq_length = past_key_values_length + seq_length
+ attention_mask = torch.ones(batch_size, mask_seq_length, device=inputs_embeds.device)
+
+ self_attn_cache = past_key_values
+
+ causal_mask = create_causal_mask(
+ config=self.config,
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ past_key_values=self_attn_cache,
+ )
+
+ # embed positions
+ if position_ids is None:
+ position_ids = torch.arange(seq_length, device=inputs_embeds.device) + past_key_values_length
+ position_ids = position_ids.unsqueeze(0)
+
+ positions = self.embed_positions(attention_mask, past_key_values_length, position_ids=position_ids)
+ hidden_states = inputs_embeds + positions
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
+
+ for idx, decoder_layer in enumerate(self.layers):
+ if self.training:
+ dropout_probability = torch.rand([])
+ if dropout_probability < self.layerdrop:
+ continue
+
+ hidden_states = decoder_layer(
+ hidden_states,
+ attention_mask=causal_mask,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ position_ids=position_ids,
+ **kwargs,
+ )
+
+ hidden_states = self.layer_norm(hidden_states)
+
+ return BaseModelOutputWithPastAndCrossAttentions(
+ last_hidden_state=hidden_states,
+ past_key_values=past_key_values,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ BioGPT Model with a `language modeling` head on top for CLM fine-tuning.
+ """
+)
+class BioGptForCausalLM(BioGptPreTrainedModel, GenerationMixin):
+ _tied_weights_keys = {"output_projection.weight": "biogpt.embed_tokens.weight"}
+
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.biogpt = BioGptModel(config)
+ self.output_projection = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_output_embeddings(self):
+ return self.output_projection
+
+ def set_output_embeddings(self, new_embeddings):
+ self.output_projection = new_embeddings
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ past_key_values: Cache | None = None,
+ labels: torch.LongTensor | None = None,
+ use_cache: bool | None = None,
+ position_ids: torch.LongTensor | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | CausalLMOutputWithCrossAttentions:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
+ `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
+ are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
+ """
+ outputs = self.biogpt(
+ input_ids,
+ attention_mask=attention_mask,
+ inputs_embeds=inputs_embeds,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ position_ids=position_ids,
+ **kwargs,
+ )
+
+ hidden_states = outputs[0]
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
+ logits = self.output_projection(hidden_states[:, slice_indices, :])
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
+
+ return CausalLMOutputWithCrossAttentions(
+ loss=loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ cross_attentions=outputs.cross_attentions,
+ )
+
+
+@auto_docstring
+class BioGptForTokenClassification(BioGptPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+
+ self.biogpt = BioGptModel(config)
+ if hasattr(config, "classifier_dropout") and config.classifier_dropout is not None:
+ classifier_dropout = config.classifier_dropout
+ else:
+ classifier_dropout = config.hidden_dropout_prob
+ self.dropout = nn.Dropout(classifier_dropout)
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
+
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ use_cache: bool | None = None,
+ position_ids: torch.LongTensor | None = None,
+ **kwargs,
+ ) -> tuple | TokenClassifierOutput:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+ transformer_outputs = self.biogpt(
+ input_ids,
+ past_key_values=past_key_values,
+ attention_mask=attention_mask,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ position_ids=position_ids,
+ **kwargs,
+ )
+
+ hidden_states = transformer_outputs[0]
+ hidden_states = self.dropout(hidden_states)
+ logits = self.classifier(hidden_states)
+
+ loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ if attention_mask is not None:
+ active_loss = attention_mask.view(-1) == 1
+ active_logits = logits.view(-1, self.num_labels)
+ active_labels = torch.where(
+ active_loss, labels.view(-1), torch.tensor(loss_fct.ignore_index).type_as(labels)
+ )
+ loss = loss_fct(active_logits, active_labels)
+ else:
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+
+ return TokenClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=transformer_outputs.hidden_states,
+ attentions=transformer_outputs.attentions,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ The BioGpt Model transformer with a sequence classification head on top (linear layer).
+
+ [`BioGptForSequenceClassification`] uses the last token in order to do the classification, as other causal models
+ (e.g. GPT-2) do.
+
+ Since it does classification on the last token, it is required to know the position of the last token. If a
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
+ each row of the batch).
+ """
+)
+class BioGptForSequenceClassification(BioGptPreTrainedModel):
+ def __init__(self, config: BioGptConfig):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+ self.biogpt = BioGptModel(config)
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ use_cache: bool | None = None,
+ position_ids: torch.LongTensor | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ **kwargs,
+ ) -> tuple | SequenceClassifierOutputWithPast:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+ transformer_outputs = self.biogpt(
+ input_ids,
+ past_key_values=past_key_values,
+ attention_mask=attention_mask,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ position_ids=position_ids,
+ **kwargs,
+ )
+ hidden_states = transformer_outputs[0]
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
+ logits = self.score(hidden_states[:, slice_indices, :])
+
+ if input_ids is not None:
+ batch_size, sequence_length = input_ids.shape[:2]
+ else:
+ batch_size, sequence_length = inputs_embeds.shape[:2]
+
+ if self.config.pad_token_id is None:
+ sequence_length = -1
+ else:
+ if input_ids is not None:
+ sequence_length = (torch.ne(input_ids, self.config.pad_token_id).sum(-1) - 1).to(logits.device)
+ else:
+ sequence_length = -1
+ logger.warning_once(
+ f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
+ "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
+ )
+
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_length]
+
+ loss = None
+ if labels is not None:
+ if self.config.problem_type is None:
+ if self.num_labels == 1:
+ self.config.problem_type = "regression"
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
+ self.config.problem_type = "single_label_classification"
+ else:
+ self.config.problem_type = "multi_label_classification"
+
+ if self.config.problem_type == "regression":
+ loss_fct = MSELoss()
+ if self.num_labels == 1:
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
+ else:
+ loss = loss_fct(pooled_logits, labels)
+ elif self.config.problem_type == "single_label_classification":
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
+ elif self.config.problem_type == "multi_label_classification":
+ loss_fct = BCEWithLogitsLoss()
+ loss = loss_fct(pooled_logits, labels)
+
+ return SequenceClassifierOutputWithPast(
+ loss=loss,
+ logits=pooled_logits,
+ past_key_values=transformer_outputs.past_key_values,
+ hidden_states=transformer_outputs.hidden_states,
+ attentions=transformer_outputs.attentions,
+ )
+
+ def get_input_embeddings(self):
+ return self.biogpt.embed_tokens
+
+ def set_input_embeddings(self, value):
+ self.biogpt.embed_tokens = value
+
+
+__all__ = [
+ "BioGptForCausalLM",
+ "BioGptForTokenClassification",
+ "BioGptForSequenceClassification",
+ "BioGptModel",
+ "BioGptPreTrainedModel",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/biogpt/tokenization_biogpt.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/biogpt/tokenization_biogpt.py
new file mode 100644
index 0000000000000000000000000000000000000000..1bf3e103a0eb837238bdd0f620c7ef423f73387c
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/biogpt/tokenization_biogpt.py
@@ -0,0 +1,329 @@
+# Copyright 2022 The HuggingFace Team and Microsoft Research AI4Science. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Tokenization classes for BioGPT."""
+
+import json
+import os
+
+from ...tokenization_python import PreTrainedTokenizer
+from ...utils import logging
+
+
+logger = logging.get_logger(__name__)
+
+VOCAB_FILES_NAMES = {
+ "vocab_file": "vocab.json",
+ "merges_file": "merges.txt",
+}
+
+
+def get_pairs(word):
+ """
+ Return set of symbol pairs in a word. word is represented as tuple of symbols (symbols being variable-length
+ strings)
+ """
+ pairs = set()
+ prev_char = word[0]
+ for char in word[1:]:
+ pairs.add((prev_char, char))
+ prev_char = char
+ return pairs
+
+
+class BioGptTokenizer(PreTrainedTokenizer):
+ """
+ Construct an FAIRSEQ Transformer tokenizer. Moses tokenization followed by Byte-Pair Encoding.
+
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
+ this superclass for more information regarding those methods.
+
+ Args:
+ vocab_file (`str`):
+ Path to the vocabulary file.
+ merges_file (`str`):
+ Merges file.
+ unk_token (`str`, *optional*, defaults to `""`):
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
+ token instead.
+ bos_token (`str`, *optional*, defaults to `""`):
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
+
+
+
+ When building a sequence using special tokens, this is not the token that is used for the beginning of
+ sequence. The token used is the `cls_token`.
+
+
+
+ eos_token (`str`, *optional*, defaults to `""`):
+ The end of sequence token.
+
+
+
+ When building a sequence using special tokens, this is not the token that is used for the end of sequence.
+ The token used is the `sep_token`.
+
+
+
+ sep_token (`str`, *optional*, defaults to `""`):
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
+ sequence classification or for a text and a question for question answering. It is also used as the last
+ token of a sequence built with special tokens.
+ pad_token (`str`, *optional*, defaults to `""`):
+ The token used for padding, for example when batching sequences of different lengths.
+ """
+
+ vocab_files_names = VOCAB_FILES_NAMES
+ model_input_names = ["input_ids", "attention_mask"]
+
+ def __init__(
+ self,
+ vocab_file,
+ merges_file,
+ unk_token="",
+ bos_token="",
+ eos_token="",
+ sep_token="",
+ pad_token="",
+ **kwargs,
+ ):
+ try:
+ import sacremoses
+ except ImportError:
+ raise ImportError(
+ "You need to install sacremoses to use BioGptTokenizer. "
+ "See https://pypi.org/project/sacremoses/ for installation."
+ )
+
+ self.lang = "en"
+ self.sm = sacremoses
+ # cache of sm.MosesTokenizer instance
+ self.cache_moses_tokenizer = {}
+ self.cache_moses_detokenizer = {}
+
+ """ Initialisation"""
+ with open(vocab_file, encoding="utf-8") as vocab_handle:
+ self.encoder = json.load(vocab_handle)
+ self.decoder = {v: k for k, v in self.encoder.items()}
+ with open(merges_file, encoding="utf-8") as merges_handle:
+ merges = merges_handle.read().split("\n")[:-1]
+ merges = [tuple(merge.split()[:2]) for merge in merges]
+ self.bpe_ranks = dict(zip(merges, range(len(merges))))
+ self.cache = {}
+
+ super().__init__(
+ bos_token=bos_token,
+ eos_token=eos_token,
+ sep_token=sep_token,
+ unk_token=unk_token,
+ pad_token=pad_token,
+ **kwargs,
+ )
+
+ @property
+ def vocab_size(self):
+ """Returns vocab size"""
+ return len(self.encoder)
+
+ def get_vocab(self):
+ return dict(self.encoder, **self.added_tokens_encoder)
+
+ def moses_tokenize(self, text, lang):
+ if lang not in self.cache_moses_tokenizer:
+ moses_tokenizer = self.sm.MosesTokenizer(lang=lang)
+ self.cache_moses_tokenizer[lang] = moses_tokenizer
+ return self.cache_moses_tokenizer[lang].tokenize(
+ text, aggressive_dash_splits=True, return_str=False, escape=True
+ )
+
+ def moses_detokenize(self, tokens, lang):
+ if lang not in self.cache_moses_detokenizer:
+ moses_detokenizer = self.sm.MosesDetokenizer(lang=lang)
+ self.cache_moses_detokenizer[lang] = moses_detokenizer
+ return self.cache_moses_detokenizer[lang].detokenize(tokens)
+
+ def bpe(self, token):
+ word = tuple(token[:-1]) + (token[-1] + "",)
+ if token in self.cache:
+ return self.cache[token]
+ pairs = get_pairs(word)
+
+ if not pairs:
+ return token + ""
+
+ while True:
+ bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
+ if bigram not in self.bpe_ranks:
+ break
+ first, second = bigram
+ new_word = []
+ i = 0
+ while i < len(word):
+ try:
+ j = word.index(first, i)
+ except ValueError:
+ new_word.extend(word[i:])
+ break
+ else:
+ new_word.extend(word[i:j])
+ i = j
+
+ if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
+ new_word.append(first + second)
+ i += 2
+ else:
+ new_word.append(word[i])
+ i += 1
+ new_word = tuple(new_word)
+ word = new_word
+ if len(word) == 1:
+ break
+ else:
+ pairs = get_pairs(word)
+ word = " ".join(word)
+ if word == "\n ":
+ word = "\n"
+ self.cache[token] = word
+ return word
+
+ def _tokenize(self, text, bypass_tokenizer=False):
+ """Returns a tokenized string."""
+ if bypass_tokenizer:
+ text = text.split()
+ else:
+ text = self.moses_tokenize(text, self.lang)
+
+ split_tokens = []
+ for token in text:
+ if token:
+ split_tokens.extend(list(self.bpe(token).split(" ")))
+
+ return split_tokens
+
+ def _convert_token_to_id(self, token):
+ """Converts a token (str) in an id using the vocab."""
+ return self.encoder.get(token, self.encoder.get(self.unk_token))
+
+ def _convert_id_to_token(self, index):
+ """Converts an index (integer) in a token (str) using the vocab."""
+ return self.decoder.get(index, self.unk_token)
+
+ def convert_tokens_to_string(self, tokens):
+ """Converts a sequence of tokens (string) in a single string."""
+ # remove BPE
+ tokens = [t.replace(" ", "").replace("", " ") for t in tokens]
+ tokens = "".join(tokens).split()
+ # detokenize
+ text = self.moses_detokenize(tokens, self.lang)
+ return text
+
+ def build_inputs_with_special_tokens(
+ self, token_ids_0: list[int], token_ids_1: list[int] | None = None
+ ) -> list[int]:
+ """
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
+ adding special tokens. A BioGPT sequence has the following format:
+
+ - single sequence: ` X `
+ - pair of sequences: ` A B `
+
+ Args:
+ token_ids_0 (`List[int]`):
+ List of IDs to which the special tokens will be added.
+ token_ids_1 (`List[int]`, *optional*):
+ Optional second list of IDs for sequence pairs.
+
+ Returns:
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
+ """
+ if token_ids_1 is None:
+ return [self.sep_token_id] + token_ids_0
+ sep = [self.sep_token_id]
+ return sep + token_ids_0 + sep + token_ids_1
+
+ def get_special_tokens_mask(
+ self, token_ids_0: list[int], token_ids_1: list[int] | None = None, already_has_special_tokens: bool = False
+ ) -> list[int]:
+ """
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
+ special tokens using the tokenizer `prepare_for_model` method.
+
+ Args:
+ token_ids_0 (`List[int]`):
+ List of IDs.
+ token_ids_1 (`List[int]`, *optional*):
+ Optional second list of IDs for sequence pairs.
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
+ Whether or not the token list is already formatted with special tokens for the model.
+
+ Returns:
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
+ """
+ if already_has_special_tokens:
+ return super().get_special_tokens_mask(
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
+ )
+ # no bos used in fairseq
+ if token_ids_1 is not None:
+ return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1))
+ return [1] + ([0] * len(token_ids_0))
+
+ def save_vocabulary(self, save_directory: str, filename_prefix: str | None = None) -> tuple[str]:
+ if not os.path.isdir(save_directory):
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
+ return
+ vocab_file = os.path.join(
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
+ )
+ merge_file = os.path.join(
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
+ )
+
+ with open(vocab_file, "w", encoding="utf-8") as f:
+ f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
+
+ index = 0
+ with open(merge_file, "w", encoding="utf-8") as writer:
+ for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
+ if index != token_index:
+ logger.warning(
+ f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
+ " Please check that the tokenizer is not corrupted!"
+ )
+ index = token_index
+ writer.write(" ".join(bpe_tokens) + "\n")
+ index += 1
+
+ return vocab_file, merge_file
+
+ def __getstate__(self):
+ state = self.__dict__.copy()
+ state["sm"] = None
+ return state
+
+ def __setstate__(self, d):
+ self.__dict__ = d
+
+ try:
+ import sacremoses
+ except ImportError:
+ raise ImportError(
+ "You need to install sacremoses to use XLMTokenizer. "
+ "See https://pypi.org/project/sacremoses/ for installation."
+ )
+
+ self.sm = sacremoses
+
+
+__all__ = ["BioGptTokenizer"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bitnet/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bitnet/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a77786d44aee531e01e53cc6b229ad795c088a62
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bitnet/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bitnet/__pycache__/configuration_bitnet.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bitnet/__pycache__/configuration_bitnet.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..36a65688d74c0295f5c9e290fe0ad0e701fe4eea
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bitnet/__pycache__/configuration_bitnet.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bitnet/__pycache__/modeling_bitnet.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bitnet/__pycache__/modeling_bitnet.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..40044d4663316c9989429598eeb3642792326c99
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bitnet/__pycache__/modeling_bitnet.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bitnet/__pycache__/modular_bitnet.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bitnet/__pycache__/modular_bitnet.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1e6e762f4713a6d8d6fde9de42cfb9bbb8cfeeb3
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bitnet/__pycache__/modular_bitnet.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/blenderbot/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/blenderbot/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c49cae6e4b4fa5999c5bb2a7ac6abee57b8cbeb8
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/blenderbot/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/blenderbot/__pycache__/configuration_blenderbot.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/blenderbot/__pycache__/configuration_blenderbot.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ce50e319beef3b9fdfe5bed71a091e81982e4133
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/blenderbot/__pycache__/configuration_blenderbot.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/blenderbot/__pycache__/modeling_blenderbot.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/blenderbot/__pycache__/modeling_blenderbot.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bef28cf4afc49f2fdd17adbd98bab7e2e0521c55
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/blenderbot/__pycache__/modeling_blenderbot.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/blenderbot/__pycache__/tokenization_blenderbot.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/blenderbot/__pycache__/tokenization_blenderbot.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..65716aa9f41e720b888b0bcac10f0db216134c5c
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/blenderbot/__pycache__/tokenization_blenderbot.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/blip_2/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/blip_2/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..0717e81fca606edde774ad19092472bf59b4701a
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/blip_2/__init__.py
@@ -0,0 +1,28 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_blip_2 import *
+ from .modeling_blip_2 import *
+ from .processing_blip_2 import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/blip_2/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/blip_2/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..290697bbd6363629a897155640db3aebe337980f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/blip_2/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/blip_2/__pycache__/configuration_blip_2.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/blip_2/__pycache__/configuration_blip_2.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..93921bc08cb7cbcd4d709754d81d9a4be2920e48
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/blip_2/__pycache__/configuration_blip_2.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/blip_2/__pycache__/modeling_blip_2.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/blip_2/__pycache__/modeling_blip_2.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d442644a3c88d9e79ca012fc471916b4d607dfe2
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/blip_2/__pycache__/modeling_blip_2.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/blip_2/__pycache__/processing_blip_2.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/blip_2/__pycache__/processing_blip_2.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..063fad5c27d85c62f609c2caed22d17da3cfecfa
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/blip_2/__pycache__/processing_blip_2.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/blip_2/configuration_blip_2.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/blip_2/configuration_blip_2.py
new file mode 100644
index 0000000000000000000000000000000000000000..b0664ae942572f58dcd90c8f17bdb630eaa80a19
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/blip_2/configuration_blip_2.py
@@ -0,0 +1,187 @@
+# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""BLIP-2 model configuration"""
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
+from ...utils import auto_docstring, logging
+from ..auto import CONFIG_MAPPING, AutoConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+@auto_docstring(checkpoint="Salesforce/blip2-opt-2.7b")
+@strict
+class Blip2VisionConfig(PreTrainedConfig):
+ r"""
+ Example:
+
+ ```python
+ >>> from transformers import Blip2VisionConfig, Blip2VisionModel
+
+ >>> # Initializing a Blip2VisionConfig with Salesforce/blip2-opt-2.7b style configuration
+ >>> configuration = Blip2VisionConfig()
+
+ >>> # Initializing a Blip2VisionModel (with random weights) from the Salesforce/blip2-opt-2.7b style configuration
+ >>> model = Blip2VisionModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "blip_2_vision_model"
+ base_config_key = "vision_config"
+
+ hidden_size: int = 1408
+ intermediate_size: int = 6144
+ num_hidden_layers: int = 39
+ num_attention_heads: int = 16
+ image_size: int | list[int] | tuple[int, int] = 224
+ patch_size: int | list[int] | tuple[int, int] = 14
+ hidden_act: str = "gelu"
+ layer_norm_eps: float = 1e-6
+ attention_dropout: float | int = 0.0
+ initializer_range: float = 1e-10
+ qkv_bias: bool = True
+
+
+@auto_docstring(checkpoint="Salesforce/blip2-opt-2.7b")
+@strict
+class Blip2QFormerConfig(PreTrainedConfig):
+ r"""
+ cross_attention_frequency (`int`, *optional*, defaults to 2):
+ The frequency of adding cross-attention to the Transformer layers.
+ use_qformer_text_input (`bool`, *optional*, defaults to `False`):
+ Whether to use BERT-style embeddings.
+
+ Examples:
+
+ ```python
+ >>> from transformers import Blip2QFormerConfig, Blip2QFormerModel
+
+ >>> # Initializing a BLIP-2 Salesforce/blip2-opt-2.7b style configuration
+ >>> configuration = Blip2QFormerConfig()
+
+ >>> # Initializing a model (with random weights) from the Salesforce/blip2-opt-2.7b style configuration
+ >>> model = Blip2QFormerModel(configuration)
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "blip_2_qformer"
+ base_config_key = "qformer_config"
+
+ vocab_size: int = 30522
+ hidden_size: int = 768
+ num_hidden_layers: int = 12
+ num_attention_heads: int = 12
+ intermediate_size: int = 3072
+ hidden_act: str = "gelu"
+ hidden_dropout_prob: float | int = 0.1
+ attention_probs_dropout_prob: float | int = 0.1
+ max_position_embeddings: int = 512
+ initializer_range: float = 0.02
+ layer_norm_eps: float = 1e-12
+ pad_token_id: int | None = 0
+ cross_attention_frequency: int = 2
+ encoder_hidden_size: int = 1408
+ use_qformer_text_input: bool = False
+
+
+@auto_docstring(checkpoint="Salesforce/blip2-opt-2.7b")
+@strict
+class Blip2Config(PreTrainedConfig):
+ r"""
+ qformer_config (`dict`, *optional*):
+ Dictionary of configuration options used to initialize [`Blip2QFormerConfig`].
+ num_query_tokens (`int`, *optional*, defaults to 32):
+ The number of query tokens passed through the Transformer.
+ image_text_hidden_size (`int`, *optional*, defaults to 256):
+ Dimensionality of the hidden state of the image-text fusion layer.
+
+ Example:
+
+ ```python
+ >>> from transformers import (
+ ... Blip2VisionConfig,
+ ... Blip2QFormerConfig,
+ ... OPTConfig,
+ ... Blip2Config,
+ ... Blip2ForConditionalGeneration,
+ ... )
+
+ >>> # Initializing a Blip2Config with Salesforce/blip2-opt-2.7b style configuration
+ >>> configuration = Blip2Config()
+
+ >>> # Initializing a Blip2ForConditionalGeneration (with random weights) from the Salesforce/blip2-opt-2.7b style configuration
+ >>> model = Blip2ForConditionalGeneration(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+
+ >>> # We can also initialize a Blip2Config from a Blip2VisionConfig, Blip2QFormerConfig and any PreTrainedConfig
+
+ >>> # Initializing BLIP-2 vision, BLIP-2 Q-Former and language model configurations
+ >>> vision_config = Blip2VisionConfig()
+ >>> qformer_config = Blip2QFormerConfig()
+ >>> text_config = OPTConfig()
+
+ >>> config = Blip2Config(vision_config=vision_config, qformer_config=qformer_config, text_config=text_config)
+ ```"""
+
+ model_type = "blip-2"
+ attribute_map = {
+ "image_token_id": "image_token_index",
+ }
+ sub_configs = {"text_config": AutoConfig, "qformer_config": Blip2QFormerConfig, "vision_config": Blip2VisionConfig}
+
+ vision_config: dict | PreTrainedConfig | None = None
+ qformer_config: dict | PreTrainedConfig | None = None
+ text_config: dict | PreTrainedConfig | None = None
+ num_query_tokens: int = 32
+ image_text_hidden_size: int = 256
+ image_token_index: int | None = None
+ initializer_factor: float = 1.0
+ initializer_range: float = 0.02
+
+ def __post_init__(self, **kwargs):
+ if self.text_config is None:
+ self.text_config = CONFIG_MAPPING["opt"]()
+ logger.info("text_config is None. Initializing the text config with default values (`OPTConfig`).")
+ elif isinstance(self.text_config, dict):
+ text_model_type = self.text_config.get("model_type", "opt")
+ self.text_config = CONFIG_MAPPING[text_model_type](**self.text_config)
+
+ if self.qformer_config is None:
+ self.qformer_config = Blip2QFormerConfig()
+ logger.info("qformer_config is None. Initializing the Blip2QFormerConfig with default values.")
+ elif isinstance(self.qformer_config, dict):
+ self.qformer_config = Blip2QFormerConfig(**self.qformer_config)
+
+ if self.vision_config is None:
+ self.vision_config = Blip2VisionConfig()
+ logger.info("`vision_config` is `None`. initializing the `Blip2VisionConfig` with default values.")
+ elif isinstance(self.vision_config, dict):
+ self.vision_config = Blip2VisionConfig(**self.vision_config)
+
+ self.qformer_config.encoder_hidden_size = self.vision_config.hidden_size
+ self.use_decoder_only_language_model = self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
+ kwargs["is_encoder_decoder"] = self.text_config.is_encoder_decoder
+ super().__post_init__(**kwargs)
+
+
+__all__ = ["Blip2Config", "Blip2QFormerConfig", "Blip2VisionConfig"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/blip_2/modeling_blip_2.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/blip_2/modeling_blip_2.py
new file mode 100644
index 0000000000000000000000000000000000000000..c51a722ea19cb73ff3b2b5b55606dbb34db38bac
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/blip_2/modeling_blip_2.py
@@ -0,0 +1,2076 @@
+# Copyright 2023 The Salesforce Authors and The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch BLIP-2 model."""
+
+import math
+from collections.abc import Callable
+from dataclasses import dataclass
+from typing import Any
+
+import torch
+from torch import nn
+from torch.nn import CrossEntropyLoss
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...generation import GenerationMixin
+from ...masking_utils import create_bidirectional_mask
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import (
+ BaseModelOutput,
+ BaseModelOutputWithPast,
+ BaseModelOutputWithPastAndCrossAttentions,
+ BaseModelOutputWithPooling,
+ BaseModelOutputWithPoolingAndCrossAttentions,
+ CausalLMOutputWithPast,
+ Seq2SeqLMOutput,
+)
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
+from ...processing_utils import Unpack
+from ...pytorch_utils import apply_chunking_to_forward
+from ...utils import (
+ ModelOutput,
+ TransformersKwargs,
+ auto_docstring,
+ can_return_tuple,
+ filter_out_non_signature_kwargs,
+ logging,
+ torch_int,
+)
+from ...utils.generic import merge_with_config_defaults
+from ...utils.output_capturing import OutputRecorder, capture_outputs
+from ..auto import AutoModelForCausalLM, AutoModelForSeq2SeqLM
+from .configuration_blip_2 import Blip2Config, Blip2QFormerConfig, Blip2VisionConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+@auto_docstring
+@dataclass
+class BaseModelOutputWithVisionQformerOutputs(BaseModelOutputWithPooling):
+ r"""
+ vision_outputs (`BaseModelOutputWithPooling`):
+ Outputs of the vision encoder.
+ qformer_outputs (`BaseModelOutputWithPoolingAndCrossAttentions`):
+ Outputs of the Q-Former (Querying Transformer).
+ """
+
+ vision_outputs: BaseModelOutputWithPooling | None = None
+ qformer_outputs: BaseModelOutputWithPoolingAndCrossAttentions | None = None
+
+
+@auto_docstring(
+ custom_intro="""
+ Class defining the outputs of [`Blip2ForConditionalGeneration`].
+ """
+)
+@dataclass
+class Blip2ForConditionalGenerationModelOutput(ModelOutput):
+ r"""
+ loss (`torch.FloatTensor`, *optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
+ Language modeling loss from the language model.
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
+ Prediction scores of the language modeling head of the language model.
+ vision_outputs (`BaseModelOutputWithPooling`):
+ Outputs of the vision encoder.
+ qformer_outputs (`BaseModelOutputWithPoolingAndCrossAttentions`):
+ Outputs of the Q-Former (Querying Transformer).
+ language_model_outputs (`CausalLMOutputWithPast` or `Seq2SeqLMOutput`):
+ Outputs of the language model.
+ """
+
+ loss: tuple[torch.FloatTensor] | None = None
+ logits: tuple[torch.FloatTensor] | None = None
+ vision_outputs: BaseModelOutputWithPooling | None = None
+ qformer_outputs: BaseModelOutputWithPoolingAndCrossAttentions | None = None
+ language_model_outputs: CausalLMOutputWithPast | Seq2SeqLMOutput | None = None
+
+ def to_tuple(self) -> tuple[Any]:
+ return tuple(
+ self[k]
+ if k not in ["vision_outputs", "qformer_outputs", "language_model_outputs"]
+ else getattr(self, k).to_tuple()
+ for k in self.keys()
+ )
+
+
+@auto_docstring
+@dataclass
+class Blip2ImageTextMatchingModelOutput(ModelOutput):
+ r"""
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`):
+ Contrastive loss for image-text similarity.
+ logits_per_image (`torch.FloatTensor` of shape `(image_batch_size, text_batch_size)`):
+ The scaled dot product scores between `image_embeds` and `text_embeds`. This represents the image-text
+ similarity scores.
+ logits_per_text (`torch.FloatTensor` of shape `(text_batch_size, image_batch_size)`):
+ The scaled dot product scores between `text_embeds` and `image_embeds`. This represents the text-image
+ similarity scores.
+ text_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim`):
+ The text embeddings obtained by applying the projection layer to the pooled output.
+ image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim`):
+ The image embeddings obtained by applying the projection layer to the pooled output.
+ text_model_output (`BaseModelOutputWithPooling`):
+ The output of the [`Blip2QFormerModel`].
+ vision_model_output (`BaseModelOutputWithPooling`):
+ The output of the [`Blip2VisionModel`].
+ """
+
+ loss: torch.FloatTensor | None = None
+ logits_per_image: torch.FloatTensor | None = None
+ logits_per_text: torch.FloatTensor | None = None
+ text_embeds: torch.FloatTensor | None = None
+ image_embeds: torch.FloatTensor | None = None
+ text_model_output: BaseModelOutputWithPooling = None
+ vision_model_output: BaseModelOutputWithPooling = None
+
+ def to_tuple(self) -> tuple[Any]:
+ return tuple(
+ self[k] if k not in ["text_model_output", "vision_model_output"] else getattr(self, k).to_tuple()
+ for k in self.keys()
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ Base class for text model's outputs that also contains a pooling of the last hidden states.
+ """
+)
+@dataclass
+# Copied from transformers.models.clip.modeling_clip.CLIPTextModelOutput with CLIP->Blip2
+class Blip2TextModelOutput(ModelOutput):
+ r"""
+ text_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
+ The text embeddings obtained by applying the projection layer to the pooler_output.
+ """
+
+ text_embeds: torch.FloatTensor | None = None
+ last_hidden_state: torch.FloatTensor | None = None
+ hidden_states: tuple[torch.FloatTensor, ...] | None = None
+ attentions: tuple[torch.FloatTensor, ...] | None = None
+
+
+@auto_docstring(
+ custom_intro="""
+ Base class for vision model's outputs that also contains image embeddings of the pooling of the last hidden states.
+ """
+)
+@dataclass
+# Copied from transformers.models.clip.modeling_clip.CLIPVisionModelOutput with CLIP->Blip2
+class Blip2VisionModelOutput(ModelOutput):
+ r"""
+ image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
+ The image embeddings obtained by applying the projection layer to the pooler_output.
+ """
+
+ image_embeds: torch.FloatTensor | None = None
+ last_hidden_state: torch.FloatTensor | None = None
+ hidden_states: tuple[torch.FloatTensor, ...] | None = None
+ attentions: tuple[torch.FloatTensor, ...] | None = None
+
+
+# Copied from transformers.models.blip.modeling_blip.BlipVisionEmbeddings with Blip->Blip2
+class Blip2VisionEmbeddings(nn.Module):
+ def __init__(self, config: Blip2VisionConfig):
+ super().__init__()
+ self.config = config
+ self.embed_dim = config.hidden_size
+ self.image_size = config.image_size
+ self.patch_size = config.patch_size
+
+ self.class_embedding = nn.Parameter(torch.randn(1, 1, self.embed_dim))
+
+ self.patch_embedding = nn.Conv2d(
+ in_channels=3, out_channels=self.embed_dim, kernel_size=self.patch_size, stride=self.patch_size
+ )
+
+ self.num_patches = (self.image_size // self.patch_size) ** 2
+ self.num_positions = self.num_patches + 1
+
+ self.position_embedding = nn.Parameter(torch.randn(1, self.num_positions, self.embed_dim))
+
+ def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor:
+ """
+ This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher resolution
+ images. This method is also adapted to support torch.jit tracing.
+
+ Adapted from:
+ - https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174-L194, and
+ - https://github.com/facebookresearch/dinov2/blob/e1277af2ba9496fbadf7aec6eba56e8d882d1e35/dinov2/models/vision_transformer.py#L179-L211
+ """
+
+ num_patches = embeddings.shape[1] - 1
+ num_positions = self.position_embedding.shape[1] - 1
+
+ # always interpolate when tracing to ensure the exported model works for dynamic input shapes
+ if not torch.jit.is_tracing() and num_patches == num_positions and height == width:
+ return self.position_embedding
+
+ class_pos_embed = self.position_embedding[:, :1]
+ patch_pos_embed = self.position_embedding[:, 1:]
+
+ dim = embeddings.shape[-1]
+
+ new_height = height // self.patch_size
+ new_width = width // self.patch_size
+
+ sqrt_num_positions = torch_int(num_positions**0.5)
+ patch_pos_embed = patch_pos_embed.reshape(1, sqrt_num_positions, sqrt_num_positions, dim)
+ patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2)
+
+ patch_pos_embed = nn.functional.interpolate(
+ patch_pos_embed,
+ size=(new_height, new_width),
+ mode="bicubic",
+ align_corners=False,
+ )
+
+ patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
+
+ return torch.cat((class_pos_embed, patch_pos_embed), dim=1)
+
+ def forward(self, pixel_values: torch.FloatTensor, interpolate_pos_encoding: bool = False) -> torch.Tensor:
+ batch_size, _, height, width = pixel_values.shape
+ target_dtype = self.patch_embedding.weight.dtype
+ patch_embeds = self.patch_embedding(pixel_values.to(dtype=target_dtype)) # shape = [*, width, grid, grid]
+ patch_embeds = patch_embeds.flatten(2).transpose(1, 2)
+ class_embeds = self.class_embedding.expand(batch_size, 1, -1).to(target_dtype)
+ embeddings = torch.cat([class_embeds, patch_embeds], dim=1)
+ if interpolate_pos_encoding:
+ position_embedding = self.interpolate_pos_encoding(embeddings, height, width)
+ else:
+ position_embedding = self.position_embedding
+ embeddings = embeddings + position_embedding[:, : embeddings.size(1), :].to(target_dtype)
+ return embeddings
+
+
+# Adapted from transformers.models.siglip.modeling_siglip.eager_attention_forward -> BLIP doesn't cast attn weights to fp32
+def eager_attention_forward(
+ module: nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: torch.Tensor | None,
+ scaling: float,
+ dropout: float = 0.0,
+ **kwargs,
+):
+ attn_weights = torch.matmul(query, key.transpose(-1, -2)) * scaling
+ if attention_mask is not None:
+ attn_weights = attn_weights + attention_mask
+
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
+
+ attn_output = torch.matmul(attn_weights, value)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+
+ return attn_output, attn_weights
+
+
+class Blip2Attention(nn.Module):
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
+
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.embed_dim = config.hidden_size
+ self.num_heads = config.num_attention_heads
+ self.head_dim = self.embed_dim // self.num_heads
+ if self.head_dim * self.num_heads != self.embed_dim:
+ raise ValueError(
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
+ f" {self.num_heads})."
+ )
+ self.scale = self.head_dim**-0.5
+ self.is_causal = False
+ self.attention_dropout = config.attention_dropout
+
+ # small tweak here compared to CLIP, no bias here
+ self.qkv = nn.Linear(self.embed_dim, 3 * self.embed_dim, bias=False)
+
+ if config.qkv_bias:
+ q_bias = nn.Parameter(torch.zeros(self.embed_dim))
+ v_bias = nn.Parameter(torch.zeros(self.embed_dim))
+ else:
+ q_bias = None
+ v_bias = None
+
+ if q_bias is not None:
+ qkv_bias = torch.cat((q_bias, torch.zeros_like(v_bias, requires_grad=False), v_bias))
+ self.qkv.bias = nn.Parameter(qkv_bias)
+
+ self.projection = nn.Linear(self.embed_dim, self.embed_dim)
+
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ **kwargs,
+ ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
+ """Input shape: Batch x Time x Channel"""
+
+ bsz, tgt_len, embed_dim = hidden_states.size()
+
+ mixed_qkv = self.qkv(hidden_states)
+
+ mixed_qkv = mixed_qkv.reshape(bsz, tgt_len, 3, self.num_heads, embed_dim // self.num_heads).permute(
+ 2, 0, 3, 1, 4
+ )
+ query_states, key_states, value_states = mixed_qkv[0], mixed_qkv[1], mixed_qkv[2]
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_states,
+ key_states,
+ value_states,
+ attention_mask=None,
+ dropout=0.0 if not self.training else self.attention_dropout,
+ scaling=self.scale,
+ **kwargs,
+ )
+
+ attn_output = attn_output.reshape(bsz, tgt_len, -1).contiguous()
+ attn_output = self.projection(attn_output)
+
+ return attn_output, attn_weights
+
+
+# Copied from transformers.models.blip.modeling_blip.BlipMLP
+class Blip2MLP(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.activation_fn = ACT2FN[config.hidden_act]
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.fc1(hidden_states)
+ hidden_states = self.activation_fn(hidden_states)
+ hidden_states = self.fc2(hidden_states)
+ return hidden_states
+
+
+# Copied from transformers.models.blip.modeling_blip.BlipEncoderLayer with Blip->Blip2
+class Blip2EncoderLayer(GradientCheckpointingLayer):
+ def __init__(self, config: Blip2Config):
+ super().__init__()
+ self.embed_dim = config.hidden_size
+ self.self_attn = Blip2Attention(config)
+ self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
+ self.mlp = Blip2MLP(config)
+ self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
+
+ @auto_docstring
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.FloatTensor:
+ residual = hidden_states
+
+ hidden_states = self.layer_norm1(hidden_states)
+ hidden_states, _ = self.self_attn(
+ hidden_states=hidden_states,
+ **kwargs,
+ )
+ hidden_states = hidden_states + residual
+ residual = hidden_states
+ hidden_states = self.layer_norm2(hidden_states)
+ hidden_states = self.mlp(hidden_states)
+
+ hidden_states = hidden_states + residual
+
+ return hidden_states
+
+
+@auto_docstring
+class Blip2PreTrainedModel(PreTrainedModel):
+ config: Blip2Config
+ base_model_prefix = "blip"
+ input_modalities = ("image", "text")
+ supports_gradient_checkpointing = True
+ _supports_attention_backend = True
+ _supports_flash_attn = True
+ _supports_sdpa = True
+ _supports_flex_attn = True
+
+ _no_split_modules = [
+ "Blip2Attention",
+ "Blip2QFormerMultiHeadAttention",
+ "Blip2EncoderLayer",
+ "Blip2TextEmbeddings",
+ "T5Block",
+ "OPTDecoderLayer",
+ ]
+ _skip_keys_device_placement = ["past_key_values"]
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ """Initialize the weights"""
+ super()._init_weights(module)
+ std = self.config.initializer_range
+ if isinstance(module, Blip2VisionEmbeddings):
+ init.trunc_normal_(module.position_embedding, mean=0.0, std=std)
+ init.trunc_normal_(module.class_embedding, mean=0.0, std=std)
+ elif isinstance(
+ module,
+ (
+ Blip2Model,
+ Blip2TextModelWithProjection,
+ Blip2VisionModelWithProjection,
+ Blip2ForConditionalGeneration,
+ Blip2ForImageTextRetrieval,
+ ),
+ ):
+ init.zeros_(module.query_tokens)
+ elif isinstance(module, Blip2TextEmbeddings):
+ init.copy_(module.position_ids, torch.arange(module.position_ids.shape[-1]).expand((1, -1)))
+
+
+# Copied from transformers.models.blip.modeling_blip.BlipEncoder with Blip->Blip2
+class Blip2Encoder(nn.Module):
+ """
+ Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
+ [`Blip2EncoderLayer`].
+
+ Args:
+ config (`Blip2Config`):
+ The corresponding vision configuration for the `Blip2Encoder`.
+ """
+
+ def __init__(self, config: Blip2Config):
+ super().__init__()
+ self.config = config
+ self.layers = nn.ModuleList([Blip2EncoderLayer(config) for _ in range(config.num_hidden_layers)])
+ self.gradient_checkpointing = False
+
+ @auto_docstring
+ def forward(
+ self,
+ inputs_embeds,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutput:
+ hidden_states = inputs_embeds
+ for encoder_layer in self.layers:
+ hidden_states = encoder_layer(
+ hidden_states,
+ **kwargs,
+ )
+
+ return BaseModelOutput(last_hidden_state=hidden_states)
+
+
+@auto_docstring
+class Blip2VisionModel(Blip2PreTrainedModel):
+ main_input_name = "pixel_values"
+ input_modalities = ("image",)
+ config: Blip2VisionConfig
+ _can_record_outputs = {
+ "hidden_states": Blip2EncoderLayer,
+ "attentions": Blip2Attention,
+ }
+
+ def __init__(self, config: Blip2VisionConfig):
+ super().__init__(config)
+ self.config = config
+ embed_dim = config.hidden_size
+
+ self.embeddings = Blip2VisionEmbeddings(config)
+ self.encoder = Blip2Encoder(config)
+ self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
+
+ self.post_init()
+
+ @merge_with_config_defaults
+ @capture_outputs(tie_last_hidden_states=False)
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: torch.FloatTensor | None = None,
+ interpolate_pos_encoding: bool = False,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutputWithPooling:
+ if pixel_values is None:
+ raise ValueError("You have to specify pixel_values")
+
+ hidden_states = self.embeddings(pixel_values, interpolate_pos_encoding=interpolate_pos_encoding)
+
+ encoder_outputs: BaseModelOutput = self.encoder(
+ inputs_embeds=hidden_states,
+ **kwargs,
+ )
+
+ last_hidden_state = encoder_outputs.last_hidden_state
+ last_hidden_state = self.post_layernorm(last_hidden_state)
+
+ pooled_output = last_hidden_state[:, 0, :]
+ pooled_output = self.post_layernorm(pooled_output)
+
+ return BaseModelOutputWithPooling(
+ last_hidden_state=last_hidden_state,
+ pooler_output=pooled_output,
+ )
+
+ def get_input_embeddings(self):
+ return self.embeddings
+
+
+class Blip2QFormerMultiHeadAttention(nn.Module):
+ def __init__(self, config, is_cross_attention=False):
+ super().__init__()
+ self.config = config
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
+ raise ValueError(
+ "The hidden size (%d) is not a multiple of the number of attention heads (%d)"
+ % (config.hidden_size, config.num_attention_heads)
+ )
+
+ self.num_attention_heads = config.num_attention_heads
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
+
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
+ if is_cross_attention:
+ self.key = nn.Linear(config.encoder_hidden_size, self.all_head_size)
+ self.value = nn.Linear(config.encoder_hidden_size, self.all_head_size)
+ else:
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
+
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
+ self.save_attention = False
+
+ def save_attn_gradients(self, attn_gradients):
+ self.attn_gradients = attn_gradients
+
+ def get_attn_gradients(self):
+ return self.attn_gradients
+
+ def save_attention_map(self, attention_map):
+ self.attention_map = attention_map
+
+ def get_attention_map(self):
+ return self.attention_map
+
+ def transpose_for_scores(self, x):
+ new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
+ x = x.view(*new_x_shape)
+ return x.permute(0, 2, 1, 3)
+
+ def forward(
+ self,
+ hidden_states,
+ attention_mask=None,
+ encoder_hidden_states=None,
+ encoder_attention_mask=None,
+ **kwargs: Unpack[TransformersKwargs],
+ ):
+ # If this is instantiated as a cross-attention module, the keys
+ # and values come from an encoder; the attention mask needs to be
+ # such that the encoder's padding tokens are not attended to.
+ is_cross_attention = encoder_hidden_states is not None
+
+ if is_cross_attention:
+ key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
+ value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
+ attention_mask = encoder_attention_mask
+ else:
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
+
+ mixed_query_layer = self.query(hidden_states)
+
+ query_layer = self.transpose_for_scores(mixed_query_layer)
+
+ # Take the dot product between "query" and "key" to get the raw attention scores.
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
+
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
+
+ if attention_mask is not None:
+ # Apply the attention mask is (precomputed for all layers in BertModel forward() function)
+ attention_scores = attention_scores + attention_mask
+
+ # Normalize the attention scores to probabilities.
+ attention_probs = nn.Softmax(dim=-1)(attention_scores)
+
+ if is_cross_attention and self.save_attention:
+ self.save_attention_map(attention_probs)
+ attention_probs.register_hook(self.save_attn_gradients)
+
+ # This is actually dropping out entire tokens to attend to, which might
+ # seem a bit unusual, but is taken from the original Transformer paper.
+ attention_probs_dropped = self.dropout(attention_probs).to(value_layer.dtype)
+
+ context_layer = torch.matmul(attention_probs_dropped, value_layer)
+
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
+ context_layer = context_layer.view(*new_context_layer_shape)
+
+ return (
+ context_layer,
+ attention_probs,
+ )
+
+
+# Copied from transformers.models.bert.modeling_bert.BertSelfOutput with Bert->Blip2QFormer
+class Blip2QFormerSelfOutput(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
+ return hidden_states
+
+
+class Blip2QFormerAttention(nn.Module):
+ def __init__(self, config, is_cross_attention=False):
+ super().__init__()
+ self.attention = Blip2QFormerMultiHeadAttention(config, is_cross_attention)
+ self.output = Blip2QFormerSelfOutput(config)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.FloatTensor | None = None,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ encoder_attention_mask: torch.FloatTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.Tensor:
+ attn_output, _ = self.attention(
+ hidden_states=hidden_states,
+ attention_mask=attention_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ **kwargs,
+ )
+ attention_output = self.output(attn_output, hidden_states)
+ return attention_output
+
+
+# Copied from transformers.models.bert.modeling_bert.BertIntermediate with Bert->Blip2QFormer
+class Blip2QFormerIntermediate(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
+ if isinstance(config.hidden_act, str):
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
+ else:
+ self.intermediate_act_fn = config.hidden_act
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.intermediate_act_fn(hidden_states)
+ return hidden_states
+
+
+# Copied from transformers.models.bert.modeling_bert.BertOutput with Bert->Blip2QFormer
+class Blip2QFormerOutput(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
+ return hidden_states
+
+
+class Blip2QFormerLayer(GradientCheckpointingLayer):
+ def __init__(self, config, layer_idx):
+ super().__init__()
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
+ self.seq_len_dim = 1
+ self.attention = Blip2QFormerAttention(config)
+
+ self.layer_idx = layer_idx
+
+ if layer_idx % config.cross_attention_frequency == 0:
+ self.crossattention = Blip2QFormerAttention(config, is_cross_attention=True)
+ self.has_cross_attention = True
+ else:
+ self.has_cross_attention = False
+
+ if config.use_qformer_text_input:
+ self.intermediate = Blip2QFormerIntermediate(config)
+ self.output = Blip2QFormerOutput(config)
+
+ self.intermediate_query = Blip2QFormerIntermediate(config)
+ self.output_query = Blip2QFormerOutput(config)
+
+ def forward(
+ self,
+ hidden_states,
+ attention_mask=None,
+ encoder_hidden_states=None,
+ encoder_attention_mask=None,
+ query_length=0,
+ **kwargs: Unpack[TransformersKwargs],
+ ):
+ attention_output = self.attention(
+ hidden_states=hidden_states,
+ attention_mask=attention_mask,
+ **kwargs,
+ )
+
+ if query_length > 0:
+ query_attention_output = attention_output[:, :query_length, :]
+
+ if self.has_cross_attention:
+ if encoder_hidden_states is None:
+ raise ValueError("encoder_hidden_states must be given for cross-attention layers")
+ query_attention_output = self.crossattention(
+ hidden_states=query_attention_output,
+ attention_mask=attention_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ **kwargs,
+ )
+
+ layer_output = apply_chunking_to_forward(
+ self.feed_forward_chunk_query,
+ self.chunk_size_feed_forward,
+ self.seq_len_dim,
+ query_attention_output,
+ )
+
+ if attention_output.shape[1] > query_length:
+ layer_output_text = apply_chunking_to_forward(
+ self.feed_forward_chunk,
+ self.chunk_size_feed_forward,
+ self.seq_len_dim,
+ attention_output[:, query_length:, :],
+ )
+ layer_output = torch.cat([layer_output, layer_output_text], dim=1)
+ else:
+ layer_output = apply_chunking_to_forward(
+ self.feed_forward_chunk,
+ self.chunk_size_feed_forward,
+ self.seq_len_dim,
+ attention_output,
+ )
+ return layer_output
+
+ def feed_forward_chunk(self, attention_output):
+ intermediate_output = self.intermediate(attention_output)
+ layer_output = self.output(intermediate_output, attention_output)
+ return layer_output
+
+ def feed_forward_chunk_query(self, attention_output):
+ intermediate_output = self.intermediate_query(attention_output)
+ layer_output = self.output_query(intermediate_output, attention_output)
+ return layer_output
+
+
+class Blip2QFormerEncoder(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.layer = nn.ModuleList(
+ [Blip2QFormerLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
+ )
+ self.gradient_checkpointing = False
+
+ @can_return_tuple
+ def forward(
+ self,
+ hidden_states,
+ attention_mask=None,
+ encoder_hidden_states=None,
+ encoder_attention_mask=None,
+ query_length=0,
+ **kwargs: Unpack[TransformersKwargs],
+ ):
+ for i in range(self.config.num_hidden_layers):
+ layer_module = self.layer[i]
+
+ hidden_states = layer_module(
+ hidden_states,
+ attention_mask,
+ encoder_hidden_states, # as a positional argument for gradient checkpointing
+ encoder_attention_mask=encoder_attention_mask,
+ query_length=query_length,
+ **kwargs,
+ )
+
+ return BaseModelOutputWithPastAndCrossAttentions(
+ last_hidden_state=hidden_states,
+ )
+
+
+class Blip2TextEmbeddings(nn.Module):
+ """Construct the embeddings from word and position embeddings."""
+
+ def __init__(self, config):
+ super().__init__()
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
+ self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
+
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
+ self.register_buffer(
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
+ )
+
+ def forward(
+ self,
+ input_ids: torch.FloatTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ query_embeds: torch.FloatTensor | None = None,
+ ) -> torch.Tensor:
+ if input_ids is not None:
+ seq_length = input_ids.size()[1]
+ else:
+ seq_length = 0
+
+ if position_ids is None:
+ position_ids = self.position_ids[:, :seq_length]
+
+ if input_ids is not None:
+ input_ids = input_ids.to(self.word_embeddings.weight.device)
+ embeddings = self.word_embeddings(input_ids)
+
+ position_embeddings = self.position_embeddings(position_ids)
+ embeddings += position_embeddings
+
+ if query_embeds is not None:
+ # `query_embeds` are kept in fp32 when we use it with Qformer
+ if query_embeds.dtype != embeddings.dtype:
+ query_embeds = query_embeds.to(embeddings.dtype)
+ embeddings = torch.cat((query_embeds, embeddings), dim=1)
+ else:
+ embeddings = query_embeds
+
+ return embeddings
+
+
+@auto_docstring(
+ custom_intro="""
+ BLIP-2 Querying Transformer (Q-Former).
+ """
+)
+class Blip2QFormerModel(Blip2PreTrainedModel):
+ config: Blip2QFormerConfig
+
+ _supports_attention_backend = False # adds position on attn weights before last matmul
+ _supports_flash_attn = False
+ _supports_sdpa = False
+ _supports_flex_attn = False
+
+ _can_record_outputs = {
+ "hidden_states": Blip2QFormerLayer,
+ "attentions": [
+ OutputRecorder(Blip2QFormerMultiHeadAttention, index=1, layer_name=".attention"),
+ ],
+ "cross_attentions": [
+ OutputRecorder(Blip2QFormerMultiHeadAttention, index=1, layer_name=".crossattention"),
+ ],
+ }
+
+ def __init__(self, config: Blip2QFormerConfig):
+ super().__init__(config)
+ self.config = config
+
+ self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ self.encoder = Blip2QFormerEncoder(config)
+
+ self.post_init()
+
+ def get_input_embeddings(self):
+ # The Q-Former operates on embeddings provided by upstream modules (e.g. query tokens or text embeddings).
+ # It does not own input embeddings itself, so we return `None` to signal that there is nothing to update.
+ return None
+
+ def set_input_embeddings(self, value):
+ raise NotImplementedError("Blip2QFormerModel does not own input embeddings and cannot set them.")
+
+ @merge_with_config_defaults
+ @capture_outputs
+ @auto_docstring
+ def forward(
+ self,
+ query_embeds: torch.FloatTensor,
+ query_length: int | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ encoder_attention_mask: torch.FloatTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | BaseModelOutputWithPoolingAndCrossAttentions:
+ r"""
+ query_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
+ Hidden states to be used in the attention computation. If cross-attention,
+ will be used for the query (i.e., key and value will use the encoder_hidden_states).
+ query_length (`int`, *optional*):
+ Length of the query, usually based on the number of query tokens.
+ If no value is provided, query_length will be inferred by the query_embeds.
+ """
+ query_length = (
+ query_length if query_length is not None else query_embeds.shape[1] if query_embeds is not None else 0
+ )
+
+ # `Blip2QFormerModel` is kept as fp32
+ original_dtype = query_embeds.dtype
+ query_embeds = query_embeds.to(self.layernorm.weight.dtype)
+ embedding_output = self.layernorm(query_embeds)
+ embedding_output = self.dropout(embedding_output)
+
+ attention_mask = create_bidirectional_mask(
+ config=self.config,
+ inputs_embeds=embedding_output.to(original_dtype),
+ attention_mask=attention_mask,
+ )
+
+ # Qformer and latent query tokens are kept in fp32. We cast `encoder_hidden_states` if not fp32 already
+ if encoder_hidden_states is not None:
+ if encoder_hidden_states.dtype != query_embeds.dtype:
+ encoder_hidden_states = encoder_hidden_states.to(query_embeds.dtype)
+
+ if encoder_attention_mask is not None:
+ encoder_attention_mask = create_bidirectional_mask(
+ config=self.config,
+ inputs_embeds=embedding_output.to(original_dtype),
+ attention_mask=encoder_attention_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ )
+
+ encoder_outputs: BaseModelOutput = self.encoder(
+ embedding_output,
+ attention_mask=attention_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ query_length=query_length,
+ **kwargs,
+ )
+ sequence_output = encoder_outputs.last_hidden_state
+ pooled_output = sequence_output[:, 0, :]
+
+ return BaseModelOutputWithPoolingAndCrossAttentions(
+ last_hidden_state=sequence_output,
+ pooler_output=pooled_output,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ BLIP-2 Model for generating text and image features. The model consists of a vision encoder, Querying Transformer
+ (Q-Former) and a language model.
+ """
+)
+class Blip2Model(Blip2PreTrainedModel):
+ config: Blip2Config
+ main_input_name = "pixel_values"
+ _keep_in_fp32_modules = ["query_tokens", "qformer"]
+ _supports_flash_attn = False # because self.qformer does not support FA2
+
+ def __init__(self, config: Blip2Config):
+ super().__init__(config)
+
+ self.vision_model = Blip2VisionModel._from_config(config.vision_config)
+
+ self.query_tokens = nn.Parameter(torch.zeros(1, config.num_query_tokens, config.qformer_config.hidden_size))
+ self.qformer = Blip2QFormerModel._from_config(config.qformer_config)
+
+ self.language_projection = nn.Linear(config.qformer_config.hidden_size, config.text_config.hidden_size)
+ if config.use_decoder_only_language_model:
+ language_model = AutoModelForCausalLM.from_config(config.text_config)
+ else:
+ language_model = AutoModelForSeq2SeqLM.from_config(config.text_config)
+
+ self.language_model = language_model
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def set_output_embeddings(self, new_embeddings):
+ self.language_model.set_output_embeddings(new_embeddings)
+
+ def get_output_embeddings(self) -> nn.Module:
+ return self.language_model.get_output_embeddings()
+
+ def get_encoder(self, modality=None):
+ if modality is None:
+ return self.language_model.get_encoder()
+ else:
+ return super().get_encoder(modality=modality)
+
+ @can_return_tuple
+ @auto_docstring
+ def get_text_features(
+ self,
+ input_ids: torch.Tensor,
+ attention_mask: torch.Tensor | None = None,
+ decoder_input_ids: torch.Tensor | None = None,
+ decoder_attention_mask: torch.Tensor | None = None,
+ labels: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutputWithPooling:
+ r"""
+ decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
+ Indices of decoder input sequence tokens in the vocabulary.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are decoder input IDs?](../glossary#decoder-input-ids)
+
+ T5 uses the `pad_token_id` as the starting token for `decoder_input_ids` generation. If `past_key_values`
+ is used, optionally only the last `decoder_input_ids` have to be input (see `past_key_values`).
+
+ To know more on how to prepare `decoder_input_ids` for pretraining take a look at [T5
+ Training](./t5#training).
+ decoder_attention_mask (`torch.BoolTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
+ Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
+ be used by default.
+
+ Examples:
+ ```python
+ >>> import torch
+ >>> from transformers import AutoTokenizer, Blip2Model
+
+ >>> model = Blip2Model.from_pretrained("Salesforce/blip2-opt-2.7b")
+ >>> tokenizer = AutoTokenizer.from_pretrained("Salesforce/blip2-opt-2.7b")
+
+ >>> inputs = tokenizer(["a photo of a cat"], padding=True, return_tensors="pt")
+ >>> with torch.inference_mode():
+ ... text_features = model.get_text_features(**inputs)
+ ```"""
+
+ if self.config.use_decoder_only_language_model:
+ text_outputs: BaseModelOutputWithPast = self.language_model.base_model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ return_dict=True,
+ **kwargs,
+ )
+ else:
+ text_outputs: BaseModelOutputWithPastAndCrossAttentions = self.language_model.get_encoder()(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ return_dict=True,
+ **kwargs,
+ )
+ return BaseModelOutputWithPooling(
+ last_hidden_state=text_outputs.last_hidden_state,
+ hidden_states=text_outputs.hidden_states,
+ attentions=text_outputs.attentions,
+ )
+
+ @can_return_tuple
+ @auto_docstring
+ def get_image_features(
+ self,
+ pixel_values: torch.FloatTensor,
+ interpolate_pos_encoding: bool = False,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutputWithPooling:
+ r"""
+ Examples:
+ ```python
+ >>> import torch
+ >>> from transformers import AutoProcessor, Blip2Model
+ >>> from transformers.image_utils import load_image
+
+ >>> model = Blip2Model.from_pretrained("Salesforce/blip2-opt-2.7b")
+
+ >>> processor = AutoProcessor.from_pretrained("Salesforce/blip2-opt-2.7b")
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
+ >>> image = load_image(url)
+
+ >>> inputs = processor(images=image, return_tensors="pt")
+ >>> with torch.inference_mode():
+ ... image_outputs = model.get_image_features(**inputs)
+ ```"""
+ return self.vision_model(
+ pixel_values=pixel_values,
+ interpolate_pos_encoding=interpolate_pos_encoding,
+ **kwargs,
+ )
+
+ @filter_out_non_signature_kwargs()
+ @auto_docstring
+ def get_qformer_features(
+ self,
+ pixel_values: torch.FloatTensor,
+ interpolate_pos_encoding: bool = False,
+ ) -> torch.FloatTensor | BaseModelOutputWithPooling:
+ r"""
+ Returns:
+ qformer_outputs (`torch.FloatTensor`):
+ The Q-Former model's last layer hidden states.
+
+ Examples:
+
+ ```python
+ >>> import torch
+ >>> from transformers import AutoProcessor, Blip2Model
+ >>> from transformers.image_utils import load_image
+
+ >>> processor = Blip2Processor.from_pretrained("Salesforce/blip2-opt-2.7b")
+ >>> model = Blip2Model.from_pretrained("Salesforce/blip2-opt-2.7b")
+
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
+ >>> image = load_image(url)
+
+ >>> inputs = processor(images=image, return_tensors="pt")
+ >>> with torch.inference_mode():
+ ... qformer_outputs = model.get_qformer_features(**inputs)
+ ```"""
+ vision_outputs: BaseModelOutputWithPooling = self.vision_model(
+ pixel_values=pixel_values,
+ interpolate_pos_encoding=interpolate_pos_encoding,
+ return_dict=True,
+ )
+
+ image_embeds = vision_outputs.last_hidden_state
+
+ # step 2: forward the query tokens through the QFormer, using the image embeddings for cross-attention
+ image_attention_mask = torch.ones(image_embeds.size()[:-1], dtype=torch.long, device=image_embeds.device)
+
+ query_tokens = self.query_tokens.expand(image_embeds.shape[0], -1, -1)
+ query_outputs: BaseModelOutputWithPoolingAndCrossAttentions = self.qformer(
+ query_embeds=query_tokens,
+ encoder_hidden_states=image_embeds,
+ encoder_attention_mask=image_attention_mask,
+ return_dict=True,
+ )
+
+ return query_outputs.last_hidden_state
+
+ def get_placeholder_mask(self, input_ids: torch.LongTensor, inputs_embeds: torch.FloatTensor):
+ """
+ Obtains multimodal placeholder mask from `input_ids` or `inputs_embeds`.
+ """
+ if input_ids is None:
+ special_image_mask = inputs_embeds == self.get_input_embeddings()(
+ torch.tensor(self.config.image_token_id, dtype=torch.long, device=inputs_embeds.device)
+ )
+ special_image_mask = special_image_mask.all(-1)
+ else:
+ special_image_mask = input_ids == self.config.image_token_id
+
+ special_image_mask = special_image_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
+ return special_image_mask
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: torch.FloatTensor,
+ input_ids: torch.FloatTensor,
+ attention_mask: torch.LongTensor | None = None,
+ decoder_input_ids: torch.LongTensor | None = None,
+ decoder_attention_mask: torch.LongTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ interpolate_pos_encoding: bool = False,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | Blip2ForConditionalGenerationModelOutput:
+ r"""
+ decoder_attention_mask (`torch.BoolTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
+ Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
+ be used by default.
+
+ Only relevant in case an encoder-decoder language model (like T5) is used.
+
+ Examples:
+
+ ```python
+ >>> from PIL import Image
+ >>> import httpx
+ >>> from io import BytesIO
+ >>> from transformers import Blip2Processor, Blip2Model
+ >>> import torch
+
+ >>> device = "cuda" if torch.cuda.is_available() else "cpu"
+
+ >>> processor = Blip2Processor.from_pretrained("Salesforce/blip2-opt-2.7b")
+ >>> model = Blip2Model.from_pretrained("Salesforce/blip2-opt-2.7b", dtype=torch.float16)
+ >>> model.to(device) # doctest: +IGNORE_RESULT
+
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
+ >>> with httpx.stream("GET", url) as response:
+ ... image = Image.open(BytesIO(response.read()))
+
+ >>> prompt = "Question: how many cats are there? Answer:"
+ >>> inputs = processor(images=image, text=prompt, return_tensors="pt").to(device, torch.float16)
+
+ >>> outputs = model(**inputs)
+ ```"""
+
+ # step 1: forward the images through the vision encoder,
+ # to get image embeddings of shape (batch_size, seq_len, hidden_size)
+ vision_outputs = self.vision_model(
+ pixel_values=pixel_values,
+ interpolate_pos_encoding=interpolate_pos_encoding,
+ **kwargs,
+ )
+ image_embeds = vision_outputs[0]
+
+ # step 2: forward the query tokens through the QFormer, using the image embeddings for cross-attention
+ image_attention_mask = torch.ones(image_embeds.size()[:-1], dtype=torch.long, device=image_embeds.device)
+
+ query_tokens = self.query_tokens.expand(image_embeds.shape[0], -1, -1)
+ query_outputs = self.qformer(
+ query_embeds=query_tokens,
+ encoder_hidden_states=image_embeds,
+ encoder_attention_mask=image_attention_mask,
+ **kwargs,
+ )
+ query_output = query_outputs[0]
+
+ # Qformer is kept in fp32, we downcast the output back if needed
+ if query_output.dtype != image_embeds.dtype:
+ query_output = query_output.to(image_embeds.dtype)
+
+ # step 3: use the language model, conditioned on the query outputs and the prompt
+ language_model_inputs = self.language_projection(query_output)
+
+ inputs_embeds = self.language_model.get_input_embeddings()(input_ids)
+
+ if attention_mask is None:
+ attention_mask = torch.ones_like(input_ids)
+
+ language_model_inputs = language_model_inputs.to(inputs_embeds.device, inputs_embeds.dtype)
+ special_image_mask = self.get_placeholder_mask(input_ids, inputs_embeds=inputs_embeds)
+ inputs_embeds = inputs_embeds.to(language_model_inputs.device).masked_scatter(
+ special_image_mask, language_model_inputs
+ )
+
+ if self.config.use_decoder_only_language_model:
+ outputs = self.language_model(
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ **kwargs,
+ )
+ logits = outputs[0]
+ loss = None
+ # we compute the loss here since we need to take into account the sequence length of the query embeds
+ if labels is not None:
+ labels = labels.to(logits.device)
+ logits = logits[:, -labels.size(1) :, :]
+ # Shift so that tokens < n predict n
+ shift_logits = logits[..., :-1, :].contiguous()
+ shift_labels = labels[..., 1:].contiguous().to(logits.device)
+
+ # Flatten the tokens
+ loss_fct = CrossEntropyLoss(reduction="mean")
+
+ loss = loss_fct(shift_logits.view(-1, self.config.text_config.vocab_size), shift_labels.view(-1))
+ else:
+ outputs = self.language_model(
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ decoder_input_ids=decoder_input_ids,
+ decoder_attention_mask=decoder_attention_mask,
+ labels=labels,
+ return_dict=True,
+ **kwargs,
+ )
+ loss = outputs.loss
+ logits = outputs.logits
+
+ return Blip2ForConditionalGenerationModelOutput(
+ loss=loss,
+ logits=logits,
+ vision_outputs=vision_outputs,
+ qformer_outputs=query_outputs,
+ language_model_outputs=outputs,
+ )
+
+
+@auto_docstring
+class Blip2TextModelWithProjection(Blip2PreTrainedModel):
+ supports_gradient_checkpointing = False
+ _keep_in_fp32_modules = ["query_tokens", "qformer"]
+ _supports_flash_attn = False # because self.qformer does not support FA2
+
+ def __init__(self, config: Blip2Config):
+ super().__init__(config)
+
+ self.query_tokens = nn.Parameter(torch.zeros(1, config.num_query_tokens, config.qformer_config.hidden_size))
+ self.embeddings = Blip2TextEmbeddings(config.qformer_config)
+ self.qformer = Blip2QFormerModel(config.qformer_config)
+
+ # text projection layer
+ self.text_projection = nn.Linear(config.qformer_config.hidden_size, config.image_text_hidden_size)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.embeddings.word_embeddings
+
+ def set_input_embeddings(self, value):
+ self.embeddings.word_embeddings = value
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | Blip2TextModelOutput:
+ r"""
+ Examples:
+
+ ```python
+ >>> import torch
+ >>> from transformers import AutoProcessor, Blip2TextModelWithProjection
+
+ >>> device = "cuda" if torch.cuda.is_available() else "cpu"
+
+ >>> model = Blip2TextModelWithProjection.from_pretrained(
+ ... "Salesforce/blip2-itm-vit-g", dtype=torch.float16
+ ... )
+
+ >>> model.to(device) # doctest: +IGNORE_RESULT
+
+ >>> processor = AutoProcessor.from_pretrained("Salesforce/blip2-itm-vit-g")
+
+ >>> inputs = processor(text=["a photo of a cat", "a photo of a dog"], return_tensors="pt").to(device)
+
+ >>> outputs = model(**inputs)
+ >>> text_embeds = outputs.text_embeds
+ >>> print(text_embeds.shape)
+ torch.Size([2, 7, 256])
+ ```"""
+
+ query_embeds = self.embeddings(
+ input_ids=input_ids,
+ position_ids=position_ids,
+ )
+
+ text_outputs = self.qformer(
+ query_embeds=query_embeds,
+ query_length=0,
+ attention_mask=attention_mask,
+ **kwargs,
+ )
+
+ pooled_output = text_outputs[0]
+ pooled_output = pooled_output.to(dtype=self.text_projection.weight.dtype)
+
+ text_embeds = self.text_projection(pooled_output)
+ text_embeds = nn.functional.normalize(text_embeds, dim=-1)
+
+ return Blip2TextModelOutput(
+ text_embeds=text_embeds,
+ last_hidden_state=text_outputs.last_hidden_state,
+ hidden_states=text_outputs.hidden_states,
+ attentions=text_outputs.attentions,
+ )
+
+
+@auto_docstring
+class Blip2VisionModelWithProjection(Blip2PreTrainedModel):
+ main_input_name = "pixel_values"
+ input_modalities = ("image",)
+ _keep_in_fp32_modules = ["query_tokens", "qformer"]
+ _supports_flash_attn = False # because self.qformer does not support FA2
+
+ def __init__(self, config: Blip2Config):
+ super().__init__(config)
+
+ self.vision_model = Blip2VisionModel._from_config(config.vision_config)
+
+ self.query_tokens = nn.Parameter(torch.zeros(1, config.num_query_tokens, config.qformer_config.hidden_size))
+ self.qformer = Blip2QFormerModel._from_config(config.qformer_config)
+
+ # vision projection layer
+ self.vision_projection = nn.Linear(config.qformer_config.hidden_size, config.image_text_hidden_size)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self) -> nn.Module:
+ return self.vision_model.embeddings.patch_embedding
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: torch.FloatTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | Blip2VisionModelOutput:
+ r"""
+ Examples:
+
+ ```python
+ >>> import torch
+ >>> from transformers import AutoProcessor, Blip2VisionModelWithProjection
+ >>> from transformers.image_utils import load_image
+
+ >>> device = "cuda" if torch.cuda.is_available() else "cpu"
+
+ >>> processor = AutoProcessor.from_pretrained("Salesforce/blip2-itm-vit-g")
+ >>> model = Blip2VisionModelWithProjection.from_pretrained(
+ ... "Salesforce/blip2-itm-vit-g", dtype=torch.float16
+ ... )
+ >>> model.to(device) # doctest: +IGNORE_RESULT
+
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
+ >>> image = load_image(url)
+
+ >>> inputs = processor(images=image, return_tensors="pt").to(device, torch.float16)
+
+ >>> with torch.inference_mode():
+ ... outputs = model(**inputs)
+ >>> image_embeds = outputs.image_embeds
+ >>> print(image_embeds.shape)
+ torch.Size([1, 32, 256])
+ ```"""
+ vision_outputs = self.vision_model(
+ pixel_values=pixel_values,
+ **kwargs,
+ )
+
+ pooled_output = vision_outputs[0]
+ image_attention_mask = torch.ones(pooled_output.size()[:-1], dtype=torch.long, device=pooled_output.device)
+ query_tokens = self.query_tokens.expand(pooled_output.shape[0], -1, -1)
+
+ query_outputs = self.qformer(
+ query_embeds=query_tokens,
+ encoder_hidden_states=pooled_output,
+ encoder_attention_mask=image_attention_mask,
+ **kwargs,
+ )
+
+ embeds = query_outputs[0]
+ embeds = embeds.to(dtype=self.vision_projection.weight.dtype)
+ image_embeds = self.vision_projection(embeds)
+ image_embeds = nn.functional.normalize(image_embeds, dim=-1)
+
+ return Blip2VisionModelOutput(
+ image_embeds=image_embeds,
+ last_hidden_state=vision_outputs.last_hidden_state,
+ hidden_states=vision_outputs.hidden_states,
+ attentions=vision_outputs.attentions,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ BLIP-2 Model for generating text given an image and an optional text prompt. The model consists of a vision
+ encoder, Querying Transformer (Q-Former) and a language model.
+
+ One can optionally pass `input_ids` to the model, which serve as a text prompt, to make the language model continue
+ the prompt. Otherwise, the language model starts generating text from the [BOS] (beginning-of-sequence) token.
+
+
+
+ Note that Flan-T5 checkpoints cannot be cast to float16. They are pre-trained using bfloat16.
+
+
+ """
+)
+class Blip2ForConditionalGeneration(Blip2PreTrainedModel, GenerationMixin):
+ config: Blip2Config
+ main_input_name = "pixel_values"
+
+ _can_compile_fullgraph = True
+ _keep_in_fp32_modules = ["query_tokens", "qformer"]
+ _supports_flash_attn = False # because self.qformer does not support FA2
+
+ def __init__(self, config: Blip2Config):
+ super().__init__(config)
+
+ self.vision_model = Blip2VisionModel._from_config(config.vision_config)
+
+ self.query_tokens = nn.Parameter(torch.zeros(1, config.num_query_tokens, config.qformer_config.hidden_size))
+ self.qformer = Blip2QFormerModel._from_config(config.qformer_config)
+
+ self.language_projection = nn.Linear(config.qformer_config.hidden_size, config.text_config.hidden_size)
+ if config.use_decoder_only_language_model:
+ language_model = AutoModelForCausalLM.from_config(config.text_config)
+ else:
+ language_model = AutoModelForSeq2SeqLM.from_config(config.text_config)
+
+ self.language_model = language_model
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def set_output_embeddings(self, new_embeddings):
+ self.language_model.set_output_embeddings(new_embeddings)
+
+ def get_output_embeddings(self) -> nn.Module:
+ return self.language_model.get_output_embeddings()
+
+ def get_encoder(self, modality=None):
+ if modality is None:
+ return self.language_model.get_encoder()
+ else:
+ return super().get_encoder(modality=modality)
+
+ def _preprocess_accelerate(self):
+ r"""
+ Some pre-processing hacks to make the model `accelerate` compatible. Check
+ https://github.com/huggingface/transformers/pull/21707 for more details.
+ """
+ hf_device_map = self.hf_device_map
+
+ if len(hf_device_map) > 1 and "language_model" not in hf_device_map and torch.cuda.device_count() > 1:
+ # warn users about unexpected behavior when using multi-GPU + BLIP-2 + `accelerate`.
+ logger.warning(
+ "The `language_model` is not in the `hf_device_map` dictionary and you are running your script"
+ " in a multi-GPU environment. this may lead to unexpected behavior when using `accelerate`."
+ " Please pass a `device_map` that contains `language_model` to remove this warning."
+ " Please refer to https://github.com/huggingface/blog/blob/main/accelerate-large-models.md for"
+ " more details on creating a `device_map` for large models.",
+ )
+
+ if hasattr(self.language_model, "_hf_hook"):
+ self.language_model._hf_hook.io_same_device = True # For `generate` compatibility
+
+ @can_return_tuple
+ @auto_docstring
+ def get_image_features(
+ self,
+ pixel_values: torch.FloatTensor,
+ interpolate_pos_encoding: bool | None = False,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutputWithVisionQformerOutputs:
+ r"""
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
+ The tensors corresponding to the input images.
+ """
+ # step 1: forward the images through the vision encoder,
+ # to get image embeddings of shape (batch_size, seq_len, hidden_size)
+ vision_outputs: BaseModelOutputWithPooling = self.vision_model(
+ pixel_values=pixel_values,
+ interpolate_pos_encoding=interpolate_pos_encoding,
+ return_dict=True,
+ **kwargs,
+ )
+ vision_outputs = BaseModelOutputWithVisionQformerOutputs(
+ last_hidden_state=vision_outputs.last_hidden_state,
+ pooler_output=vision_outputs.pooler_output,
+ hidden_states=vision_outputs.hidden_states,
+ attentions=vision_outputs.attentions,
+ vision_outputs=vision_outputs,
+ qformer_outputs=None,
+ )
+ image_embeds = vision_outputs[0]
+
+ # step 2: forward the query tokens through the QFormer, using the image embeddings for cross-attention
+ image_attention_mask = torch.ones(image_embeds.size()[:-1], dtype=torch.long, device=image_embeds.device)
+
+ query_tokens = self.query_tokens.expand(image_embeds.shape[0], -1, -1)
+ qformer_outputs = self.qformer(
+ query_embeds=query_tokens,
+ encoder_hidden_states=image_embeds,
+ encoder_attention_mask=image_attention_mask,
+ return_dict=True,
+ )
+ vision_outputs.qformer_outputs = qformer_outputs
+ query_output = qformer_outputs[0]
+
+ # Qformer is kept in fp32, we downcast the output back if needed
+ if query_output.dtype != image_embeds.dtype:
+ query_output = query_output.to(image_embeds.dtype)
+
+ # step 3: use the language model, conditioned on the query outputs and the prompt
+ image_features = self.language_projection(query_output)
+ vision_outputs.pooler_output = image_features
+
+ return vision_outputs
+
+ def get_placeholder_mask(self, input_ids: torch.LongTensor, inputs_embeds: torch.FloatTensor):
+ """
+ Obtains multimodal placeholder mask from `input_ids` or `inputs_embeds`.
+ """
+ if input_ids is None:
+ special_image_mask = inputs_embeds == self.get_input_embeddings()(
+ torch.tensor(self.config.image_token_id, dtype=torch.long, device=inputs_embeds.device)
+ )
+ special_image_mask = special_image_mask.all(-1)
+ else:
+ special_image_mask = input_ids == self.config.image_token_id
+
+ special_image_mask = special_image_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
+ return special_image_mask
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: torch.FloatTensor,
+ input_ids: torch.LongTensor,
+ attention_mask: torch.LongTensor | None = None,
+ decoder_input_ids: torch.LongTensor | None = None,
+ decoder_attention_mask: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ interpolate_pos_encoding: bool = False,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | Blip2ForConditionalGenerationModelOutput:
+ r"""
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Indices of input sequence tokens in the vocabulary of the language model. Input tokens can optionally be
+ provided to serve as text prompt, which the language model can continue.
+
+ Indices can be obtained using [`Blip2Processor`]. See [`Blip2Processor.__call__`] for details.
+
+ [What are input IDs?](../glossary#input-ids)
+ decoder_attention_mask (`torch.BoolTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
+ Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
+ be used by default.
+
+ Only relevant in case an encoder-decoder language model (like T5) is used.
+
+ Examples:
+
+ Prepare processor, model and image input
+
+ ```python
+ >>> from PIL import Image
+ >>> import httpx
+ >>> from io import BytesIO
+ >>> from transformers import Blip2Processor, Blip2ForConditionalGeneration
+ >>> import torch
+
+ >>> device = "cuda" if torch.cuda.is_available() else "cpu"
+
+ >>> processor = Blip2Processor.from_pretrained("Salesforce/blip2-opt-2.7b")
+ >>> model = Blip2ForConditionalGeneration.from_pretrained(
+ ... "Salesforce/blip2-opt-2.7b", load_in_8bit=True, device_map={"": 0}, dtype=torch.float16
+ ... ) # doctest: +IGNORE_RESULT
+
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
+ >>> with httpx.stream("GET", url) as response:
+ ... image = Image.open(BytesIO(response.read()))
+ ```
+
+ Image captioning (without providing a text prompt):
+
+ ```python
+ >>> inputs = processor(images=image, return_tensors="pt").to(device, torch.float16)
+
+ >>> generated_ids = model.generate(**inputs)
+ >>> generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0].strip()
+ >>> print(generated_text)
+ two cats laying on a couch
+ ```
+
+ Visual question answering (prompt = question):
+
+ ```python
+ >>> prompt = "Question: how many cats are there? Answer:"
+ >>> inputs = processor(images=image, text=prompt, return_tensors="pt").to(device="cuda", dtype=torch.float16)
+
+ >>> generated_ids = model.generate(**inputs)
+ >>> generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0].strip()
+ >>> print(generated_text)
+ two
+ ```
+
+ Note that int8 inference is also supported through [bitsandbytes](https://github.com/TimDettmers/bitsandbytes).
+ This greatly reduces the amount of memory used by the model while maintaining the same performance.
+
+ ```python
+ >>> model = Blip2ForConditionalGeneration.from_pretrained(
+ ... "Salesforce/blip2-opt-2.7b", load_in_8bit=True, device_map={"": 0}, dtype=torch.bfloat16
+ ... ) # doctest: +IGNORE_RESULT
+
+ >>> inputs = processor(images=image, text=prompt, return_tensors="pt").to(device="cuda", dtype=torch.bfloat16)
+
+ >>> generated_ids = model.generate(**inputs)
+ >>> generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0].strip()
+ >>> print(generated_text)
+ two
+ ```"""
+
+ image_features: BaseModelOutputWithVisionQformerOutputs = self.get_image_features(
+ pixel_values, interpolate_pos_encoding=interpolate_pos_encoding, return_dict=True
+ )
+ language_model_inputs = image_features.pooler_output
+ qformer_outputs = image_features.qformer_outputs
+ vision_outputs = image_features.vision_outputs
+
+ if inputs_embeds is None:
+ inputs_embeds = self.get_input_embeddings()(input_ids)
+
+ if attention_mask is None:
+ attention_mask = torch.ones_like(input_ids)
+
+ language_model_inputs = language_model_inputs.to(inputs_embeds.device, inputs_embeds.dtype)
+ special_image_mask = self.get_placeholder_mask(input_ids, inputs_embeds=inputs_embeds)
+ inputs_embeds = inputs_embeds.to(language_model_inputs.device).masked_scatter(
+ special_image_mask, language_model_inputs
+ )
+
+ if self.config.use_decoder_only_language_model:
+ outputs = self.language_model(
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ **kwargs,
+ )
+ logits = outputs[0]
+ loss = None
+ # we compute the loss here since we need to take into account the sequence length of the query embeds
+ if labels is not None:
+ labels = labels.to(logits.device)
+ logits = logits[:, -labels.size(1) :, :]
+ # Shift so that tokens < n predict n
+ shift_logits = logits[..., :-1, :].contiguous()
+ shift_labels = labels[..., 1:].contiguous().to(logits.device)
+
+ # Flatten the tokens
+ loss_fct = CrossEntropyLoss(reduction="mean")
+
+ loss = loss_fct(shift_logits.view(-1, self.config.text_config.vocab_size), shift_labels.view(-1))
+ else:
+ kwargs["return_dict"] = True
+ outputs = self.language_model(
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ decoder_input_ids=decoder_input_ids,
+ decoder_attention_mask=decoder_attention_mask,
+ labels=labels,
+ **kwargs,
+ )
+ loss = outputs.loss
+ logits = outputs.logits
+
+ return Blip2ForConditionalGenerationModelOutput(
+ loss=loss,
+ logits=logits,
+ vision_outputs=vision_outputs,
+ qformer_outputs=qformer_outputs,
+ language_model_outputs=outputs,
+ )
+
+ @torch.no_grad()
+ def generate(
+ self,
+ pixel_values: torch.FloatTensor,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ interpolate_pos_encoding: bool = False,
+ **generate_kwargs,
+ ) -> torch.LongTensor:
+ """
+ Overrides `generate` function to be able to use the model as a conditional generator.
+
+ Args:
+ pixel_values (`torch.FloatTensor` of shape (batch_size, num_channels, height, width)):
+ Input images to be processed.
+ input_ids (`torch.LongTensor` of shape (batch_size, sequence_length), *optional*):
+ The sequence used as a prompt for the generation.
+ attention_mask (`torch.LongTensor` of shape (batch_size, sequence_length), *optional*):
+ Mask to avoid performing attention on padding token indices
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
+ Embedded representation of the inputs. Should be float, not int tokens.
+ interpolate_pos_encoding (`bool`, *optional*, defaults to `False`):
+ Whether to interpolate the positional encoding of the image embeddings.
+
+ Returns:
+ captions (list): A list of strings of length batch_size * num_captions.
+ """
+ if hasattr(self, "hf_device_map"):
+ # preprocess for `accelerate`
+ self._preprocess_accelerate()
+
+ batch_size = pixel_values.shape[0]
+ image_embeds = self.vision_model(
+ pixel_values,
+ return_dict=True,
+ interpolate_pos_encoding=interpolate_pos_encoding,
+ ).last_hidden_state
+ image_attention_mask = torch.ones(image_embeds.size()[:-1], dtype=torch.long, device=image_embeds.device)
+
+ query_tokens = self.query_tokens.expand(image_embeds.shape[0], -1, -1)
+ query_outputs = self.qformer(
+ query_embeds=query_tokens,
+ encoder_hidden_states=image_embeds,
+ encoder_attention_mask=image_attention_mask,
+ return_dict=True,
+ )
+ query_output = query_outputs.last_hidden_state
+
+ # Qformer is kept in fp32, we downcast the output back if needed
+ if query_output.dtype != image_embeds.dtype:
+ query_output = query_output.to(image_embeds.dtype)
+
+ language_model_inputs = self.language_projection(query_output)
+
+ if inputs_embeds is None:
+ if input_ids is None:
+ image_tokens = [self.config.image_token_index] * self.config.num_query_tokens
+ start_tokens = image_tokens + [self.config.text_config.bos_token_id]
+ input_ids = torch.tensor([start_tokens], dtype=torch.long, device=image_embeds.device)
+ input_ids = input_ids.repeat(batch_size, 1)
+ inputs_embeds = self.get_input_embeddings()(input_ids)
+
+ if attention_mask is None:
+ attention_mask = torch.ones_like(input_ids)
+
+ if input_ids is None:
+ special_image_mask = inputs_embeds == self.get_input_embeddings()(
+ torch.tensor(self.config.image_token_id, dtype=torch.long, device=inputs_embeds.device)
+ )
+ special_image_mask = special_image_mask.all(-1)
+ else:
+ special_image_mask = input_ids == self.config.image_token_id
+
+ special_image_mask = special_image_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
+ language_model_inputs = language_model_inputs.to(inputs_embeds.device, inputs_embeds.dtype)
+ inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, language_model_inputs)
+
+ inputs = {"inputs_embeds": inputs_embeds, "attention_mask": attention_mask}
+ if not self.language_model.config.is_encoder_decoder:
+ inputs["input_ids"] = input_ids
+
+ outputs = self.language_model.generate(**inputs, **generate_kwargs)
+
+ return outputs
+
+
+@auto_docstring(
+ custom_intro="""
+ BLIP-2 Model with a vision and text projector, and a classification head on top. The model is used in the context
+ of image-text retrieval. Given an image and a text, the model returns the probability of the text being relevant to
+ the image.
+ """
+)
+class Blip2ForImageTextRetrieval(Blip2PreTrainedModel):
+ main_input_name = "pixel_values"
+ input_modalities = ("image",)
+ _keep_in_fp32_modules = ["query_tokens", "qformer"]
+ _supports_flash_attn = False # because self.qformer does not support FA2
+
+ def __init__(self, config: Blip2Config):
+ super().__init__(config)
+
+ self.vision_model = Blip2VisionModel._from_config(config.vision_config)
+
+ self.query_tokens = nn.Parameter(torch.zeros(1, config.num_query_tokens, config.qformer_config.hidden_size))
+
+ self.embeddings = Blip2TextEmbeddings(config.qformer_config)
+ self.qformer = Blip2QFormerModel._from_config(config.qformer_config)
+
+ # vision projection layer
+ self.vision_projection = nn.Linear(config.qformer_config.hidden_size, config.image_text_hidden_size)
+
+ # text projection layer
+ self.text_projection = nn.Linear(config.qformer_config.hidden_size, config.image_text_hidden_size)
+
+ # image text matching head
+ self.itm_head = nn.Linear(config.qformer_config.hidden_size, 2)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.embeddings.word_embeddings
+
+ def set_input_embeddings(self, value):
+ self.embeddings.word_embeddings = value
+
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: torch.FloatTensor,
+ input_ids: torch.LongTensor,
+ attention_mask: torch.LongTensor | None = None,
+ use_image_text_matching_head: bool | None = False,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple | Blip2ImageTextMatchingModelOutput:
+ r"""
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Indices of input sequence tokens in the vocabulary of the language model. Input tokens can optionally be
+ provided to serve as text prompt, which the language model can continue.
+
+ Indices can be obtained using [`Blip2Processor`]. See [`Blip2Processor.__call__`] for details.
+
+ [What are input IDs?](../glossary#input-ids)
+ use_image_text_matching_head (`bool`, *optional*):
+ Whether to return the Image-Text Matching or Contrastive scores.
+
+ Examples:
+
+ ```python
+ >>> import torch
+ >>> from PIL import Image
+ >>> import httpx
+ >>> from io import BytesIO
+ >>> from transformers import AutoProcessor, Blip2ForImageTextRetrieval
+
+ >>> device = "cuda" if torch.cuda.is_available() else "cpu"
+
+ >>> model = Blip2ForImageTextRetrieval.from_pretrained("Salesforce/blip2-itm-vit-g", dtype=torch.float16)
+ >>> processor = AutoProcessor.from_pretrained("Salesforce/blip2-itm-vit-g")
+
+ >>> model.to(device) # doctest: +IGNORE_RESULT
+
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
+ >>> with httpx.stream("GET", url) as response:
+ ... image = Image.open(BytesIO(response.read()))
+ >>> text = "two cats laying on a pink blanket"
+
+ >>> inputs = processor(images=image, text=text, return_tensors="pt").to(device, torch.float16)
+ >>> itm_out = model(**inputs, use_image_text_matching_head=True)
+ >>> logits_per_image = torch.nn.functional.softmax(itm_out.logits_per_image, dim=1)
+ >>> probs = logits_per_image.softmax(dim=1) # we can take the softmax to get the label probabilities
+
+ >>> print(f"{probs[0][0]:.1%} that image 0 is not '{text}'")
+ 26.9% that image 0 is not 'two cats laying on a pink blanket'
+
+ >>> print(f"{probs[0][1]:.1%} that image 0 is '{text}'")
+ 73.0% that image 0 is 'two cats laying on a pink blanket'
+
+ >>> texts = ["a photo of a cat", "a photo of a dog"]
+
+ >>> inputs = processor(images=image, text=texts, return_tensors="pt").to(device, torch.float16)
+ >>> itc_out = model(**inputs, use_image_text_matching_head=False)
+ >>> logits_per_image = itc_out.logits_per_image # this is the image-text similarity score
+ >>> probs = logits_per_image.softmax(dim=1) # we can take the softmax to get the label probabilities
+
+ >>> print(f"{probs[0][0]:.1%} that image 0 is '{texts[0]}'")
+ 55.3% that image 0 is 'a photo of a cat'
+
+ >>> print(f"{probs[0][1]:.1%} that image 0 is '{texts[1]}'")
+ 44.7% that image 0 is 'a photo of a dog'
+ ```
+ """
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+
+ vision_outputs = self.vision_model(
+ pixel_values=pixel_values,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ image_embeds = vision_outputs[0]
+ image_attention_mask = torch.ones(image_embeds.size()[:-1], dtype=torch.long, device=image_embeds.device)
+
+ if use_image_text_matching_head:
+ query_tokens = self.query_tokens.expand(image_embeds.shape[0], -1, -1)
+ if self.config.image_token_index is not None:
+ input_ids = input_ids[:, self.config.num_query_tokens :]
+ else:
+ query_attention_mask = torch.ones(
+ query_tokens.size()[:-1], dtype=torch.long, device=query_tokens.device
+ )
+ attention_mask = torch.cat([query_attention_mask, attention_mask], dim=1)
+
+ query_embeds = self.embeddings(
+ input_ids=input_ids,
+ query_embeds=query_tokens,
+ )
+
+ text_outputs = self.qformer(
+ query_embeds=query_embeds,
+ query_length=query_tokens.shape[1],
+ attention_mask=attention_mask,
+ encoder_hidden_states=image_embeds,
+ encoder_attention_mask=image_attention_mask,
+ return_dict=return_dict,
+ )
+ text_embeds = text_outputs[0] if not return_dict else text_outputs.last_hidden_state
+ text_embeds = text_embeds.to(dtype=self.itm_head.weight.dtype)
+
+ output = self.itm_head(text_embeds[:, : query_tokens.size(1), :])
+ logits_per_image = output.mean(dim=1)
+ logits_per_text = logits_per_image.t()
+ else:
+ query_tokens = self.query_tokens.expand(image_embeds.shape[0], -1, -1)
+ query_outputs = self.qformer(
+ query_embeds=query_tokens,
+ encoder_hidden_states=image_embeds,
+ encoder_attention_mask=image_attention_mask,
+ return_dict=return_dict,
+ )
+ image_embeds = query_outputs[0] if not return_dict else query_outputs.last_hidden_state
+ image_embeds = image_embeds.to(dtype=self.vision_projection.weight.dtype)
+
+ if self.config.image_token_index is not None:
+ input_ids = input_ids[:, self.config.num_query_tokens :]
+ attention_mask = attention_mask[:, self.config.num_query_tokens :]
+
+ query_embeds = self.embeddings(
+ input_ids=input_ids,
+ )
+ text_outputs = self.qformer(
+ query_embeds=query_embeds,
+ query_length=0,
+ attention_mask=attention_mask,
+ return_dict=return_dict,
+ )
+ question_embeds = text_outputs[0] if not return_dict else text_outputs.last_hidden_state
+ question_embeds = question_embeds.to(dtype=self.text_projection.weight.dtype)
+
+ # normalized features
+ image_embeds = nn.functional.normalize(self.vision_projection(image_embeds), dim=-1)
+ text_embeds = nn.functional.normalize(self.text_projection(question_embeds[:, 0, :]), dim=-1)
+
+ # cosine similarity as logits
+ logits_per_image = torch.matmul(image_embeds, text_embeds.t())
+ logits_per_image, _ = logits_per_image.max(dim=1)
+
+ logits_per_text = logits_per_image.t()
+
+ if not return_dict:
+ output = (logits_per_image, logits_per_text, text_embeds, image_embeds, text_outputs, vision_outputs)
+ return output
+
+ return Blip2ImageTextMatchingModelOutput(
+ logits_per_image=logits_per_image,
+ logits_per_text=logits_per_text,
+ text_embeds=text_embeds,
+ image_embeds=image_embeds,
+ text_model_output=text_outputs,
+ vision_model_output=vision_outputs,
+ )
+
+
+__all__ = [
+ "Blip2Model",
+ "Blip2VisionModelWithProjection",
+ "Blip2QFormerModel",
+ "Blip2PreTrainedModel",
+ "Blip2ForConditionalGeneration",
+ "Blip2ForImageTextRetrieval",
+ "Blip2VisionModel",
+ "Blip2TextModelWithProjection",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/blip_2/processing_blip_2.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/blip_2/processing_blip_2.py
new file mode 100644
index 0000000000000000000000000000000000000000..e339854a6736ec1c5e8e23b31644e6533d4c27c8
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/blip_2/processing_blip_2.py
@@ -0,0 +1,114 @@
+# Copyright 2023 The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""
+Processor class for BLIP-2.
+"""
+
+from ...image_processing_utils import BatchFeature
+from ...image_utils import ImageInput
+from ...processing_utils import ProcessingKwargs, ProcessorMixin, Unpack
+from ...tokenization_utils_base import AddedToken, BatchEncoding, PreTokenizedInput, TextInput
+from ...utils import auto_docstring, logging
+
+
+logger = logging.get_logger(__name__)
+
+
+class Blip2ProcessorKwargs(ProcessingKwargs, total=False):
+ _defaults = {
+ "text_kwargs": {
+ "add_special_tokens": True,
+ "padding": False,
+ "stride": 0,
+ "return_overflowing_tokens": False,
+ "return_special_tokens_mask": False,
+ "return_offsets_mapping": False,
+ "return_token_type_ids": False,
+ "return_length": False,
+ "verbose": True,
+ },
+ }
+
+
+@auto_docstring
+class Blip2Processor(ProcessorMixin):
+ def __init__(self, image_processor, tokenizer, num_query_tokens=None, **kwargs):
+ r"""
+ num_query_tokens (`int`, *optional*):
+ Number of tokens used by the Qformer as queries, should be same as in model's config.
+ """
+ tokenizer.return_token_type_ids = False
+ if not hasattr(tokenizer, "image_token"):
+ self.image_token = AddedToken("", normalized=False, special=True)
+ tokenizer.add_tokens([self.image_token], special_tokens=True)
+ else:
+ self.image_token = tokenizer.image_token
+ self.num_query_tokens = num_query_tokens
+
+ super().__init__(image_processor, tokenizer)
+
+ @auto_docstring
+ def __call__(
+ self,
+ images: ImageInput | None = None,
+ text: str | list[str] | TextInput | PreTokenizedInput | None = None,
+ **kwargs: Unpack[Blip2ProcessorKwargs],
+ ) -> BatchEncoding:
+ if images is None and text is None:
+ raise ValueError("You have to specify either images or text.")
+ output_kwargs = self._merge_kwargs(
+ Blip2ProcessorKwargs,
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
+ **kwargs,
+ )
+
+ # BC for explicit return_tensors
+ return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None)
+ max_length = output_kwargs["text_kwargs"].pop("max_length", None)
+ if max_length is not None:
+ output_kwargs["text_kwargs"]["max_length"] = max_length - self.num_query_tokens
+
+ encoding = BatchFeature(tensor_type=return_tensors)
+ if text is not None:
+ if isinstance(text, str):
+ text = [text]
+ elif not isinstance(text, list) and not isinstance(text[0], str):
+ raise ValueError("Invalid input text. Please provide a string, or a list of strings")
+
+ # We need this hacky manipulation because BLIP expects image tokens to be at the beginning even before BOS token
+ text_encoding = self.tokenizer(text, **output_kwargs["text_kwargs"])
+
+ if images is not None and self.num_query_tokens is not None:
+ # Image tokens should not be padded/truncated or prepended with special BOS token
+ image_tokens = self.image_token.content * self.num_query_tokens
+ output_kwargs["text_kwargs"]["add_special_tokens"] = False
+ output_kwargs["text_kwargs"]["padding"] = False
+ output_kwargs["text_kwargs"]["truncation"] = False
+ image_text_encoding = self.tokenizer(image_tokens, **output_kwargs["text_kwargs"])
+ for k in text_encoding:
+ text_encoding[k] = [image_text_encoding[k] + sample for sample in text_encoding[k]]
+ encoding.update(text_encoding)
+
+ # Now add pixel_values encoding. If we also have text_encoding, update image encoding and return it.
+ # else, return the text encoding.
+ if images is not None:
+ image_encoding = self.image_processor(images, **output_kwargs["images_kwargs"])
+ encoding.update(image_encoding)
+
+ # Cast to desired return tensors type
+ encoding = BatchFeature(encoding, tensor_type=return_tensors)
+ return encoding
+
+
+__all__ = ["Blip2Processor"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bloom/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bloom/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..ba39d13cedcb6ce497397c40fc85159f0bb0af16
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bloom/__init__.py
@@ -0,0 +1,28 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_bloom import *
+ from .modeling_bloom import *
+ from .tokenization_bloom import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bloom/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bloom/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9c14b9758170f88a2941eff16fe0296e66898308
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bloom/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bloom/__pycache__/configuration_bloom.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bloom/__pycache__/configuration_bloom.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ec32ebbc66a08b94a9f6a1e99d3482a3697c0329
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bloom/__pycache__/configuration_bloom.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bloom/__pycache__/modeling_bloom.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bloom/__pycache__/modeling_bloom.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3d1d11b31011578e567183b1b7dbc325718f661b
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bloom/__pycache__/modeling_bloom.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bloom/configuration_bloom.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bloom/configuration_bloom.py
new file mode 100644
index 0000000000000000000000000000000000000000..f0b57e33fb7d1bad4cc6dea404a48030994ef32b
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bloom/configuration_bloom.py
@@ -0,0 +1,82 @@
+# Copyright 2022 the Big Science Workshop and HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Bloom configuration"""
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring
+
+
+@auto_docstring(checkpoint="bigscience/bloom")
+@strict
+class BloomConfig(PreTrainedConfig):
+ r"""
+ apply_residual_connection_post_layernorm (`bool`, *optional*, defaults to `False`):
+ If enabled, use the layer norm of the hidden states as the residual in the transformer blocks
+ slow_but_exact (`bool`, *optional*, defaults to `False`):
+ Experimental feature. Whether to use slow but exact implementation of the attention mechanism. While
+ merging the TP rank tensors, due to slicing operations the results may be slightly different between the
+ model trained on Megatron and our model. Please refer to [this
+ issue](https://github.com/pytorch/pytorch/issues/76232). A solution to obtain more accurate results is to
+ enable this feature. Enabling this will hurt the computational time of the inference. Will be probably
+ resolved in the future once the main model has been fine-tuned with TP_rank=1.
+
+ Example:
+
+ ```python
+ >>> from transformers import BloomConfig, BloomModel
+
+ >>> # Initializing a Bloom configuration
+ >>> configuration = BloomConfig()
+
+ >>> # Initializing a model (with random weights) from the configuration
+ >>> model = BloomModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "bloom"
+ keys_to_ignore_at_inference = ["past_key_values"]
+ attribute_map = {
+ "num_hidden_layers": "n_layer",
+ "num_attention_heads": "n_head",
+ }
+
+ vocab_size: int = 250880
+ hidden_size: int = 64
+ n_layer: int = 2
+ n_head: int = 8
+ layer_norm_epsilon: float = 1e-5
+ initializer_range: float = 0.02
+ use_cache: bool = True
+ bos_token_id: int | None = 1
+ eos_token_id: int | list[int] | None = 2
+ pad_token_id: int | None = None
+ apply_residual_connection_post_layernorm: bool = False
+ hidden_dropout: float | int = 0.0
+ attention_dropout: float | int = 0.0
+ pretraining_tp: int = 1 # TP rank used when training with megatro
+ slow_but_exact: bool = False
+ tie_word_embeddings: bool = True
+
+ def __post_init__(self, **kwargs):
+ # Backward compatibility with n_embed kwarg
+ n_embed = kwargs.pop("n_embed", None)
+ self.hidden_size = self.hidden_size if n_embed is None else n_embed
+ super().__post_init__(**kwargs)
+
+
+__all__ = ["BloomConfig"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bloom/modeling_bloom.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bloom/modeling_bloom.py
new file mode 100644
index 0000000000000000000000000000000000000000..71099024429aeb4fbb478804f877cf2ce7c21a8a
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/bloom/modeling_bloom.py
@@ -0,0 +1,987 @@
+# Copyright 2022 HuggingFace Inc. team and BigScience workshop.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch BLOOM model."""
+
+import math
+
+import torch
+from torch import nn
+from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, LayerNorm, MSELoss
+from torch.nn import functional as F
+
+from ...cache_utils import Cache, DynamicCache, StaticCache
+from ...generation import GenerationMixin
+from ...masking_utils import create_causal_mask
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import (
+ BaseModelOutputWithPastAndCrossAttentions,
+ CausalLMOutputWithCrossAttentions,
+ QuestionAnsweringModelOutput,
+ SequenceClassifierOutputWithPast,
+ TokenClassifierOutput,
+)
+from ...modeling_utils import PreTrainedModel
+from ...utils import (
+ auto_docstring,
+ logging,
+)
+from .configuration_bloom import BloomConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+def build_alibi_tensor(attention_mask: torch.Tensor, num_heads: int, dtype: torch.dtype) -> torch.Tensor:
+ """
+ Link to paper: https://huggingface.co/papers/2108.12409 Alibi tensor is not causal as the original paper mentions, it
+ relies on a translation invariance of softmax for quick implementation: with l being a tensor, and a fixed value
+ `softmax(l+a) = softmax(l)`. Based on
+ https://github.com/ofirpress/attention_with_linear_biases/blob/a35aaca144e0eb6b789dfcb46784c4b8e31b7983/fairseq/models/transformer.py#L742
+ TODO @thomasw21 this doesn't work as nicely due to the masking strategy, and so masking varies slightly.
+
+ Args:
+ Returns tensor shaped (batch_size * num_heads, 1, max_seq_len)
+ attention_mask (`torch.Tensor`):
+ Token-wise attention mask, this should be of shape (batch_size, max_seq_len).
+ num_heads (`int`):
+ number of heads
+ dtype (`torch.dtype`, *optional*, default=`torch.bfloat16`):
+ dtype of the output tensor
+ """
+ batch_size, seq_length = attention_mask.shape
+ closest_power_of_2 = 2 ** math.floor(math.log2(num_heads))
+ base = torch.tensor(
+ 2 ** (-(2 ** -(math.log2(closest_power_of_2) - 3))), device=attention_mask.device, dtype=torch.float32
+ )
+ powers = torch.arange(1, 1 + closest_power_of_2, device=attention_mask.device, dtype=torch.int32)
+ slopes = torch.pow(base, powers)
+
+ if closest_power_of_2 != num_heads:
+ extra_base = torch.tensor(
+ 2 ** (-(2 ** -(math.log2(2 * closest_power_of_2) - 3))), device=attention_mask.device, dtype=torch.float32
+ )
+ num_remaining_heads = min(closest_power_of_2, num_heads - closest_power_of_2)
+ extra_powers = torch.arange(1, 1 + 2 * num_remaining_heads, 2, device=attention_mask.device, dtype=torch.int32)
+ slopes = torch.cat([slopes, torch.pow(extra_base, extra_powers)], dim=0)
+
+ # Note: alibi will added to the attention bias that will be applied to the query, key product of attention
+ # => therefore alibi will have to be of shape (batch_size, num_heads, query_length, key_length)
+ # => here we set (batch_size=1, num_heads=num_heads, query_length=1, key_length=max_length)
+ # => the query_length dimension will then be broadcasted correctly
+ # This is more or less identical to T5's relative position bias:
+ # https://github.com/huggingface/transformers/blob/f681437203baa7671de3174b0fa583c349d9d5e1/src/transformers/models/t5/modeling_t5.py#L527
+ arange_tensor = ((attention_mask.cumsum(dim=-1) - 1) * attention_mask)[:, None, :]
+ alibi = slopes[..., None] * arange_tensor
+ return alibi.reshape(batch_size * num_heads, 1, seq_length).to(dtype)
+
+
+def dropout_add(x: torch.Tensor, residual: torch.Tensor, prob: float, training: bool) -> torch.Tensor:
+ """
+ Dropout add function
+
+ Args:
+ x (`torch.tensor`):
+ input tensor
+ residual (`torch.tensor`):
+ residual tensor
+ prob (`float`):
+ dropout probability
+ training (`bool`):
+ training mode
+ """
+ out = F.dropout(x, p=prob, training=training)
+ out = residual + out
+ return out
+
+
+def bloom_gelu_forward(x: torch.Tensor) -> torch.Tensor:
+ """
+ Custom bias GELU function. Adapted from Megatron-DeepSpeed code. Here we use a simple implementation (inference) to
+ make the model jitable.
+
+ Args:
+ x (`torch.tensor`):
+ input hidden states
+ """
+ return x * 0.5 * (1.0 + torch.tanh(0.79788456 * x * (1 + 0.044715 * x * x)))
+
+
+def bloom_gelu_back(g: torch.Tensor, x: torch.Tensor) -> torch.Tensor:
+ """
+ gradient of tanh approximation of gelu gradient of actual gelu is: 0.5 * (1. + torch.erf(x * 0.70710678)) +
+ 0.3989423 * x * torch.exp(-0.5 * x * x)
+
+ Args:
+ g (`torch.tensor`):
+ gradient output tensor
+ x (`torch.tensor`):
+ input tensor
+ """
+ x = x[0] # x is a tuple of 1 element, needs to unpack it first
+ tanh_out = torch.tanh(0.79788456 * x * (1 + 0.044715 * x * x))
+ # sqrt(2/pi) * 3 * 0.044715 -> 0.1070322243
+ ff = 0.5 * x * ((1 - tanh_out * tanh_out) * (0.79788456 + 0.1070322243 * x * x)) + 0.5 * (1 + tanh_out)
+ return ff * g
+
+
+class GeLUFunction(torch.autograd.Function):
+ @staticmethod
+ def forward(ctx, input: torch.Tensor) -> torch.Tensor:
+ ctx.save_for_backward(input)
+ return bloom_gelu_forward(input)
+
+ @staticmethod
+ def backward(ctx, grad_output: torch.Tensor) -> torch.Tensor:
+ input = ctx.saved_tensors
+ tmp = bloom_gelu_back(grad_output, input)
+ return tmp
+
+
+class BloomGelu(nn.Module):
+ """
+ Partly copied from Megatron-DeepSpeed code and adapted for our needs
+ """
+
+ def __init__(self):
+ super().__init__()
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ return GeLUFunction.apply(x)
+
+
+class BloomAttention(nn.Module):
+ def __init__(self, config: BloomConfig, layer_idx: int | None = None):
+ super().__init__()
+
+ self.pretraining_tp = config.pretraining_tp
+ self.slow_but_exact = config.slow_but_exact
+
+ self.hidden_size = config.hidden_size
+ self.num_heads = config.n_head
+ self.head_dim = self.hidden_size // self.num_heads
+ self.split_size = self.hidden_size
+ self.hidden_dropout = config.hidden_dropout
+
+ if self.head_dim * self.num_heads != self.hidden_size:
+ raise ValueError(
+ f"`hidden_size` must be divisible by num_heads (got `hidden_size`: {self.hidden_size} and `num_heads`:"
+ f" {self.num_heads})."
+ )
+
+ # Layer-wise attention scaling
+ self.inv_norm_factor = 1.0 / math.sqrt(self.head_dim)
+ self.beta = 1.0
+ self.layer_idx = layer_idx
+ if layer_idx is None:
+ logger.warning_once(
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
+ "when creating this class."
+ )
+
+ self.query_key_value = nn.Linear(self.hidden_size, 3 * self.hidden_size, bias=True)
+ self.dense = nn.Linear(self.hidden_size, self.hidden_size)
+ self.attention_dropout = nn.Dropout(config.attention_dropout)
+
+ def _reshape(self, fused_qkv: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ """
+ Split the last dimension into (num_heads, head_dim) and reshapes to (bs, heads, len, dim) shape
+ without making any copies, results share same memory storage as `fused_qkv`
+
+ Args:
+ fused_qkv (`torch.tensor`): [batch_size, seq_length, num_heads * 3 * head_dim]
+
+ Returns:
+ query: [batch_size, num_heads, seq_length, head_dim]
+ key: [batch_size, num_heads, seq_length, head_dim]
+ value: [batch_size, num_heads, seq_length, head_dim]
+ """
+ batch_size, seq_length, three_times_hidden_size = fused_qkv.shape
+ fused_qkv = fused_qkv.view(batch_size, seq_length, self.num_heads, 3, self.head_dim)
+ query_layer = fused_qkv[..., 0, :].transpose(1, 2)
+ key_layer = fused_qkv[..., 1, :].transpose(1, 2)
+ value_layer = fused_qkv[..., 2, :].transpose(1, 2)
+ return query_layer, key_layer, value_layer
+
+ def _merge_heads(self, x: torch.Tensor) -> torch.Tensor:
+ """
+ Merge heads together over the last dimension
+
+ Args:
+ x (`torch.tensor`): [batch_size * num_heads, seq_length, head_dim]
+
+ Returns:
+ torch.tensor: [batch_size, seq_length, num_heads * head_dim]
+ """
+ # What we want to achieve is:
+ # batch_size * num_heads, seq_length, head_dim -> batch_size, seq_length, num_heads * head_dim
+ batch_size_and_num_heads, seq_length, _ = x.shape
+ batch_size = batch_size_and_num_heads // self.num_heads
+
+ # First view to decompose the batch size
+ # batch_size * num_heads, seq_length, head_dim -> batch_size, num_heads, seq_length, head_dim
+ x = x.view(batch_size, self.num_heads, seq_length, self.head_dim)
+
+ # batch_size, num_heads, seq_length, head_dim -> batch_size, seq_length, num_heads, head_dim
+ x = x.permute(0, 2, 1, 3)
+
+ # batch_size, seq_length, num_heads, head_dim -> batch_size, seq_length, num_heads * head_dim
+ return x.reshape(batch_size, seq_length, self.num_heads * self.head_dim)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ residual: torch.Tensor,
+ alibi: torch.Tensor,
+ attention_mask: torch.Tensor,
+ layer_past: Cache | None = None,
+ use_cache: bool = False,
+ output_attentions: bool = False,
+ **kwargs,
+ ):
+ batch_size, q_length, _ = hidden_states.shape
+ fused_qkv = self.query_key_value(hidden_states) # [batch_size, seq_length, 3 x hidden_size]
+ # 3 x [batch_size, num_heads, seq_length, head_dim]
+ query_layer, key_layer, value_layer = self._reshape(fused_qkv)
+
+ if layer_past is not None:
+ key_layer, value_layer = layer_past.update(key_layer, value_layer, self.layer_idx)
+
+ # reshape qkv for further computations
+ query_layer = query_layer.reshape(batch_size * self.num_heads, -1, self.head_dim)
+ key_layer = key_layer.reshape(batch_size * self.num_heads, -1, self.head_dim).transpose(-1, -2)
+ value_layer = value_layer.reshape(batch_size * self.num_heads, -1, self.head_dim)
+
+ # [batch_size * num_heads, q_length, kv_length]
+ attention_scores = alibi.baddbmm(
+ batch1=query_layer,
+ batch2=key_layer,
+ beta=self.beta,
+ alpha=self.inv_norm_factor,
+ )
+
+ # change view to [batch_size, num_heads, q_length, kv_length]
+ attn_weights = attention_scores.view(batch_size, self.num_heads, q_length, -1)
+ if attention_mask is not None:
+ attn_weights = attn_weights + attention_mask
+
+ # cast attention scores to fp32, compute scaled softmax and cast back to initial dtype
+ attention_probs = F.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_layer.dtype)
+
+ # [batch_size, num_heads, q_length, kv_length]
+ attention_probs = self.attention_dropout(attention_probs)
+
+ # change view [batch_size x num_heads, q_length, kv_length]
+ attention_probs_reshaped = attention_probs.view(batch_size * self.num_heads, q_length, -1)
+
+ # matmul: [batch_size * num_heads, q_length, head_dim]
+ context_layer = torch.bmm(attention_probs_reshaped, value_layer)
+
+ # change view [batch_size, q_length, num_heads * head_dim]
+ context_layer = self._merge_heads(context_layer)
+
+ # aggregate results across tp ranks. See here: https://github.com/pytorch/pytorch/issues/76232
+ if self.pretraining_tp > 1 and self.slow_but_exact:
+ slices = self.hidden_size / self.pretraining_tp
+ output_tensor = torch.zeros_like(context_layer)
+ for i in range(self.pretraining_tp):
+ output_tensor = output_tensor + F.linear(
+ context_layer[:, :, int(i * slices) : int((i + 1) * slices)],
+ self.dense.weight[:, int(i * slices) : int((i + 1) * slices)],
+ )
+ else:
+ output_tensor = self.dense(context_layer)
+
+ output_tensor = dropout_add(output_tensor, residual, self.hidden_dropout, self.training)
+ return output_tensor, attention_probs
+
+
+class BloomMLP(nn.Module):
+ def __init__(self, config: BloomConfig):
+ super().__init__()
+ hidden_size = config.hidden_size
+
+ self.pretraining_tp = config.pretraining_tp
+ self.slow_but_exact = config.slow_but_exact
+ self.dense_h_to_4h = nn.Linear(hidden_size, 4 * hidden_size)
+ self.gelu_impl = BloomGelu()
+ self.dense_4h_to_h = nn.Linear(4 * hidden_size, hidden_size)
+ self.hidden_dropout = config.hidden_dropout
+
+ def forward(self, hidden_states: torch.Tensor, residual: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.gelu_impl(self.dense_h_to_4h(hidden_states))
+
+ if self.pretraining_tp > 1 and self.slow_but_exact:
+ intermediate_output = torch.zeros_like(residual)
+ slices = self.dense_4h_to_h.weight.shape[-1] / self.pretraining_tp
+ for i in range(self.pretraining_tp):
+ intermediate_output = intermediate_output + F.linear(
+ hidden_states[:, :, int(i * slices) : int((i + 1) * slices)],
+ self.dense_4h_to_h.weight[:, int(i * slices) : int((i + 1) * slices)],
+ )
+ else:
+ intermediate_output = self.dense_4h_to_h(hidden_states)
+
+ output = dropout_add(intermediate_output, residual, self.hidden_dropout, self.training)
+
+ return output
+
+
+class BloomBlock(GradientCheckpointingLayer):
+ def __init__(self, config: BloomConfig, layer_idx: int | None = None):
+ super().__init__()
+ hidden_size = config.hidden_size
+
+ self.input_layernorm = LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
+ self.num_heads = config.n_head
+ self.self_attention = BloomAttention(config, layer_idx)
+ self.post_attention_layernorm = LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
+
+ self.mlp = BloomMLP(config)
+
+ self.apply_residual_connection_post_layernorm = config.apply_residual_connection_post_layernorm
+ self.hidden_dropout = config.hidden_dropout
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ alibi: torch.Tensor,
+ attention_mask: torch.Tensor,
+ layer_past: Cache | None = None,
+ use_cache: bool = False,
+ output_attentions: bool = False,
+ **kwargs,
+ ):
+ # hidden_states: [batch_size, seq_length, hidden_size]
+
+ # Layer norm at the beginning of the transformer layer.
+ layernorm_output = self.input_layernorm(hidden_states)
+
+ # Layer norm post the self attention.
+ if self.apply_residual_connection_post_layernorm:
+ residual = layernorm_output
+ else:
+ residual = hidden_states
+
+ # Self attention.
+ attention_output, attn_weights = self.self_attention(
+ layernorm_output,
+ residual,
+ layer_past=layer_past,
+ attention_mask=attention_mask,
+ alibi=alibi,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ )
+
+ layernorm_output = self.post_attention_layernorm(attention_output)
+
+ # Get residual
+ if self.apply_residual_connection_post_layernorm:
+ residual = layernorm_output
+ else:
+ residual = attention_output
+
+ # MLP.
+ output = self.mlp(layernorm_output, residual)
+
+ return output, attn_weights # hidden_states, attentions
+
+
+@auto_docstring
+class BloomPreTrainedModel(PreTrainedModel):
+ config: BloomConfig
+ base_model_prefix = "transformer"
+ supports_gradient_checkpointing = True
+ _no_split_modules = ["BloomBlock"]
+ _skip_keys_device_placement = ["past_key_values"]
+ _can_compile_fullgraph = True
+
+
+@auto_docstring
+class BloomModel(BloomPreTrainedModel):
+ def __init__(self, config: BloomConfig):
+ super().__init__(config)
+
+ self.embed_dim = config.hidden_size
+ self.num_heads = config.n_head
+
+ # Embedding + LN Embedding
+ self.word_embeddings = nn.Embedding(config.vocab_size, self.embed_dim)
+ self.word_embeddings_layernorm = LayerNorm(self.embed_dim, eps=config.layer_norm_epsilon)
+
+ # Transformer blocks
+ self.h = nn.ModuleList([BloomBlock(config, layer_idx=i) for i in range(config.num_hidden_layers)])
+
+ # Final Layer Norm
+ self.ln_f = LayerNorm(self.embed_dim, eps=config.layer_norm_epsilon)
+
+ self.gradient_checkpointing = False
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def build_alibi_tensor(self, attention_mask: torch.Tensor, num_heads: int, dtype: torch.dtype) -> torch.Tensor:
+ return build_alibi_tensor(attention_mask, num_heads, dtype)
+
+ def get_input_embeddings(self):
+ return self.word_embeddings
+
+ def set_input_embeddings(self, new_embeddings: torch.Tensor):
+ self.word_embeddings = new_embeddings
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ attention_mask: torch.Tensor | None = None,
+ inputs_embeds: torch.LongTensor | None = None,
+ use_cache: bool | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple[torch.Tensor, ...] | BaseModelOutputWithPastAndCrossAttentions:
+ r"""
+ input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
+ `input_ids_length` = `sequence_length` if `past_key_values` is `None` else `past_key_values.get_seq_length()`
+ (`sequence_length` of input past key value states). Indices of input sequence tokens in the vocabulary.
+
+ If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
+ `input_ids`.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input-ids)
+ """
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ if (input_ids is None) ^ (inputs_embeds is not None):
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
+
+ if self.gradient_checkpointing and self.training and use_cache:
+ logger.warning_once(
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
+ )
+ use_cache = False
+
+ if inputs_embeds is None:
+ inputs_embeds = self.word_embeddings(input_ids)
+
+ if use_cache and past_key_values is None:
+ past_key_values = DynamicCache(config=self.config)
+
+ batch_size, seq_length, _ = inputs_embeds.shape
+ past_length = past_key_values.get_seq_length() if past_key_values is not None else 0
+ seq_length_with_past = seq_length + past_length
+
+ hidden_states = self.word_embeddings_layernorm(inputs_embeds)
+
+ all_self_attentions = () if output_attentions else None
+ all_hidden_states = () if output_hidden_states else None
+
+ # Compute alibi tensor: check build_alibi_tensor documentation
+ if attention_mask is None:
+ attention_mask = torch.ones((batch_size, seq_length_with_past), device=hidden_states.device)
+ else:
+ attention_mask = attention_mask.to(hidden_states.device)
+
+ alibi = self.build_alibi_tensor(attention_mask, self.num_heads, dtype=hidden_states.dtype)
+ causal_mask = create_causal_mask(
+ config=self.config,
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ )
+
+ for i, block in enumerate(self.h):
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ outputs = block(
+ hidden_states,
+ layer_past=past_key_values,
+ attention_mask=causal_mask,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ alibi=alibi,
+ )
+
+ hidden_states = outputs[0]
+ if output_attentions:
+ all_self_attentions = all_self_attentions + (outputs[1],)
+
+ # Add last hidden state
+ hidden_states = self.ln_f(hidden_states)
+
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ if not return_dict:
+ return tuple(
+ v for v in [hidden_states, past_key_values, all_hidden_states, all_self_attentions] if v is not None
+ )
+
+ return BaseModelOutputWithPastAndCrossAttentions(
+ last_hidden_state=hidden_states,
+ past_key_values=past_key_values,
+ hidden_states=all_hidden_states,
+ attentions=all_self_attentions,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ The Bloom Model transformer with a language modeling head on top (linear layer with weights tied to the input
+ embeddings).
+ """
+)
+class BloomForCausalLM(BloomPreTrainedModel, GenerationMixin):
+ _tied_weights_keys = {"lm_head.weight": "transformer.word_embeddings.weight"}
+
+ def __init__(self, config: BloomConfig):
+ super().__init__(config)
+ self.transformer = BloomModel(config)
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def set_output_embeddings(self, new_embeddings: torch.Tensor):
+ self.lm_head = new_embeddings
+
+ def prepare_inputs_for_generation(
+ self,
+ input_ids,
+ past_key_values=None,
+ attention_mask=None,
+ inputs_embeds=None,
+ use_cache=True,
+ is_first_iteration=False,
+ **kwargs,
+ ):
+ # Overwritten because of the fixed-shape attention mask creation
+
+ model_inputs = super().prepare_inputs_for_generation(
+ input_ids,
+ past_key_values=past_key_values,
+ attention_mask=attention_mask,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ is_first_iteration=is_first_iteration,
+ **kwargs,
+ )
+
+ # This part differs from other models because BLOOM needs a 2D mask to construct alibi tensor
+ # The only difference is the usage of 2D instead of 4D mask, but the shape will be static
+ if isinstance(past_key_values, StaticCache) and attention_mask is not None:
+ target_length = past_key_values.get_max_cache_shape()
+ batch_size, seq_length = attention_mask.shape
+ diff = target_length - seq_length
+
+ new_attn_mask = torch.zeros(batch_size, diff, device=attention_mask.device, dtype=attention_mask.dtype)
+ attention_mask = torch.cat([attention_mask, new_attn_mask], dim=-1)
+ model_inputs["attention_mask"] = attention_mask
+
+ return model_inputs
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ attention_mask: torch.Tensor | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ labels: torch.Tensor | None = None,
+ use_cache: bool | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ **kwargs,
+ ) -> tuple[torch.Tensor] | CausalLMOutputWithCrossAttentions:
+ r"""
+ input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
+ `input_ids_length` = `sequence_length` if `past_key_values` is `None` else `past_key_values.get_seq_length()`
+ (`sequence_length` of input past key value states). Indices of input sequence tokens in the vocabulary.
+
+ If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
+ `input_ids`.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input-ids)
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
+ `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
+ are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
+ """
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ transformer_outputs = self.transformer(
+ input_ids,
+ past_key_values=past_key_values,
+ attention_mask=attention_mask,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ hidden_states = transformer_outputs[0]
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(
+ logits,
+ labels,
+ vocab_size=self.config.vocab_size,
+ num_items_in_batch=kwargs.get("num_items_in_batch"),
+ )
+
+ if not return_dict:
+ output = (logits,) + transformer_outputs[1:]
+ return ((loss,) + output) if loss is not None else output
+
+ return CausalLMOutputWithCrossAttentions(
+ loss=loss,
+ logits=logits,
+ past_key_values=transformer_outputs.past_key_values,
+ hidden_states=transformer_outputs.hidden_states,
+ attentions=transformer_outputs.attentions,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ The Bloom Model transformer with a sequence classification head on top (linear layer).
+
+ [`BloomForSequenceClassification`] uses the last token in order to do the classification, as other causal models
+ (e.g. GPT-1) do.
+
+ Since it does classification on the last token, it requires to know the position of the last token. If a
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
+ each row of the batch).
+ """
+)
+class BloomForSequenceClassification(BloomPreTrainedModel):
+ def __init__(self, config: BloomConfig):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+ self.transformer = BloomModel(config)
+ self.score = nn.Linear(config.hidden_size, config.num_labels, bias=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ attention_mask: torch.Tensor | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ labels: torch.Tensor | None = None,
+ use_cache: bool | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple[torch.Tensor] | SequenceClassifierOutputWithPast:
+ r"""
+ input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
+ `input_ids_length` = `sequence_length` if `past_key_values` is `None` else `past_key_values.get_seq_length()`
+ (`sequence_length` of input past key value states). Indices of input sequence tokens in the vocabulary.
+
+ If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
+ `input_ids`.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input-ids)
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ transformer_outputs = self.transformer(
+ input_ids,
+ past_key_values=past_key_values,
+ attention_mask=attention_mask,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ hidden_states = transformer_outputs[0]
+ logits = self.score(hidden_states)
+
+ if input_ids is not None:
+ batch_size = input_ids.shape[0]
+ else:
+ batch_size = inputs_embeds.shape[0]
+
+ if self.config.pad_token_id is None and batch_size != 1:
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
+ if self.config.pad_token_id is None:
+ last_non_pad_token = -1
+ elif input_ids is not None:
+ # To handle both left- and right- padding, we take the rightmost token that is not equal to pad_token_id
+ non_pad_mask = (input_ids != self.config.pad_token_id).to(logits.device, torch.int32)
+ token_indices = torch.arange(input_ids.shape[-1], device=logits.device, dtype=torch.int32)
+ last_non_pad_token = (token_indices * non_pad_mask).argmax(-1)
+ else:
+ last_non_pad_token = -1
+ logger.warning_once(
+ f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
+ "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
+ )
+
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), last_non_pad_token]
+
+ loss = None
+ if labels is not None:
+ if self.config.problem_type is None:
+ if self.num_labels == 1:
+ self.config.problem_type = "regression"
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
+ self.config.problem_type = "single_label_classification"
+ else:
+ self.config.problem_type = "multi_label_classification"
+
+ if self.config.problem_type == "regression":
+ loss_fct = MSELoss()
+ if self.num_labels == 1:
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
+ else:
+ loss = loss_fct(pooled_logits, labels)
+ elif self.config.problem_type == "single_label_classification":
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(pooled_logits, labels)
+ elif self.config.problem_type == "multi_label_classification":
+ loss_fct = BCEWithLogitsLoss()
+ loss = loss_fct(pooled_logits, labels)
+ if not return_dict:
+ output = (pooled_logits,) + transformer_outputs[1:]
+ return ((loss,) + output) if loss is not None else output
+
+ return SequenceClassifierOutputWithPast(
+ loss=loss,
+ logits=pooled_logits,
+ past_key_values=transformer_outputs.past_key_values,
+ hidden_states=transformer_outputs.hidden_states,
+ attentions=transformer_outputs.attentions,
+ )
+
+
+@auto_docstring
+class BloomForTokenClassification(BloomPreTrainedModel):
+ def __init__(self, config: BloomConfig):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+
+ self.transformer = BloomModel(config)
+ if hasattr(config, "classifier_dropout") and config.classifier_dropout is not None:
+ classifier_dropout = config.classifier_dropout
+ elif hasattr(config, "hidden_dropout") and config.hidden_dropout is not None:
+ classifier_dropout = config.hidden_dropout
+ else:
+ classifier_dropout = 0.1
+ self.dropout = nn.Dropout(classifier_dropout)
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ attention_mask: torch.Tensor | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ labels: torch.Tensor | None = None,
+ use_cache: bool | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple[torch.Tensor] | TokenClassifierOutput:
+ r"""
+ input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
+ `input_ids_length` = `sequence_length` if `past_key_values` is `None` else `past_key_values.get_seq_length()`
+ (`sequence_length` of input past key value states). Indices of input sequence tokens in the vocabulary.
+
+ If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
+ `input_ids`.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input-ids)
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ transformer_outputs = self.transformer(
+ input_ids,
+ past_key_values=past_key_values,
+ attention_mask=attention_mask,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ hidden_states = transformer_outputs[0]
+ hidden_states = self.dropout(hidden_states)
+ logits = self.classifier(hidden_states)
+
+ loss = None
+ if labels is not None:
+ # move labels to correct device
+ labels = labels.to(logits.device)
+ batch_size, seq_length = labels.shape
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(
+ logits.view(batch_size * seq_length, self.num_labels), labels.view(batch_size * seq_length)
+ )
+
+ if not return_dict:
+ output = (logits,) + transformer_outputs[2:]
+ return ((loss,) + output) if loss is not None else output
+
+ return TokenClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=transformer_outputs.hidden_states,
+ attentions=transformer_outputs.attentions,
+ )
+
+
+@auto_docstring
+class BloomForQuestionAnswering(BloomPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.transformer = BloomModel(config)
+ self.qa_outputs = nn.Linear(config.hidden_size, 2)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ start_positions: torch.LongTensor | None = None,
+ end_positions: torch.LongTensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple | QuestionAnsweringModelOutput:
+ r"""
+ input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
+ `input_ids_length` = `sequence_length` if `past_key_values` is `None` else `past_key_values.get_seq_length()`
+ (`sequence_length` of input past key value states). Indices of input sequence tokens in the vocabulary.
+
+ If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
+ `input_ids`.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input-ids)
+ """
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ outputs = self.transformer(
+ input_ids,
+ attention_mask=attention_mask,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ sequence_output = outputs[0]
+
+ logits = self.qa_outputs(sequence_output)
+ start_logits, end_logits = logits.split(1, dim=-1)
+ start_logits = start_logits.squeeze(-1).contiguous()
+ end_logits = end_logits.squeeze(-1).contiguous()
+
+ total_loss = None
+ if start_positions is not None and end_positions is not None:
+ # If we are on multi-GPU, split add a dimension
+ if len(start_positions.size()) > 1:
+ start_positions = start_positions.squeeze(-1)
+ if len(end_positions.size()) > 1:
+ end_positions = end_positions.squeeze(-1)
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
+ ignored_index = start_logits.size(1)
+ start_positions = start_positions.clamp(0, ignored_index)
+ end_positions = end_positions.clamp(0, ignored_index)
+
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
+ start_loss = loss_fct(start_logits, start_positions)
+ end_loss = loss_fct(end_logits, end_positions)
+ total_loss = (start_loss + end_loss) / 2
+
+ if not return_dict:
+ output = (start_logits, end_logits) + outputs[2:]
+ return ((total_loss,) + output) if total_loss is not None else output
+
+ return QuestionAnsweringModelOutput(
+ loss=total_loss,
+ start_logits=start_logits,
+ end_logits=end_logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+__all__ = [
+ "BloomForCausalLM",
+ "BloomModel",
+ "BloomPreTrainedModel",
+ "BloomForSequenceClassification",
+ "BloomForTokenClassification",
+ "BloomForQuestionAnswering",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/camembert/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/camembert/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..070e8311ae6ff33169a88b589ca9c027c40c274f
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/camembert/__init__.py
@@ -0,0 +1,28 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_camembert import *
+ from .modeling_camembert import *
+ from .tokenization_camembert import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/camembert/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/camembert/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5e8243fa7377f99ee09c0e0112581cade000d532
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/camembert/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/camembert/__pycache__/configuration_camembert.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/camembert/__pycache__/configuration_camembert.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..04ca19989b09c5d4fa78c36983e11143d4d0ebea
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/camembert/__pycache__/configuration_camembert.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/camembert/__pycache__/modeling_camembert.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/camembert/__pycache__/modeling_camembert.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..58e0fb027e00eed8426ffa37419850517f56ff05
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/camembert/__pycache__/modeling_camembert.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/camembert/__pycache__/modular_camembert.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/camembert/__pycache__/modular_camembert.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2c5604af64268e87077297b4f787ce9c930e5a6a
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/camembert/__pycache__/modular_camembert.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/camembert/__pycache__/tokenization_camembert.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/camembert/__pycache__/tokenization_camembert.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..663518d556482351ecb9f9af6cb695b8c7fea29c
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/camembert/__pycache__/tokenization_camembert.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/camembert/configuration_camembert.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/camembert/configuration_camembert.py
new file mode 100644
index 0000000000000000000000000000000000000000..5890f34571206c8f04afcf603af227f95f876a5e
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/camembert/configuration_camembert.py
@@ -0,0 +1,66 @@
+# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
+# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""CamemBERT configuration"""
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring
+
+
+@auto_docstring(checkpoint="almanach/camembert-base")
+@strict
+class CamembertConfig(PreTrainedConfig):
+ r"""
+ Example:
+
+ ```python
+ >>> from transformers import CamembertConfig, CamembertModel
+
+ >>> # Initializing a Camembert almanach/camembert-base style configuration
+ >>> configuration = CamembertConfig()
+
+ >>> # Initializing a model (with random weights) from the almanach/camembert-base style configuration
+ >>> model = CamembertModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "camembert"
+
+ vocab_size: int = 30522
+ hidden_size: int = 768
+ num_hidden_layers: int = 12
+ num_attention_heads: int = 12
+ intermediate_size: int = 3072
+ hidden_act: str = "gelu"
+ hidden_dropout_prob: float | int = 0.1
+ attention_probs_dropout_prob: float | int = 0.1
+ max_position_embeddings: int = 512
+ type_vocab_size: int = 2
+ initializer_range: float = 0.02
+ layer_norm_eps: float = 1e-12
+ pad_token_id: int | None = 1
+ bos_token_id: int | None = 0
+ eos_token_id: int | list[int] | None = 2
+ use_cache: bool = True
+ classifier_dropout: float | int | None = None
+ is_decoder: bool = False
+ add_cross_attention: bool = False
+ tie_word_embeddings: bool = True
+
+
+__all__ = ["CamembertConfig"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/camembert/modeling_camembert.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/camembert/modeling_camembert.py
new file mode 100644
index 0000000000000000000000000000000000000000..9d10a8aeaef1aa732107bc061a7213f51b2b0f7a
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/camembert/modeling_camembert.py
@@ -0,0 +1,1271 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/camembert/modular_camembert.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_camembert.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2019 Inria, Facebook AI Research and the HuggingFace Inc. team.
+# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from collections.abc import Callable
+
+import torch
+import torch.nn as nn
+from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
+
+from ... import initialization as init
+from ...activations import ACT2FN, gelu
+from ...cache_utils import Cache, DynamicCache, EncoderDecoderCache
+from ...generation import GenerationMixin
+from ...masking_utils import create_bidirectional_mask, create_causal_mask
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import (
+ BaseModelOutputWithPastAndCrossAttentions,
+ BaseModelOutputWithPoolingAndCrossAttentions,
+ CausalLMOutputWithCrossAttentions,
+ MaskedLMOutput,
+ MultipleChoiceModelOutput,
+ QuestionAnsweringModelOutput,
+ SequenceClassifierOutput,
+ TokenClassifierOutput,
+)
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
+from ...processing_utils import Unpack
+from ...pytorch_utils import apply_chunking_to_forward
+from ...utils import TransformersKwargs, auto_docstring, logging
+from ...utils.generic import can_return_tuple, merge_with_config_defaults
+from ...utils.output_capturing import capture_outputs
+from .configuration_camembert import CamembertConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+class CamembertEmbeddings(nn.Module):
+ """Construct the embeddings from word, position and token_type embeddings."""
+
+ def __init__(self, config):
+ super().__init__()
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
+ self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
+
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
+ self.register_buffer(
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
+ )
+ self.register_buffer(
+ "token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False
+ )
+
+ self.padding_idx = config.pad_token_id
+ self.position_embeddings = nn.Embedding(
+ config.max_position_embeddings, config.hidden_size, padding_idx=self.padding_idx
+ )
+
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ past_key_values_length: int = 0,
+ ) -> torch.Tensor:
+ if position_ids is None:
+ if input_ids is not None:
+ # Create the position ids from the input token ids. Any padded tokens remain padded.
+ position_ids = self.create_position_ids_from_input_ids(
+ input_ids, self.padding_idx, past_key_values_length
+ )
+ else:
+ position_ids = self.create_position_ids_from_inputs_embeds(inputs_embeds, self.padding_idx)
+
+ if input_ids is not None:
+ input_shape = input_ids.size()
+ else:
+ input_shape = inputs_embeds.size()[:-1]
+
+ batch_size, seq_length = input_shape
+
+ # Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
+ # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
+ # issue #5664
+ if token_type_ids is None:
+ if hasattr(self, "token_type_ids"):
+ # NOTE: We assume either pos ids to have bsz == 1 (broadcastable) or bsz == effective bsz (input_shape[0])
+ buffered_token_type_ids = self.token_type_ids.expand(position_ids.shape[0], -1)
+ buffered_token_type_ids = torch.gather(buffered_token_type_ids, dim=1, index=position_ids)
+ token_type_ids = buffered_token_type_ids.expand(batch_size, seq_length)
+ else:
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
+
+ if inputs_embeds is None:
+ inputs_embeds = self.word_embeddings(input_ids)
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
+ embeddings = inputs_embeds + token_type_embeddings
+
+ position_embeddings = self.position_embeddings(position_ids)
+ embeddings = embeddings + position_embeddings
+
+ embeddings = self.LayerNorm(embeddings)
+ embeddings = self.dropout(embeddings)
+ return embeddings
+
+ @staticmethod
+ def create_position_ids_from_inputs_embeds(inputs_embeds, padding_idx):
+ """
+ We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids.
+
+ Args:
+ inputs_embeds: torch.Tensor
+
+ Returns: torch.Tensor
+ """
+ input_shape = inputs_embeds.size()[:-1]
+ sequence_length = input_shape[1]
+
+ position_ids = torch.arange(
+ padding_idx + 1, sequence_length + padding_idx + 1, dtype=torch.long, device=inputs_embeds.device
+ )
+ return position_ids.unsqueeze(0).expand(input_shape)
+
+ @staticmethod
+ def create_position_ids_from_input_ids(input_ids, padding_idx, past_key_values_length=0):
+ """
+ Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols
+ are ignored. This is modified from fairseq's `utils.make_positions`.
+
+ Args:
+ x: torch.Tensor x:
+
+ Returns: torch.Tensor
+ """
+ # The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA.
+ mask = input_ids.ne(padding_idx).int()
+ incremental_indices = (torch.cumsum(mask, dim=1).type_as(mask) + past_key_values_length) * mask
+ return incremental_indices.long() + padding_idx
+
+
+def eager_attention_forward(
+ module: nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: torch.Tensor | None,
+ scaling: float | None = None,
+ dropout: float = 0.0,
+ **kwargs: Unpack[TransformersKwargs],
+):
+ if scaling is None:
+ scaling = query.size(-1) ** -0.5
+
+ # Take the dot product between "query" and "key" to get the raw attention scores.
+ attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
+
+ if attention_mask is not None:
+ attn_weights = attn_weights + attention_mask
+
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
+
+ attn_output = torch.matmul(attn_weights, value)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+
+ return attn_output, attn_weights
+
+
+class CamembertSelfAttention(nn.Module):
+ def __init__(self, config, is_causal=False, layer_idx=None):
+ super().__init__()
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
+ raise ValueError(
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
+ f"heads ({config.num_attention_heads})"
+ )
+ self.config = config
+
+ self.num_attention_heads = config.num_attention_heads
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
+ self.scaling = self.attention_head_size**-0.5
+
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
+
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
+
+ self.is_decoder = config.is_decoder
+ self.is_causal = is_causal
+ self.layer_idx = layer_idx
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.FloatTensor | None = None,
+ past_key_values: Cache | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor]:
+ input_shape = hidden_states.shape[:-1]
+ hidden_shape = (*input_shape, -1, self.attention_head_size)
+
+ # get all proj
+ query_layer = self.query(hidden_states).view(*hidden_shape).transpose(1, 2)
+ key_layer = self.key(hidden_states).view(*hidden_shape).transpose(1, 2)
+ value_layer = self.value(hidden_states).view(*hidden_shape).transpose(1, 2)
+
+ if past_key_values is not None:
+ # decoder-only camembert can have a simple dynamic cache for example
+ current_past_key_values = past_key_values
+ if isinstance(past_key_values, EncoderDecoderCache):
+ current_past_key_values = past_key_values.self_attention_cache
+
+ # save all key/value_layer to cache to be re-used for fast auto-regressive generation
+ key_layer, value_layer = current_past_key_values.update(key_layer, value_layer, self.layer_idx)
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_layer,
+ key_layer,
+ value_layer,
+ attention_mask,
+ dropout=0.0 if not self.training else self.dropout.p,
+ scaling=self.scaling,
+ **kwargs,
+ )
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ return attn_output, attn_weights
+
+
+class CamembertCrossAttention(nn.Module):
+ def __init__(self, config, is_causal=False, layer_idx=None):
+ super().__init__()
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
+ raise ValueError(
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
+ f"heads ({config.num_attention_heads})"
+ )
+ self.config = config
+
+ self.num_attention_heads = config.num_attention_heads
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
+ self.scaling = self.attention_head_size**-0.5
+
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
+
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
+
+ self.is_causal = is_causal
+ self.layer_idx = layer_idx
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ past_key_values: EncoderDecoderCache | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor]:
+ # determine input shapes
+ input_shape = hidden_states.shape[:-1]
+
+ hidden_shape = (*input_shape, -1, self.attention_head_size)
+
+ # get query proj
+ query_layer = self.query(hidden_states).view(hidden_shape).transpose(1, 2)
+
+ is_updated = past_key_values.is_updated.get(self.layer_idx) if past_key_values is not None else False
+ if past_key_values is not None and is_updated:
+ # reuse k,v, cross_attentions
+ key_layer = past_key_values.cross_attention_cache.layers[self.layer_idx].keys
+ value_layer = past_key_values.cross_attention_cache.layers[self.layer_idx].values
+ else:
+ kv_shape = (*encoder_hidden_states.shape[:-1], -1, self.attention_head_size)
+ key_layer = self.key(encoder_hidden_states).view(kv_shape).transpose(1, 2)
+ value_layer = self.value(encoder_hidden_states).view(kv_shape).transpose(1, 2)
+
+ if past_key_values is not None:
+ # save all states to the cache
+ key_layer, value_layer = past_key_values.cross_attention_cache.update(
+ key_layer, value_layer, self.layer_idx
+ )
+ # set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls
+ past_key_values.is_updated[self.layer_idx] = True
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_layer,
+ key_layer,
+ value_layer,
+ attention_mask,
+ dropout=0.0 if not self.training else self.dropout.p,
+ scaling=self.scaling,
+ **kwargs,
+ )
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ return attn_output, attn_weights
+
+
+class CamembertSelfOutput(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
+ return hidden_states
+
+
+class CamembertAttention(nn.Module):
+ def __init__(self, config, is_causal=False, layer_idx=None, is_cross_attention=False):
+ super().__init__()
+ self.is_cross_attention = is_cross_attention
+ attention_class = CamembertCrossAttention if is_cross_attention else CamembertSelfAttention
+ self.self = attention_class(config, is_causal=is_causal, layer_idx=layer_idx)
+ self.output = CamembertSelfOutput(config)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.FloatTensor | None = None,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ encoder_attention_mask: torch.FloatTensor | None = None,
+ past_key_values: Cache | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor]:
+ attention_mask = attention_mask if not self.is_cross_attention else encoder_attention_mask
+ attention_output, attn_weights = self.self(
+ hidden_states,
+ encoder_hidden_states=encoder_hidden_states,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ **kwargs,
+ )
+ attention_output = self.output(attention_output, hidden_states)
+ return attention_output, attn_weights
+
+
+class CamembertIntermediate(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
+ if isinstance(config.hidden_act, str):
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
+ else:
+ self.intermediate_act_fn = config.hidden_act
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.intermediate_act_fn(hidden_states)
+ return hidden_states
+
+
+class CamembertOutput(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
+ return hidden_states
+
+
+class CamembertLayer(GradientCheckpointingLayer):
+ def __init__(self, config, layer_idx=None):
+ super().__init__()
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
+ self.seq_len_dim = 1
+ self.attention = CamembertAttention(config, is_causal=config.is_decoder, layer_idx=layer_idx)
+ self.is_decoder = config.is_decoder
+ self.add_cross_attention = config.add_cross_attention
+ if self.add_cross_attention:
+ if not self.is_decoder:
+ raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
+ self.crossattention = CamembertAttention(
+ config,
+ is_causal=False,
+ layer_idx=layer_idx,
+ is_cross_attention=True,
+ )
+ self.intermediate = CamembertIntermediate(config)
+ self.output = CamembertOutput(config)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.FloatTensor | None = None,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ encoder_attention_mask: torch.FloatTensor | None = None,
+ past_key_values: Cache | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.Tensor:
+ self_attention_output, _ = self.attention(
+ hidden_states,
+ attention_mask,
+ past_key_values=past_key_values,
+ **kwargs,
+ )
+ attention_output = self_attention_output
+
+ if self.is_decoder and encoder_hidden_states is not None:
+ if not hasattr(self, "crossattention"):
+ raise ValueError(
+ f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
+ " by setting `config.add_cross_attention=True`"
+ )
+
+ cross_attention_output, _ = self.crossattention(
+ self_attention_output,
+ None, # attention_mask
+ encoder_hidden_states,
+ encoder_attention_mask,
+ past_key_values=past_key_values,
+ **kwargs,
+ )
+ attention_output = cross_attention_output
+
+ layer_output = apply_chunking_to_forward(
+ self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
+ )
+ return layer_output
+
+ def feed_forward_chunk(self, attention_output):
+ intermediate_output = self.intermediate(attention_output)
+ layer_output = self.output(intermediate_output, attention_output)
+ return layer_output
+
+
+class CamembertLMHead(nn.Module):
+ """Camembert Head for masked language modeling."""
+
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size)
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
+
+ def forward(self, features, **kwargs):
+ x = self.dense(features)
+ x = gelu(x)
+ x = self.layer_norm(x)
+
+ # project back to size of vocabulary with bias
+ x = self.decoder(x)
+
+ return x
+
+
+@auto_docstring
+class CamembertPreTrainedModel(PreTrainedModel):
+ config_class = CamembertConfig
+ base_model_prefix = "roberta"
+ supports_gradient_checkpointing = True
+ _supports_flash_attn = True
+ _supports_sdpa = True
+ _supports_flex_attn = True
+ _supports_attention_backend = True
+ _can_record_outputs = {
+ "hidden_states": CamembertLayer,
+ "attentions": CamembertSelfAttention,
+ "cross_attentions": CamembertCrossAttention,
+ }
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ """Initialize the weights"""
+ super()._init_weights(module)
+ if isinstance(module, CamembertLMHead):
+ init.zeros_(module.bias)
+ elif isinstance(module, CamembertEmbeddings):
+ init.copy_(module.position_ids, torch.arange(module.position_ids.shape[-1]).expand((1, -1)))
+ init.zeros_(module.token_type_ids)
+
+
+class CamembertEncoder(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.layer = nn.ModuleList([CamembertLayer(config, layer_idx=i) for i in range(config.num_hidden_layers)])
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.FloatTensor | None = None,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ encoder_attention_mask: torch.FloatTensor | None = None,
+ past_key_values: Cache | None = None,
+ use_cache: bool | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | BaseModelOutputWithPastAndCrossAttentions:
+ for i, layer_module in enumerate(self.layer):
+ hidden_states = layer_module(
+ hidden_states,
+ attention_mask,
+ encoder_hidden_states, # as a positional argument for gradient checkpointing
+ encoder_attention_mask=encoder_attention_mask,
+ past_key_values=past_key_values,
+ **kwargs,
+ )
+
+ return BaseModelOutputWithPastAndCrossAttentions(
+ last_hidden_state=hidden_states,
+ past_key_values=past_key_values if use_cache else None,
+ )
+
+
+class CamembertPooler(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.activation = nn.Tanh()
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ # We "pool" the model by simply taking the hidden state corresponding
+ # to the first token.
+ first_token_tensor = hidden_states[:, 0]
+ pooled_output = self.dense(first_token_tensor)
+ pooled_output = self.activation(pooled_output)
+ return pooled_output
+
+
+@auto_docstring(
+ custom_intro="""
+ The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
+ cross-attention is added between the self-attention layers, following the architecture described in [Attention is
+ all you need](https://huggingface.co/papers/1706.03762) by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
+ Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
+
+ To behave as an decoder the model needs to be initialized with the `is_decoder` argument of the configuration set
+ to `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and
+ `add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass.
+ """
+)
+class CamembertModel(CamembertPreTrainedModel):
+ _no_split_modules = ["CamembertEmbeddings", "CamembertLayer"]
+
+ def __init__(self, config, add_pooling_layer=True):
+ r"""
+ add_pooling_layer (bool, *optional*, defaults to `True`):
+ Whether to add a pooling layer
+ """
+ super().__init__(config)
+ self.config = config
+ self.gradient_checkpointing = False
+
+ self.embeddings = CamembertEmbeddings(config)
+ self.encoder = CamembertEncoder(config)
+
+ self.pooler = CamembertPooler(config) if add_pooling_layer else None
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.embeddings.word_embeddings
+
+ def set_input_embeddings(self, value):
+ self.embeddings.word_embeddings = value
+
+ @merge_with_config_defaults
+ @capture_outputs
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ token_type_ids: torch.Tensor | None = None,
+ position_ids: torch.Tensor | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ encoder_hidden_states: torch.Tensor | None = None,
+ encoder_attention_mask: torch.Tensor | None = None,
+ past_key_values: Cache | None = None,
+ use_cache: bool | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | BaseModelOutputWithPoolingAndCrossAttentions:
+ if (input_ids is None) ^ (inputs_embeds is not None):
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
+
+ if self.config.is_decoder:
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
+ else:
+ use_cache = False
+
+ if use_cache and past_key_values is None:
+ past_key_values = (
+ EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache(config=self.config))
+ if encoder_hidden_states is not None or self.config.is_encoder_decoder
+ else DynamicCache(config=self.config)
+ )
+
+ past_key_values_length = past_key_values.get_seq_length() if past_key_values is not None else 0
+
+ embedding_output = self.embeddings(
+ input_ids=input_ids,
+ position_ids=position_ids,
+ token_type_ids=token_type_ids,
+ inputs_embeds=inputs_embeds,
+ past_key_values_length=past_key_values_length,
+ )
+
+ attention_mask, encoder_attention_mask = self._create_attention_masks(
+ attention_mask=attention_mask,
+ encoder_attention_mask=encoder_attention_mask,
+ embedding_output=embedding_output,
+ encoder_hidden_states=encoder_hidden_states,
+ past_key_values=past_key_values,
+ )
+
+ encoder_outputs = self.encoder(
+ embedding_output,
+ attention_mask=attention_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ position_ids=position_ids,
+ **kwargs,
+ )
+ sequence_output = encoder_outputs.last_hidden_state
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
+
+ return BaseModelOutputWithPoolingAndCrossAttentions(
+ last_hidden_state=sequence_output,
+ pooler_output=pooled_output,
+ past_key_values=encoder_outputs.past_key_values,
+ )
+
+ def _create_attention_masks(
+ self,
+ attention_mask,
+ encoder_attention_mask,
+ embedding_output,
+ encoder_hidden_states,
+ past_key_values,
+ ):
+ if self.config.is_decoder:
+ attention_mask = create_causal_mask(
+ config=self.config,
+ inputs_embeds=embedding_output,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ )
+ else:
+ attention_mask = create_bidirectional_mask(
+ config=self.config,
+ inputs_embeds=embedding_output,
+ attention_mask=attention_mask,
+ )
+
+ if encoder_attention_mask is not None:
+ encoder_attention_mask = create_bidirectional_mask(
+ config=self.config,
+ inputs_embeds=embedding_output,
+ attention_mask=encoder_attention_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ )
+
+ return attention_mask, encoder_attention_mask
+
+
+@auto_docstring
+class CamembertForMaskedLM(CamembertPreTrainedModel):
+ _tied_weights_keys = {
+ "lm_head.decoder.weight": "roberta.embeddings.word_embeddings.weight",
+ "lm_head.decoder.bias": "lm_head.bias",
+ }
+
+ def __init__(self, config):
+ super().__init__(config)
+
+ if config.is_decoder:
+ logger.warning(
+ "If you want to use `CamembertForMaskedLM` make sure `config.is_decoder=False` for "
+ "bi-directional self-attention."
+ )
+ self.lm_head = CamembertLMHead(config)
+
+ self.roberta = CamembertModel(config, add_pooling_layer=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_output_embeddings(self):
+ return self.lm_head.decoder
+
+ def set_output_embeddings(self, new_embeddings):
+ self.lm_head.decoder = new_embeddings
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ encoder_attention_mask: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | MaskedLMOutput:
+ r"""
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,1]`:
+
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token.
+ This parameter can only be used when the model is initialized with `type_vocab_size` parameter with value
+ >= 2. All the value in this tensor should be always < type_vocab_size.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
+ """
+ outputs = self.roberta(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ return_dict=True,
+ **kwargs,
+ )
+ sequence_output = outputs[0]
+ prediction_scores = self.lm_head(sequence_output)
+
+ masked_lm_loss = None
+ if labels is not None:
+ # move labels to correct device
+ labels = labels.to(prediction_scores.device)
+ loss_fct = CrossEntropyLoss()
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
+
+ return MaskedLMOutput(
+ loss=masked_lm_loss,
+ logits=prediction_scores,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+class CamembertClassificationHead(nn.Module):
+ """Head for sentence-level classification tasks."""
+
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ classifier_dropout = (
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
+ )
+ self.dropout = nn.Dropout(classifier_dropout)
+ self.out_proj = nn.Linear(config.hidden_size, config.num_labels)
+
+ def forward(self, features, **kwargs):
+ x = features[:, 0, :] # take token (equiv. to [CLS])
+ x = self.dropout(x)
+ x = self.dense(x)
+ x = torch.tanh(x)
+ x = self.dropout(x)
+ x = self.out_proj(x)
+ return x
+
+
+@auto_docstring(
+ custom_intro="""
+ Camembert Model transformer with a sequence classification/regression head on top (a linear layer on top of the
+ pooled output) e.g. for GLUE tasks.
+ """
+)
+class CamembertForSequenceClassification(CamembertPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+ self.config = config
+ self.classifier = CamembertClassificationHead(config)
+
+ self.roberta = CamembertModel(config, add_pooling_layer=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | SequenceClassifierOutput:
+ r"""
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,1]`:
+
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token.
+ This parameter can only be used when the model is initialized with `type_vocab_size` parameter with value
+ >= 2. All the value in this tensor should be always < type_vocab_size.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+ outputs = self.roberta(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ return_dict=True,
+ **kwargs,
+ )
+ sequence_output = outputs[0]
+ logits = self.classifier(sequence_output)
+
+ loss = None
+ if labels is not None:
+ # move labels to correct device
+ labels = labels.to(logits.device)
+ if self.config.problem_type is None:
+ if self.num_labels == 1:
+ self.config.problem_type = "regression"
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
+ self.config.problem_type = "single_label_classification"
+ else:
+ self.config.problem_type = "multi_label_classification"
+
+ if self.config.problem_type == "regression":
+ loss_fct = MSELoss()
+ if self.num_labels == 1:
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
+ else:
+ loss = loss_fct(logits, labels)
+ elif self.config.problem_type == "single_label_classification":
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+ elif self.config.problem_type == "multi_label_classification":
+ loss_fct = BCEWithLogitsLoss()
+ loss = loss_fct(logits, labels)
+
+ return SequenceClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+class CamembertForMultipleChoice(CamembertPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+ self.classifier = nn.Linear(config.hidden_size, 1)
+
+ self.roberta = CamembertModel(config, add_pooling_layer=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | MultipleChoiceModelOutput:
+ r"""
+ input_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input-ids)
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,1]`:
+
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token.
+ This parameter can only be used when the model is initialized with `type_vocab_size` parameter with value
+ >= 2. All the value in this tensor should be always < type_vocab_size.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
+ num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
+ `input_ids` above)
+ position_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
+ config.max_position_embeddings - 1]`.
+
+ [What are position IDs?](../glossary#position-ids)
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_choices, sequence_length, hidden_size)`, *optional*):
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
+ model's internal embedding lookup matrix.
+ """
+ num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
+
+ flat_input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
+ flat_position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
+ flat_token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
+ flat_attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
+ flat_inputs_embeds = (
+ inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
+ if inputs_embeds is not None
+ else None
+ )
+
+ outputs = self.roberta(
+ flat_input_ids,
+ position_ids=flat_position_ids,
+ token_type_ids=flat_token_type_ids,
+ attention_mask=flat_attention_mask,
+ inputs_embeds=flat_inputs_embeds,
+ return_dict=True,
+ **kwargs,
+ )
+ pooled_output = outputs[1]
+
+ pooled_output = self.dropout(pooled_output)
+ logits = self.classifier(pooled_output)
+ reshaped_logits = logits.view(-1, num_choices)
+
+ loss = None
+ if labels is not None:
+ # move labels to correct device
+ labels = labels.to(reshaped_logits.device)
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(reshaped_logits, labels)
+
+ return MultipleChoiceModelOutput(
+ loss=loss,
+ logits=reshaped_logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+class CamembertForTokenClassification(CamembertPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+ classifier_dropout = (
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
+ )
+ self.dropout = nn.Dropout(classifier_dropout)
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
+
+ self.roberta = CamembertModel(config, add_pooling_layer=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | TokenClassifierOutput:
+ r"""
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,1]`:
+
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token.
+ This parameter can only be used when the model is initialized with `type_vocab_size` parameter with value
+ >= 2. All the value in this tensor should be always < type_vocab_size.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
+ """
+ outputs = self.roberta(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ return_dict=True,
+ **kwargs,
+ )
+
+ sequence_output = outputs[0]
+
+ sequence_output = self.dropout(sequence_output)
+ logits = self.classifier(sequence_output)
+
+ loss = None
+ if labels is not None:
+ # move labels to correct device
+ labels = labels.to(logits.device)
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+
+ return TokenClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+class CamembertForQuestionAnswering(CamembertPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
+
+ self.roberta = CamembertModel(config, add_pooling_layer=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ start_positions: torch.LongTensor | None = None,
+ end_positions: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | QuestionAnsweringModelOutput:
+ r"""
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,1]`:
+
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token.
+ This parameter can only be used when the model is initialized with `type_vocab_size` parameter with value
+ >= 2. All the value in this tensor should be always < type_vocab_size.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ """
+ outputs = self.roberta(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ return_dict=True,
+ **kwargs,
+ )
+
+ sequence_output = outputs[0]
+
+ logits = self.qa_outputs(sequence_output)
+ start_logits, end_logits = logits.split(1, dim=-1)
+ start_logits = start_logits.squeeze(-1).contiguous()
+ end_logits = end_logits.squeeze(-1).contiguous()
+
+ total_loss = None
+ if start_positions is not None and end_positions is not None:
+ # If we are on multi-GPU, split add a dimension
+ if len(start_positions.size()) > 1:
+ start_positions = start_positions.squeeze(-1)
+ if len(end_positions.size()) > 1:
+ end_positions = end_positions.squeeze(-1)
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
+ ignored_index = start_logits.size(1)
+ start_positions = start_positions.clamp(0, ignored_index)
+ end_positions = end_positions.clamp(0, ignored_index)
+
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
+ start_loss = loss_fct(start_logits, start_positions)
+ end_loss = loss_fct(end_logits, end_positions)
+ total_loss = (start_loss + end_loss) / 2
+
+ return QuestionAnsweringModelOutput(
+ loss=total_loss,
+ start_logits=start_logits,
+ end_logits=end_logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ Camembert Model with a `language modeling` head on top for CLM fine-tuning.
+ """
+)
+class CamembertForCausalLM(CamembertPreTrainedModel, GenerationMixin):
+ _tied_weights_keys = {
+ "lm_head.decoder.weight": "roberta.embeddings.word_embeddings.weight",
+ "lm_head.decoder.bias": "lm_head.bias",
+ }
+
+ def __init__(self, config):
+ super().__init__(config)
+
+ if not config.is_decoder:
+ logger.warning("If you want to use `CamembertLMHeadModel` as a standalone, add `is_decoder=True.`")
+ self.lm_head = CamembertLMHead(config)
+
+ self.roberta = CamembertModel(config, add_pooling_layer=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_output_embeddings(self):
+ return self.lm_head.decoder
+
+ def set_output_embeddings(self, new_embeddings):
+ self.lm_head.decoder = new_embeddings
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ encoder_attention_mask: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ past_key_values: tuple[tuple[torch.FloatTensor]] | None = None,
+ use_cache: bool | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | CausalLMOutputWithCrossAttentions:
+ r"""
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,1]`:
+
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token.
+ This parameter can only be used when the model is initialized with `type_vocab_size` parameter with value
+ >= 2. All the value in this tensor should be always < type_vocab_size.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
+ `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
+ ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
+
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, CamembertForCausalLM, AutoConfig
+ >>> import torch
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("almanach/camembert-base")
+ >>> config = AutoConfig.from_pretrained("almanach/camembert-base")
+ >>> config.is_decoder = True
+ >>> model = CamembertForCausalLM.from_pretrained("almanach/camembert-base", config=config)
+
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
+ >>> outputs = model(**inputs)
+
+ >>> prediction_logits = outputs.logits
+ ```"""
+ if labels is not None:
+ use_cache = False
+
+ outputs: BaseModelOutputWithPoolingAndCrossAttentions = self.roberta(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ return_dict=True,
+ **kwargs,
+ )
+
+ hidden_states = outputs.last_hidden_state
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
+
+ return CausalLMOutputWithCrossAttentions(
+ loss=loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ cross_attentions=outputs.cross_attentions,
+ )
+
+
+__all__ = [
+ "CamembertForCausalLM",
+ "CamembertForMaskedLM",
+ "CamembertForMultipleChoice",
+ "CamembertForQuestionAnswering",
+ "CamembertForSequenceClassification",
+ "CamembertForTokenClassification",
+ "CamembertModel",
+ "CamembertPreTrainedModel",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/camembert/tokenization_camembert.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/camembert/tokenization_camembert.py
new file mode 100644
index 0000000000000000000000000000000000000000..dca65b28f73cbbf9b87a5fa13963e55cc783d375
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/camembert/tokenization_camembert.py
@@ -0,0 +1,166 @@
+# Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License
+"""Tokenization classes for Camembert model."""
+
+from tokenizers import Regex, Tokenizer, decoders, normalizers, pre_tokenizers, processors
+from tokenizers.models import Unigram
+
+from ...tokenization_python import AddedToken
+from ...tokenization_utils_tokenizers import TokenizersBackend
+from ...utils import logging
+
+
+logger = logging.get_logger(__name__)
+
+VOCAB_FILES_NAMES = {"vocab_file": "sentencepiece.bpe.model", "tokenizer_file": "tokenizer.json"}
+
+
+SPIECE_UNDERLINE = "▁"
+
+
+class CamembertTokenizer(TokenizersBackend):
+ """
+ Construct a "fast" CamemBERT tokenizer (backed by HuggingFace's *tokenizers* library). Adapted from
+ [`RobertaTokenizer`] and [`XLNetTokenizer`]. Based on
+ [Unigram](https://huggingface.co/docs/tokenizers/python/latest/components.html?highlight=unigram#models).
+
+ This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
+ refer to this superclass for more information regarding those methods.
+
+ Args:
+ bos_token (`str`, *optional*, defaults to `""`):
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
+
+
+
+ When building a sequence using special tokens, this is not the token that is used for the beginning of
+ sequence. The token used is the `cls_token`.
+
+
+
+ eos_token (`str`, *optional*, defaults to `""`):
+ The end of sequence token.
+
+
+
+ When building a sequence using special tokens, this is not the token that is used for the end of sequence.
+ The token used is the `sep_token`.
+
+
+
+ sep_token (`str`, *optional*, defaults to `""`):
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
+ sequence classification or for a text and a question for question answering. It is also used as the last
+ token of a sequence built with special tokens.
+ cls_token (`str`, *optional*, defaults to `""`):
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
+ unk_token (`str`, *optional*, defaults to `""`):
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
+ token instead.
+ pad_token (`str`, *optional*, defaults to `""`):
+ The token used for padding, for example when batching sequences of different lengths.
+ mask_token (`str`, *optional*, defaults to `""`):
+ The token used for masking values. This is the token used when training this model with masked language
+ modeling. This is the token which the model will try to predict.
+ additional_special_tokens (`list[str]`, *optional*, defaults to `["NOTUSED", "NOTUSED"]`):
+ Additional special tokens used by the tokenizer.
+ add_prefix_space (`bool`, *optional*, defaults to `True`):
+ Whether or not to add an initial space to the input. This allows to treat the leading word just as any
+ other word.
+ vocab_file (`str`, *optional*):
+ [SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
+ contains the vocabulary necessary to instantiate a tokenizer.
+ vocab (`str`, `dict` or `list`, *optional*):
+ Custom vocabulary dictionary. If not provided, vocabulary is loaded from vocab_file.
+ """
+
+ vocab_files_names = VOCAB_FILES_NAMES
+ model_input_names = ["input_ids", "attention_mask"]
+ slow_tokenizer_class = None
+
+ def __init__(
+ self,
+ bos_token="",
+ eos_token="",
+ sep_token="",
+ cls_token="",
+ unk_token="",
+ pad_token="",
+ mask_token="",
+ additional_special_tokens=None,
+ add_prefix_space=True,
+ vocab_file=None,
+ vocab: str | dict | list | None = None,
+ **kwargs,
+ ):
+ self.vocab_file = vocab_file
+ self.add_prefix_space = add_prefix_space
+
+ mask_token = AddedToken(mask_token, lstrip=True, special=True) if isinstance(mask_token, str) else mask_token
+
+ if additional_special_tokens is None:
+ additional_special_tokens = ["NOTUSED", "NOTUSED", "NOTUSED"]
+
+ if vocab is not None:
+ self._vocab = vocab
+ unk_index = next((i for i, (tok, _) in enumerate(self._vocab) if tok == str(unk_token)), 0)
+ self._tokenizer = Tokenizer(Unigram(self._vocab, unk_id=unk_index, byte_fallback=False))
+ else:
+ self._vocab = [
+ ("NOTUSED", 0.0),
+ (str(pad_token), 0.0),
+ ("NOTUSED", 0.0),
+ (str(unk_token), 0.0),
+ ("NOTUSED", -100),
+ (str(mask_token), 0.0),
+ ]
+ self._tokenizer = Tokenizer(Unigram(self._vocab, unk_id=3, byte_fallback=False))
+
+ self._tokenizer.normalizer = normalizers.Sequence(
+ [
+ normalizers.Replace(Regex(r"\s{2,}|[\n\r\t]"), " "),
+ normalizers.Strip(left=False, right=True),
+ ]
+ )
+
+ prepend_scheme = "always" if add_prefix_space else "never"
+ self._tokenizer.pre_tokenizer = pre_tokenizers.Metaspace(replacement="▁", prepend_scheme=prepend_scheme)
+ self._tokenizer.decoder = decoders.Metaspace(replacement="▁", prepend_scheme=prepend_scheme)
+
+ super().__init__(
+ bos_token=bos_token,
+ eos_token=eos_token,
+ sep_token=sep_token,
+ cls_token=cls_token,
+ unk_token=unk_token,
+ pad_token=pad_token,
+ mask_token=mask_token,
+ additional_special_tokens=additional_special_tokens,
+ add_prefix_space=add_prefix_space,
+ **kwargs,
+ )
+
+ # always adds BOS/EOS with " " separator for pairs
+ self._tokenizer.post_processor = processors.TemplateProcessing(
+ single=f"{self.bos_token} $A {self.eos_token}",
+ pair=f"{self.bos_token} $A {self.eos_token} {self.eos_token} $B {self.eos_token}",
+ special_tokens=[
+ (self.bos_token, self.bos_token_id),
+ (self.eos_token, self.eos_token_id),
+ ],
+ )
+
+
+__all__ = ["CamembertTokenizer"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/code_llama/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/code_llama/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9373edc1b0e72e927d5fb4486afccbf34c361dc1
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/code_llama/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/code_llama/__pycache__/tokenization_code_llama.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/code_llama/__pycache__/tokenization_code_llama.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0db002efceec25443c8599466f4a224e5d13c916
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/code_llama/__pycache__/tokenization_code_llama.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cohere2/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cohere2/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..081deb9bfc52da3deb2f7749fe0817c8acaa2b56
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cohere2/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cohere2/__pycache__/configuration_cohere2.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cohere2/__pycache__/configuration_cohere2.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c66afdab6bff24f1cb874c12662749fd58e28c7a
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cohere2/__pycache__/configuration_cohere2.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cohere2/__pycache__/modeling_cohere2.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cohere2/__pycache__/modeling_cohere2.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b57cd2a20dd6564744d1f8be80751a2a7926278b
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cohere2/__pycache__/modeling_cohere2.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cohere2/__pycache__/modular_cohere2.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cohere2/__pycache__/modular_cohere2.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..33c67bfad58d38b417c199ac9c59a0bdacc94a72
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cohere2/__pycache__/modular_cohere2.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cohere2_vision/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cohere2_vision/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5316051e62940193fe0dc6995c5cecaaad5425af
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cohere2_vision/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cohere2_vision/__pycache__/configuration_cohere2_vision.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cohere2_vision/__pycache__/configuration_cohere2_vision.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6980896e7dd7aa0079be678f4ff07a044552a9fc
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cohere2_vision/__pycache__/configuration_cohere2_vision.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cohere2_vision/__pycache__/image_processing_cohere2_vision.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cohere2_vision/__pycache__/image_processing_cohere2_vision.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4d6361e1a7ebb6cbc3d196fb4b81ecaa6492d0eb
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cohere2_vision/__pycache__/image_processing_cohere2_vision.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cohere2_vision/__pycache__/modeling_cohere2_vision.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cohere2_vision/__pycache__/modeling_cohere2_vision.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b92a09d72d5f8b34605dffdc23002c855ca3f362
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cohere2_vision/__pycache__/modeling_cohere2_vision.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cohere2_vision/__pycache__/modular_cohere2_vision.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cohere2_vision/__pycache__/modular_cohere2_vision.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fa5d3e2dcaab347bea934c9dcb59a82d224ce0c9
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cohere2_vision/__pycache__/modular_cohere2_vision.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cohere2_vision/__pycache__/processing_cohere2_vision.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cohere2_vision/__pycache__/processing_cohere2_vision.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0a8e02b3b70dd72d534386dd8093452ff07a0677
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cohere2_vision/__pycache__/processing_cohere2_vision.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/colmodernvbert/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/colmodernvbert/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..65976110a9527cd6bd33c86a5b405dc07d101c65
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/colmodernvbert/__init__.py
@@ -0,0 +1,28 @@
+# Copyright 2026 Illuin Technology and contributors, and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_colmodernvbert import *
+ from .modeling_colmodernvbert import *
+ from .processing_colmodernvbert import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/colmodernvbert/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/colmodernvbert/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b85740c17ffe26ad1d2c2da1d40f1c52124ddeb9
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/colmodernvbert/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/colmodernvbert/__pycache__/configuration_colmodernvbert.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/colmodernvbert/__pycache__/configuration_colmodernvbert.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..65b5db764d909670bf0c0711690b48a4fe3c2548
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/colmodernvbert/__pycache__/configuration_colmodernvbert.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/colmodernvbert/__pycache__/modeling_colmodernvbert.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/colmodernvbert/__pycache__/modeling_colmodernvbert.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..429c5decdbdf5398e3fb956c1985a849b3866b62
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/colmodernvbert/__pycache__/modeling_colmodernvbert.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/colmodernvbert/__pycache__/modular_colmodernvbert.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/colmodernvbert/__pycache__/modular_colmodernvbert.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5784afb8e7479c4805eba3286f5398e08886487d
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/colmodernvbert/__pycache__/modular_colmodernvbert.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/colmodernvbert/__pycache__/processing_colmodernvbert.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/colmodernvbert/__pycache__/processing_colmodernvbert.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e5fb3d2314f5171ee99cf9249f0ad4d8687d72bf
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/colmodernvbert/__pycache__/processing_colmodernvbert.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/colmodernvbert/configuration_colmodernvbert.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/colmodernvbert/configuration_colmodernvbert.py
new file mode 100644
index 0000000000000000000000000000000000000000..efa57dfc8640e1d1d54934d5823c37f8c9ecbfc9
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/colmodernvbert/configuration_colmodernvbert.py
@@ -0,0 +1,81 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/colmodernvbert/modular_colmodernvbert.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_colmodernvbert.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2026 Illuin Technology and contributors, and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring, logging
+from ..auto import CONFIG_MAPPING
+
+
+logger = logging.get_logger(__name__)
+
+
+@auto_docstring(checkpoint="ModernVBERT/colmodernvbert-merged")
+@strict
+class ColModernVBertConfig(PreTrainedConfig):
+ r"""
+ Example:
+
+ ```python
+ from transformers import ColModernVBertConfig, ColModernVBertForRetrieval
+
+ config = ColModernVBertConfig()
+ model = ColModernVBertForRetrieval(config)
+ ```
+ """
+
+ model_type = "colmodernvbert"
+ sub_configs = {"vlm_config": PreTrainedConfig}
+
+ vlm_config: dict | PreTrainedConfig | None = None
+ embedding_dim: int = 128
+ initializer_range: float = 0.02
+
+ def __post_init__(self, **kwargs):
+ if self.vlm_config is None:
+ self.vlm_config = CONFIG_MAPPING["modernvbert"]()
+ logger.info(
+ "`vlm_config` is `None`. Initializing `vlm_config` with the `ModernVBertConfig` with default values."
+ )
+ elif isinstance(self.vlm_config, dict):
+ self.vlm_config = CONFIG_MAPPING[self.vlm_config["model_type"]](**self.vlm_config)
+
+ if not hasattr(self.vlm_config, "vocab_size"):
+ self.vlm_config.vocab_size = self.vlm_config.get_text_config().vocab_size
+ if self.vlm_config is None:
+ self.vlm_config = CONFIG_MAPPING["qwen2_vl"]()
+ logger.info(
+ "`vlm_config` is `None`. Initializing `vlm_config` with the `Qwen2VLConfig` with default values."
+ )
+ elif isinstance(self.vlm_config, dict):
+ self.vlm_config = CONFIG_MAPPING[self.vlm_config["model_type"]](**self.vlm_config)
+
+ if not hasattr(self.vlm_config, "vocab_size"):
+ self.vlm_config.vocab_size = self.vlm_config.get_text_config().vocab_size
+
+ super().__post_init__(**kwargs)
+
+ def get_text_config(self, *args, **kwargs) -> PreTrainedConfig:
+ return self.vlm_config.get_text_config(*args, **kwargs)
+
+
+__all__ = ["ColModernVBertConfig"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/colmodernvbert/modeling_colmodernvbert.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/colmodernvbert/modeling_colmodernvbert.py
new file mode 100644
index 0000000000000000000000000000000000000000..754ffed137df83f701ab3aaf4479c582e940611a
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/colmodernvbert/modeling_colmodernvbert.py
@@ -0,0 +1,158 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/colmodernvbert/modular_colmodernvbert.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_colmodernvbert.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2026 Illuin Technology and contributors, and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from dataclasses import dataclass
+
+import torch
+from torch import nn
+
+from ... import initialization as init
+from ...modeling_utils import PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import ModelOutput, TransformersKwargs, auto_docstring
+from ...utils.generic import can_return_tuple
+from ..auto.modeling_auto import AutoModel
+from .configuration_colmodernvbert import ColModernVBertConfig
+
+
+@auto_docstring
+class ColModernVBertPreTrainedModel(PreTrainedModel):
+ config: ColModernVBertConfig
+ base_model_prefix = "model"
+ input_modalities = ("image", "text")
+ _no_split_modules = []
+ _supports_sdpa = True
+ _supports_flash_attn = True
+ _supports_flex_attn = True
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ std = (
+ self.config.initializer_range
+ if hasattr(self.config, "initializer_range")
+ else self.config.vlm_config.text_config.initializer_range
+ )
+
+ if isinstance(module, (nn.Linear, nn.Conv2d)):
+ init.normal_(module.weight, mean=0.0, std=std)
+ if module.bias is not None:
+ init.zeros_(module.bias)
+ elif isinstance(module, nn.Embedding):
+ init.normal_(module.weight, mean=0.0, std=std)
+ # Here we need the check explicitly, as we slice the weight in the `zeros_` call, so it looses the flag
+ if module.padding_idx is not None and not getattr(module.weight, "_is_hf_initialized", False):
+ init.zeros_(module.weight[module.padding_idx])
+
+
+@auto_docstring(
+ custom_intro="""
+ Base class for ColModernVBert embeddings output.
+ """
+)
+@dataclass
+class ColModernVBertForRetrievalOutput(ModelOutput):
+ r"""
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
+ Language modeling loss (for next-token prediction).
+ embeddings (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
+ The embeddings of the model.
+ image_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True` and `pixel_values` are provided):
+ Tuple of `torch.FloatTensor` (one for the output of the image modality projection + one for the output of each layer) of shape
+ `(batch_size, num_channels, image_size, image_size)`.
+ Hidden-states of the image encoder at the output of each layer plus the initial modality projection outputs.
+ """
+
+ loss: torch.FloatTensor | None = None
+ embeddings: torch.Tensor | None = None
+ hidden_states: tuple[torch.FloatTensor] | None = None
+ image_hidden_states: tuple[torch.FloatTensor] | None = None
+ attentions: tuple[torch.FloatTensor] | None = None
+
+
+@auto_docstring(
+ custom_intro="""
+ Following the ColPali approach, ColModernVBert leverages VLMs to construct efficient multi-vector embeddings directly
+ from document images (“screenshots”) for document retrieval. The model is trained to maximize the similarity
+ between these document embeddings and the corresponding query embeddings, using the late interaction method
+ introduced in ColBERT.
+
+ Using ColModernVBert removes the need for potentially complex and brittle layout recognition and OCR pipelines with
+ a single model that can take into account both the textual and visual content (layout, charts, ...) of a document.
+
+ ColModernVBert is trained on top of ModernVBert, and was introduced in the following paper:
+ [*ModernVBERT: Towards Smaller Visual Document Retrievers*](https://arxiv.org/abs/2510.01149).
+
+ ColModernVBert is part of the ColVision model family, which was introduced with ColPali in the following paper:
+ [*ColPali: Efficient Document Retrieval with Vision Language Models*](https://huggingface.co/papers/2407.01449).
+ """
+)
+class ColModernVBertForRetrieval(ColModernVBertPreTrainedModel):
+ base_model_prefix = "vlm"
+
+ def __init__(self, config: ColModernVBertConfig):
+ super().__init__(config)
+ self.config = config
+ self.vocab_size = config.vlm_config.text_config.vocab_size
+ self.vlm = AutoModel.from_config(config.vlm_config)
+
+ self.embedding_dim = self.config.embedding_dim
+ self.embedding_proj_layer = nn.Linear(
+ self.config.vlm_config.text_config.hidden_size,
+ self.embedding_dim,
+ )
+
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ pixel_values: torch.FloatTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> ColModernVBertForRetrievalOutput:
+ vlm_output = self.vlm(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ pixel_values=pixel_values,
+ **kwargs,
+ )
+
+ last_hidden_states = vlm_output[0] # (batch_size, sequence_length, hidden_size)
+ proj_dtype = self.embedding_proj_layer.weight.dtype
+ embeddings = self.embedding_proj_layer(last_hidden_states.to(proj_dtype)) # (batch_size, sequence_length, dim)
+
+ # L2 normalization
+ embeddings = embeddings / embeddings.norm(dim=-1, keepdim=True) # (batch_size, sequence_length, dim)
+
+ if attention_mask is not None:
+ attention_mask = attention_mask.to(dtype=embeddings.dtype, device=embeddings.device)
+ embeddings = embeddings * attention_mask.unsqueeze(-1) # (batch_size, sequence_length, dim)
+
+ return ColModernVBertForRetrievalOutput(
+ embeddings=embeddings,
+ hidden_states=vlm_output.hidden_states,
+ attentions=vlm_output.attentions,
+ image_hidden_states=vlm_output.image_hidden_states,
+ )
+
+
+__all__ = ["ColModernVBertForRetrieval", "ColModernVBertPreTrainedModel"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/colmodernvbert/modular_colmodernvbert.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/colmodernvbert/modular_colmodernvbert.py
new file mode 100644
index 0000000000000000000000000000000000000000..0729a9ca7d704c96329c71678b86d087a539205c
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/colmodernvbert/modular_colmodernvbert.py
@@ -0,0 +1,422 @@
+# Copyright 2026 Illuin Technology and contributors, and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from dataclasses import dataclass
+from typing import Optional, Union
+
+import torch
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...feature_extraction_utils import BatchFeature
+from ...image_utils import ImageInput, is_valid_image
+from ...processing_utils import Unpack
+from ...tokenization_utils_base import TextInput
+from ...utils import ModelOutput, TransformersKwargs, auto_docstring, logging
+from ...utils.generic import can_return_tuple
+from ...utils.import_utils import requires
+from ..auto import CONFIG_MAPPING
+from ..auto.modeling_auto import AutoModel
+from ..colpali.modeling_colpali import ColPaliForRetrieval, ColPaliPreTrainedModel
+from ..colqwen2.configuration_colqwen2 import ColQwen2Config
+from ..idefics3.processing_idefics3 import Idefics3Processor, Idefics3ProcessorKwargs
+
+
+logger = logging.get_logger(__name__)
+
+
+@auto_docstring(checkpoint="ModernVBERT/colmodernvbert-merged")
+@strict
+class ColModernVBertConfig(ColQwen2Config):
+ r"""
+ Example:
+
+ ```python
+ from transformers import ColModernVBertConfig, ColModernVBertForRetrieval
+
+ config = ColModernVBertConfig()
+ model = ColModernVBertForRetrieval(config)
+ ```
+ """
+
+ model_type = "colmodernvbert"
+ sub_configs = {"vlm_config": PreTrainedConfig}
+
+ vlm_config: dict | PreTrainedConfig | None = None
+ embedding_dim: int = 128
+ initializer_range: float = 0.02
+
+ def __post_init__(self, **kwargs):
+ if self.vlm_config is None:
+ self.vlm_config = CONFIG_MAPPING["modernvbert"]()
+ logger.info(
+ "`vlm_config` is `None`. Initializing `vlm_config` with the `ModernVBertConfig` with default values."
+ )
+ elif isinstance(self.vlm_config, dict):
+ self.vlm_config = CONFIG_MAPPING[self.vlm_config["model_type"]](**self.vlm_config)
+
+ if not hasattr(self.vlm_config, "vocab_size"):
+ self.vlm_config.vocab_size = self.vlm_config.get_text_config().vocab_size
+
+ super().__post_init__(**kwargs)
+
+
+class ColModernVBertProcessorKwargs(Idefics3ProcessorKwargs, total=False):
+ _defaults = {
+ "text_kwargs": {
+ "padding": "longest",
+ },
+ "images_kwargs": {
+ "return_row_col_info": True,
+ "data_format": "channels_first",
+ "do_convert_rgb": True,
+ },
+ "common_kwargs": {"return_tensors": "pt"},
+ }
+
+
+@requires(backends=("torch",))
+@auto_docstring
+class ColModernVBertProcessor(Idefics3Processor):
+ r"""
+ Constructs a ColModernVBert processor which wraps a ModernVBertProcessor and special methods to process images and queries, as
+ well as to compute the late-interaction retrieval score.
+
+ [`ColModernVBertProcessor`] offers all the functionalities of [`ModernVBertProcessor`]. See the [`~ModernVBertProcessor.__call__`]
+ for more information.
+
+ Args:
+ image_processor ([`Idefics3ImageProcessor`]): An instance of [`Idefics3ImageProcessor`]. The image processor is a required input.
+ tokenizer (`PreTrainedTokenizerFast`, *optional*): An instance of [`PreTrainedTokenizerFast`]. This should correspond with the model's text model. The tokenizer is a required input.
+ image_seq_len (`int`, *optional*, defaults to 64): The length of the image sequence i.e. the number of tokens per image in the input.
+ visual_prompt_prefix (`Optional`, *optional*): A prefix to be prepended to visual prompts.
+ query_prefix (`Optional`, *optional*): A prefix to be prepended to query prompts.
+ """
+
+ def __init__(
+ self,
+ image_processor,
+ tokenizer=None,
+ chat_template=None,
+ image_seq_len: int = 64,
+ visual_prompt_prefix: str | None = None,
+ query_prefix: str | None = None,
+ **kwargs,
+ ):
+ r"""
+ image_seq_len (`int`, *optional*, defaults to 64):
+ The length of the image sequence i.e. the number of tokens per image in the input.
+ visual_prompt_prefix (`str`, *optional*):
+ A string that gets tokenized and prepended to the image tokens.
+ query_prefix (`str`, *optional*):
+ A prefix to be used for the query.
+ """
+ chat_template = None # ColModernVBert does not use chat templates
+
+ super().__init__(
+ image_processor,
+ tokenizer,
+ chat_template=chat_template,
+ image_seq_len=image_seq_len,
+ **kwargs,
+ )
+
+ self.visual_prompt_prefix = visual_prompt_prefix or (
+ f"<|begin_of_text|>User:{self.image_token}Describe the image.\nAssistant:"
+ )
+ self.query_prefix = query_prefix or ""
+ self.query_augmentation_token = self.end_of_utterance_token
+
+ def process_images(
+ self,
+ images: ImageInput | None = None,
+ **kwargs: Unpack[ColModernVBertProcessorKwargs],
+ ) -> BatchFeature:
+ """
+ Prepare for the model one or several image(s). Handles input validation, RGB conversion,
+ and prepends the `visual_prompt_prefix` to each image. Optionally computes labels from
+ `token_type_ids` when a `suffix` is provided in `text_kwargs`.
+
+ Args:
+ images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `list[PIL.Image.Image]`, `list[np.ndarray]`, `list[torch.Tensor]`):
+ The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
+ tensor. In case of a NumPy array/PyTorch tensor, each image should be of shape (C, H, W), where C is a
+ number of channels, H and W are image height and width.
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
+ If set, will return tensors of a particular framework. Acceptable values are:
+
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
+ - `'np'`: Return NumPy `np.ndarray` objects.
+
+ Returns:
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
+
+ - **input_ids** -- List of token ids to be fed to a model.
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
+ `None`).
+ - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
+ """
+ output_kwargs = self._merge_kwargs(
+ ColModernVBertProcessorKwargs,
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
+ **kwargs,
+ )
+
+ suffix = output_kwargs["text_kwargs"].pop("suffix", None)
+
+ return_token_type_ids = suffix is not None
+
+ # Normalize input to a flat list of images
+ if is_valid_image(images):
+ images = [images]
+ elif isinstance(images, list) and is_valid_image(images[0]):
+ pass
+ elif not (isinstance(images, list) and isinstance(images[0], list) and is_valid_image(images[0][0])):
+ raise ValueError("images must be an image, list of images or list of list of images")
+
+ # Ensure all images are in RGB format
+ images = [image.convert("RGB") for image in images]
+
+ # Pair each image with the visual prompt prefix for the VLM backbone
+ batch_doc = self.__call__(
+ text=[self.visual_prompt_prefix] * len(images),
+ images=images,
+ images_kwargs=output_kwargs["images_kwargs"],
+ text_kwargs=output_kwargs["text_kwargs"],
+ )
+
+ # When suffix is provided, generate labels by masking non-suffix tokens
+ if return_token_type_ids:
+ labels = batch_doc["input_ids"].masked_fill(batch_doc["token_type_ids"] == 0, -100)
+ batch_doc.update({"labels": labels})
+
+ return batch_doc
+
+ def process_queries(
+ self,
+ text: TextInput | list[TextInput],
+ **kwargs: Unpack[ColModernVBertProcessorKwargs],
+ ) -> BatchFeature:
+ """
+ Prepare for the model one or several text queries. Handles input validation, prepends the
+ `query_prefix`, and appends query augmentation tokens (used to pad query embeddings for
+ better late-interaction retrieval performance).
+
+ Args:
+ text (`str`, `list[str]`, `list[list[str]]`):
+ The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
+ (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
+ `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
+ If set, will return tensors of a particular framework. Acceptable values are:
+
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
+ - `'np'`: Return NumPy `np.ndarray` objects.
+
+ Returns:
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
+
+ - **input_ids** -- List of token ids to be fed to a model.
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
+ `None`).
+ """
+ output_kwargs = self._merge_kwargs(
+ ColModernVBertProcessorKwargs,
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
+ **kwargs,
+ )
+
+ suffix = output_kwargs["text_kwargs"].pop("suffix", None)
+
+ if isinstance(text, str):
+ text = [text]
+ elif not (isinstance(text, list) and isinstance(text[0], str)):
+ raise ValueError("Text must be a string or a list of strings")
+
+ # Default suffix: repeat the augmentation token to pad query embeddings
+ if suffix is None:
+ suffix = self.query_augmentation_token * 10
+
+ # Build final queries: prefix + original query + augmentation suffix
+ texts_query: list[str] = [self.query_prefix + query + suffix for query in text]
+
+ batch_query = self.__call__(
+ text=texts_query,
+ return_token_type_ids=False,
+ text_kwargs=output_kwargs["text_kwargs"],
+ )
+
+ return batch_query
+
+ def score_retrieval(
+ self,
+ query_embeddings: Union["torch.Tensor", list["torch.Tensor"]],
+ passage_embeddings: Union["torch.Tensor", list["torch.Tensor"]],
+ batch_size: int = 128,
+ output_dtype: Optional["torch.dtype"] = None,
+ output_device: Union["torch.device", str] = "cpu",
+ ) -> "torch.Tensor":
+ """
+ Compute the late-interaction/MaxSim score (ColBERT-like) for the given multi-vector
+ query embeddings (`qs`) and passage embeddings (`ps`). For ColQwen2, a passage is the
+ image of a document page.
+
+ Because the embedding tensors are multi-vector and can thus have different shapes, they
+ should be fed as:
+ (1) a list of tensors, where the i-th tensor is of shape (sequence_length_i, embedding_dim)
+ (2) a single tensor of shape (n_passages, max_sequence_length, embedding_dim) -> usually
+ obtained by padding the list of tensors.
+
+ Args:
+ query_embeddings (`Union[torch.Tensor, list[torch.Tensor]`): Query embeddings.
+ passage_embeddings (`Union[torch.Tensor, list[torch.Tensor]`): Passage embeddings.
+ batch_size (`int`, *optional*, defaults to 128): Batch size for computing scores.
+ output_dtype (`torch.dtype`, *optional*, defaults to `torch.float32`): The dtype of the output tensor.
+ If `None`, the dtype of the input embeddings is used.
+ output_device (`torch.device` or `str`, *optional*, defaults to "cpu"): The device of the output tensor.
+
+ Returns:
+ `torch.Tensor`: A tensor of shape `(n_queries, n_passages)` containing the scores. The score
+ tensor is saved on the "cpu" device.
+ """
+
+ if len(query_embeddings) == 0:
+ raise ValueError("No queries provided")
+ if len(passage_embeddings) == 0:
+ raise ValueError("No passages provided")
+
+ if query_embeddings[0].device != passage_embeddings[0].device:
+ raise ValueError("Queries and passages must be on the same device")
+
+ if query_embeddings[0].dtype != passage_embeddings[0].dtype:
+ raise ValueError("Queries and passages must have the same dtype")
+
+ if output_dtype is None:
+ output_dtype = query_embeddings[0].dtype
+
+ scores: list[torch.Tensor] = []
+
+ for i in range(0, len(query_embeddings), batch_size):
+ batch_scores: list[torch.Tensor] = []
+ batch_queries = torch.nn.utils.rnn.pad_sequence(
+ query_embeddings[i : i + batch_size], batch_first=True, padding_value=0
+ )
+ for j in range(0, len(passage_embeddings), batch_size):
+ batch_passages = torch.nn.utils.rnn.pad_sequence(
+ passage_embeddings[j : j + batch_size], batch_first=True, padding_value=0
+ )
+ batch_scores.append(
+ torch.einsum("bnd,csd->bcns", batch_queries, batch_passages).max(dim=3)[0].sum(dim=2)
+ )
+ scores.append(torch.cat(batch_scores, dim=1).to(output_dtype).to(output_device))
+
+ return torch.cat(scores, dim=0)
+
+
+@auto_docstring
+class ColModernVBertPreTrainedModel(ColPaliPreTrainedModel):
+ config: ColModernVBertConfig
+
+
+@auto_docstring(
+ custom_intro="""
+ Base class for ColModernVBert embeddings output.
+ """
+)
+@dataclass
+class ColModernVBertForRetrievalOutput(ModelOutput):
+ r"""
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
+ Language modeling loss (for next-token prediction).
+ embeddings (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
+ The embeddings of the model.
+ image_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True` and `pixel_values` are provided):
+ Tuple of `torch.FloatTensor` (one for the output of the image modality projection + one for the output of each layer) of shape
+ `(batch_size, num_channels, image_size, image_size)`.
+ Hidden-states of the image encoder at the output of each layer plus the initial modality projection outputs.
+ """
+
+ loss: torch.FloatTensor | None = None
+ embeddings: torch.Tensor | None = None
+ hidden_states: tuple[torch.FloatTensor] | None = None
+ image_hidden_states: tuple[torch.FloatTensor] | None = None
+ attentions: tuple[torch.FloatTensor] | None = None
+
+
+@auto_docstring(
+ custom_intro="""
+ Following the ColPali approach, ColModernVBert leverages VLMs to construct efficient multi-vector embeddings directly
+ from document images (“screenshots”) for document retrieval. The model is trained to maximize the similarity
+ between these document embeddings and the corresponding query embeddings, using the late interaction method
+ introduced in ColBERT.
+
+ Using ColModernVBert removes the need for potentially complex and brittle layout recognition and OCR pipelines with
+ a single model that can take into account both the textual and visual content (layout, charts, ...) of a document.
+
+ ColModernVBert is trained on top of ModernVBert, and was introduced in the following paper:
+ [*ModernVBERT: Towards Smaller Visual Document Retrievers*](https://arxiv.org/abs/2510.01149).
+
+ ColModernVBert is part of the ColVision model family, which was introduced with ColPali in the following paper:
+ [*ColPali: Efficient Document Retrieval with Vision Language Models*](https://huggingface.co/papers/2407.01449).
+ """
+)
+class ColModernVBertForRetrieval(ColPaliForRetrieval):
+ def __init__(self, config: ColModernVBertConfig):
+ super().__init__(config)
+ self.vlm = AutoModel.from_config(config.vlm_config)
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ pixel_values: torch.FloatTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> ColModernVBertForRetrievalOutput:
+ vlm_output = self.vlm(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ pixel_values=pixel_values,
+ **kwargs,
+ )
+
+ last_hidden_states = vlm_output[0] # (batch_size, sequence_length, hidden_size)
+ proj_dtype = self.embedding_proj_layer.weight.dtype
+ embeddings = self.embedding_proj_layer(last_hidden_states.to(proj_dtype)) # (batch_size, sequence_length, dim)
+
+ # L2 normalization
+ embeddings = embeddings / embeddings.norm(dim=-1, keepdim=True) # (batch_size, sequence_length, dim)
+
+ if attention_mask is not None:
+ attention_mask = attention_mask.to(dtype=embeddings.dtype, device=embeddings.device)
+ embeddings = embeddings * attention_mask.unsqueeze(-1) # (batch_size, sequence_length, dim)
+
+ return ColModernVBertForRetrievalOutput(
+ embeddings=embeddings,
+ hidden_states=vlm_output.hidden_states,
+ attentions=vlm_output.attentions,
+ image_hidden_states=vlm_output.image_hidden_states,
+ )
+
+
+__all__ = [
+ "ColModernVBertConfig",
+ "ColModernVBertForRetrieval",
+ "ColModernVBertPreTrainedModel",
+ "ColModernVBertProcessor",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/colmodernvbert/processing_colmodernvbert.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/colmodernvbert/processing_colmodernvbert.py
new file mode 100644
index 0000000000000000000000000000000000000000..de9a8120568227471a2fd24f49dc5b119bbc97ae
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/colmodernvbert/processing_colmodernvbert.py
@@ -0,0 +1,566 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/colmodernvbert/modular_colmodernvbert.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_colmodernvbert.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2026 Illuin Technology and contributors, and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import re
+from itertools import accumulate
+from typing import TYPE_CHECKING, Optional, Union
+
+import numpy as np
+import torch
+
+from ...feature_extraction_utils import BatchFeature
+from ...image_utils import ImageInput, is_valid_image, load_image
+from ...processing_utils import MultiModalData, ProcessingKwargs, ProcessorMixin, Unpack
+from ...tokenization_utils_base import AddedToken, BatchEncoding, TextInput
+from ...utils import auto_docstring
+from ...utils.import_utils import requires
+
+
+if TYPE_CHECKING:
+ from ...tokenization_utils_base import PreTokenizedInput
+
+
+class ColModernVBertProcessorKwargs(ProcessingKwargs, total=False):
+ _defaults = {
+ "text_kwargs": {
+ "padding": "longest",
+ },
+ "images_kwargs": {
+ "return_row_col_info": True,
+ "data_format": "channels_first",
+ "do_convert_rgb": True,
+ },
+ "common_kwargs": {"return_tensors": "pt"},
+ }
+
+
+def is_url(val) -> bool:
+ return isinstance(val, str) and val.startswith("http")
+
+
+def is_image_or_image_url(elem):
+ return is_url(elem) or is_valid_image(elem)
+
+
+def _prompt_split_image(image_seq_len, image_rows, image_cols, fake_token_around_image, image_token, global_img_token):
+ """Prompt with expanded image tokens for when the image is split into patches."""
+ text_split_images = ""
+ for n_h in range(image_rows):
+ for n_w in range(image_cols):
+ text_split_images += (
+ f"{fake_token_around_image}" + f"" + f"{image_token}" * image_seq_len
+ )
+ text_split_images += "\n"
+
+ text_split_images += (
+ f"\n{fake_token_around_image}"
+ + f"{global_img_token}"
+ + f"{image_token}" * image_seq_len
+ + f"{fake_token_around_image}"
+ )
+ return text_split_images
+
+
+def _prompt_single_image(image_seq_len, fake_token_around_image, image_token, global_img_token):
+ """Prompt with expanded image tokens for a single image."""
+ return (
+ f"{fake_token_around_image}"
+ + f"{global_img_token}"
+ + f"{image_token}" * image_seq_len
+ + f"{fake_token_around_image}"
+ )
+
+
+def get_image_prompt_string(
+ image_rows, image_cols, image_seq_len, fake_token_around_image, image_token, global_img_token
+):
+ if image_rows == 0 and image_cols == 0:
+ return _prompt_single_image(
+ image_seq_len,
+ fake_token_around_image=fake_token_around_image,
+ image_token=image_token,
+ global_img_token=global_img_token,
+ )
+ return _prompt_split_image(
+ image_seq_len, image_rows, image_cols, fake_token_around_image, image_token, global_img_token
+ )
+
+
+@requires(backends=("torch",))
+@auto_docstring
+class ColModernVBertProcessor(ProcessorMixin):
+ r"""
+ Constructs a ColModernVBert processor which wraps a ModernVBertProcessor and special methods to process images and queries, as
+ well as to compute the late-interaction retrieval score.
+
+ [`ColModernVBertProcessor`] offers all the functionalities of [`ModernVBertProcessor`]. See the [`~ModernVBertProcessor.__call__`]
+ for more information.
+
+ Args:
+ image_processor ([`Idefics3ImageProcessor`]): An instance of [`Idefics3ImageProcessor`]. The image processor is a required input.
+ tokenizer (`PreTrainedTokenizerFast`, *optional*): An instance of [`PreTrainedTokenizerFast`]. This should correspond with the model's text model. The tokenizer is a required input.
+ image_seq_len (`int`, *optional*, defaults to 64): The length of the image sequence i.e. the number of tokens per image in the input.
+ visual_prompt_prefix (`Optional`, *optional*): A prefix to be prepended to visual prompts.
+ query_prefix (`Optional`, *optional*): A prefix to be prepended to query prompts.
+ """
+
+ def __init__(
+ self,
+ image_processor,
+ tokenizer=None,
+ chat_template=None,
+ image_seq_len: int = 64,
+ visual_prompt_prefix: str | None = None,
+ query_prefix: str | None = None,
+ **kwargs,
+ ):
+ r"""
+ image_seq_len (`int`, *optional*, defaults to 64):
+ The length of the image sequence i.e. the number of tokens per image in the input.
+ visual_prompt_prefix (`str`, *optional*):
+ A string that gets tokenized and prepended to the image tokens.
+ query_prefix (`str`, *optional*):
+ A prefix to be used for the query.
+ """
+ chat_template = None # ColModernVBert does not use chat templates
+ self.fake_image_token = AddedToken("", normalized=False, special=True).content
+ self.image_token = AddedToken("", normalized=False, special=True).content
+ self.end_of_utterance_token = AddedToken("", normalized=False, special=True).content
+ self.global_image_tag = "" # https://github.com/huggingface/transformers/pull/32473/files/8063e5e17362571b693f1db95167f5443a3be1b2#r1734825341
+ self.image_seq_len = image_seq_len
+ self.image_token_id = tokenizer.convert_tokens_to_ids(self.image_token)
+ self.fake_image_token_id = tokenizer.convert_tokens_to_ids(self.fake_image_token)
+ self.global_image_token_id = tokenizer.convert_tokens_to_ids(self.global_image_tag)
+ self.row_col_ids = [
+ tokenizer.convert_tokens_to_ids(f"") for i in range(6) for j in range(6)
+ ]
+
+ # This regex matches one or more occurrences of tags (optionally surrounded by newline characters)
+ # or tags (where x and y are digits, also optionally surrounded by newline characters).
+ self._regex_to_remove_extra_special_tokens = re.compile(r"(\n?\n?|\n?)+")
+
+ tokens_to_add = {
+ "additional_special_tokens": [
+ self.fake_image_token,
+ self.image_token,
+ self.end_of_utterance_token,
+ ]
+ }
+ tokenizer.add_special_tokens(tokens_to_add)
+ self.image_token_id = tokenizer.convert_tokens_to_ids(self.image_token)
+
+ super().__init__(image_processor, tokenizer, chat_template=chat_template, **kwargs)
+
+ self.visual_prompt_prefix = visual_prompt_prefix or (
+ f"<|begin_of_text|>User:{self.image_token}Describe the image.\nAssistant:"
+ )
+ self.query_prefix = query_prefix or ""
+ self.query_augmentation_token = self.end_of_utterance_token
+
+ def _extract_images_from_prompts(self, prompts):
+ prompt_images = []
+ for prompt in prompts:
+ images = []
+ for elem in prompt:
+ if is_valid_image(elem):
+ images.append(elem)
+ elif is_url(elem):
+ images.append(load_image(elem))
+ prompt_images.append(images)
+ return prompt_images
+
+ @auto_docstring
+ def __call__(
+ self,
+ images: ImageInput | list[ImageInput] | list[list[ImageInput]] = None,
+ text: Union[TextInput, "PreTokenizedInput", list[TextInput], list["PreTokenizedInput"]] = None,
+ image_seq_len: int | None = None,
+ **kwargs: Unpack[ColModernVBertProcessorKwargs],
+ ) -> BatchEncoding:
+ r"""
+ image_seq_len (`int`, *optional*):
+ The length of the image sequence. If not provided, the default value of self.image_seq_len is used.
+ image_seq_len should be equal to int(((image_size // patch_size) ** 2) / (scale_factor**2))
+ """
+ if text is None and images is None:
+ raise ValueError("You must provide either `text` or `images`.")
+
+ output_kwargs = self._merge_kwargs(
+ ColModernVBertProcessorKwargs,
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
+ **kwargs,
+ )
+
+ image_seq_len = image_seq_len if image_seq_len is not None else self.image_seq_len
+ return_mm_token_type_ids = output_kwargs["text_kwargs"].pop("return_mm_token_type_ids", False)
+ return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None)
+
+ n_images_in_text = []
+ n_images_in_images = []
+ inputs = {}
+
+ if text is not None:
+ if isinstance(text, str):
+ text = [text]
+ elif not isinstance(text, list) and not isinstance(text[0], str):
+ raise ValueError("Invalid input text. Please provide a string, or a list of strings")
+ n_images_in_text = [sample.count(self.image_token) for sample in text]
+
+ if images is not None:
+ if is_image_or_image_url(images):
+ images = [[images]]
+ elif isinstance(images, (list, tuple)) and is_image_or_image_url(images[0]):
+ if text is not None:
+ if sum(n_images_in_text) != len(images):
+ raise ValueError(
+ f"The total number of {self.image_token} tokens in the prompts should be the same as the number of images passed."
+ f" Found {sum(n_images_in_text)} {self.image_token} tokens and {len(images)} images."
+ )
+ # Reorganize the images to match the prompts
+ cumsum_images_in_text = [0] + list(accumulate(n_images_in_text))
+ images = [
+ images[cumsum_images_in_text[i] : cumsum_images_in_text[i + 1]]
+ for i in range(len(n_images_in_text))
+ ]
+ else:
+ images = [images]
+ elif (
+ not isinstance(images, (list, tuple))
+ and not isinstance(images[0], (list, tuple))
+ and not is_image_or_image_url(images[0][0])
+ ):
+ raise ValueError(
+ "Invalid input images. Please provide a single image or a list of images or a list of list of images."
+ )
+ n_images_in_images = [len(sample) for sample in images]
+
+ # Load images if they are URLs
+ images = [[load_image(im) if is_url(im) else im for im in sample] for sample in images]
+
+ image_inputs = self.image_processor(images, **output_kwargs["images_kwargs"])
+ inputs.update(image_inputs)
+
+ if text is not None:
+ if n_images_in_images != n_images_in_text:
+ raise ValueError(
+ f"The number of images in the text {n_images_in_text} and images {n_images_in_images} should be the same."
+ )
+
+ image_rows = inputs.pop("rows", [[0] * n_images for n_images in n_images_in_text])
+ image_cols = inputs.pop("cols", [[0] * n_images for n_images in n_images_in_text])
+
+ fake_image_token = self.fake_image_token
+ image_token = self.image_token
+ global_img_token = self.global_image_tag
+
+ prompt_strings = []
+ batch_image_seq_lengths = []
+ for sample, sample_rows, sample_cols in zip(text, image_rows, image_cols):
+ # Replace the image token with fake tokens around the expanded image token sequence of length `image_seq_len`
+ image_prompt_strings = []
+ image_seq_lengths = []
+ for n_rows, n_cols in zip(sample_rows, sample_cols):
+ image_prompt_string = get_image_prompt_string(
+ n_rows,
+ n_cols,
+ image_seq_len,
+ image_token=image_token,
+ fake_token_around_image=fake_image_token,
+ global_img_token=global_img_token,
+ )
+ # Add +2 and +3 for special BOI/EOI/fake_image_wrapper tokens
+ row_length = (self.image_seq_len + 2) * n_cols + 1
+ image_seq_lengths.append((self.image_seq_len + 3) + row_length * n_rows)
+ image_prompt_strings.append(image_prompt_string)
+
+ batch_image_seq_lengths.append(image_seq_lengths)
+ split_sample = sample.split(image_token)
+ if len(split_sample) == 0:
+ raise ValueError("The image token should be present in the text.")
+
+ # Place in the image prompt strings where the image tokens are
+ sample = split_sample[0]
+ for i, image_prompt_string in enumerate(image_prompt_strings):
+ sample += image_prompt_string + split_sample[i + 1]
+ prompt_strings.append(sample)
+
+ text_inputs = self.tokenizer(prompt_strings, **output_kwargs["text_kwargs"])
+ self._check_special_mm_tokens(prompt_strings, text_inputs, modalities=["image"])
+ inputs.update(text_inputs)
+
+ elif text is not None:
+ if any(n_images_in_text):
+ raise ValueError(
+ f"Found {sum(n_images_in_text)} {self.image_token} tokens in the text but no images were passed."
+ )
+ text_inputs = self.tokenizer(text=text, **output_kwargs["text_kwargs"])
+ inputs.update(text_inputs)
+
+ if return_mm_token_type_ids:
+ inputs["mm_token_type_ids"] = self.create_mm_token_type_ids(inputs["input_ids"], batch_image_seq_lengths)
+ return BatchFeature(data=inputs, tensor_type=return_tensors)
+
+ def create_mm_token_type_ids(self, input_ids: list, batch_image_seq_lengths: list[int]) -> list[list[int]]:
+ # We have to iterate for each list separately because inputs
+ # might be non-padded lists and we can't cast numpy on that!
+ # Then cast numpy as each input for faster indexing
+ mm_token_type_ids = []
+ for i, seq_lengths in enumerate(batch_image_seq_lengths):
+ array_ids = np.array(input_ids[i])
+ mm_token_types = np.zeros_like(array_ids)
+ image_start_positions = np.where(array_ids == self.fake_image_token_id)[0]
+ j = 0
+ for seq_len in seq_lengths:
+ if j >= len(image_start_positions):
+ break
+ start = image_start_positions[j]
+ end = start + seq_len
+ mm_token_types[start:end] = 1
+ j = np.searchsorted(image_start_positions, end)
+ mm_token_type_ids.append(mm_token_types.tolist())
+
+ return mm_token_type_ids
+
+ def _get_num_multimodal_tokens(self, image_sizes=None, **kwargs):
+ """
+ Computes the number of placeholder tokens needed for multimodal inputs with the given sizes.
+
+ Args:
+ image_sizes (`list[list[int]]`, *optional*):
+ The input sizes formatted as (height, width) per each image.
+
+ Returns:
+ `MultiModalData`: A `MultiModalData` object holding number of tokens per each of the provided
+ input modalities, along with other useful data.
+ """
+
+ vision_data = {}
+ if image_sizes is not None:
+ images_kwargs = ColModernVBertProcessorKwargs._defaults.get("images_kwargs", {})
+ images_kwargs.update(kwargs)
+
+ num_image_row_cols = [
+ self.image_processor.get_number_of_image_patches(*image_size, images_kwargs)
+ for image_size in image_sizes
+ ]
+
+ base_image_length = self.image_seq_len + 3
+ col_length = self.image_seq_len + 2
+ num_image_tokens = []
+ num_image_patches = []
+
+ for num_patches, num_rows, num_cols in num_image_row_cols:
+ row_length = col_length * num_cols + 1
+ num_image_tokens.append(base_image_length + (row_length * num_rows))
+ num_image_patches.append(num_patches)
+
+ vision_data.update({"num_image_tokens": num_image_tokens, "num_image_patches": num_image_patches})
+
+ return MultiModalData(**vision_data)
+
+ def process_images(
+ self,
+ images: ImageInput | None = None,
+ **kwargs: Unpack[ColModernVBertProcessorKwargs],
+ ) -> BatchFeature:
+ """
+ Prepare for the model one or several image(s). Handles input validation, RGB conversion,
+ and prepends the `visual_prompt_prefix` to each image. Optionally computes labels from
+ `token_type_ids` when a `suffix` is provided in `text_kwargs`.
+
+ Args:
+ images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `list[PIL.Image.Image]`, `list[np.ndarray]`, `list[torch.Tensor]`):
+ The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
+ tensor. In case of a NumPy array/PyTorch tensor, each image should be of shape (C, H, W), where C is a
+ number of channels, H and W are image height and width.
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
+ If set, will return tensors of a particular framework. Acceptable values are:
+
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
+ - `'np'`: Return NumPy `np.ndarray` objects.
+
+ Returns:
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
+
+ - **input_ids** -- List of token ids to be fed to a model.
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
+ `None`).
+ - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
+ """
+ output_kwargs = self._merge_kwargs(
+ ColModernVBertProcessorKwargs,
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
+ **kwargs,
+ )
+
+ suffix = output_kwargs["text_kwargs"].pop("suffix", None)
+
+ return_token_type_ids = suffix is not None
+
+ # Normalize input to a flat list of images
+ if is_valid_image(images):
+ images = [images]
+ elif isinstance(images, list) and is_valid_image(images[0]):
+ pass
+ elif not (isinstance(images, list) and isinstance(images[0], list) and is_valid_image(images[0][0])):
+ raise ValueError("images must be an image, list of images or list of list of images")
+
+ # Ensure all images are in RGB format
+ images = [image.convert("RGB") for image in images]
+
+ # Pair each image with the visual prompt prefix for the VLM backbone
+ batch_doc = self.__call__(
+ text=[self.visual_prompt_prefix] * len(images),
+ images=images,
+ images_kwargs=output_kwargs["images_kwargs"],
+ text_kwargs=output_kwargs["text_kwargs"],
+ )
+
+ # When suffix is provided, generate labels by masking non-suffix tokens
+ if return_token_type_ids:
+ labels = batch_doc["input_ids"].masked_fill(batch_doc["token_type_ids"] == 0, -100)
+ batch_doc.update({"labels": labels})
+
+ return batch_doc
+
+ def process_queries(
+ self,
+ text: TextInput | list[TextInput],
+ **kwargs: Unpack[ColModernVBertProcessorKwargs],
+ ) -> BatchFeature:
+ """
+ Prepare for the model one or several text queries. Handles input validation, prepends the
+ `query_prefix`, and appends query augmentation tokens (used to pad query embeddings for
+ better late-interaction retrieval performance).
+
+ Args:
+ text (`str`, `list[str]`, `list[list[str]]`):
+ The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
+ (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
+ `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
+ If set, will return tensors of a particular framework. Acceptable values are:
+
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
+ - `'np'`: Return NumPy `np.ndarray` objects.
+
+ Returns:
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
+
+ - **input_ids** -- List of token ids to be fed to a model.
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
+ `None`).
+ """
+ output_kwargs = self._merge_kwargs(
+ ColModernVBertProcessorKwargs,
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
+ **kwargs,
+ )
+
+ suffix = output_kwargs["text_kwargs"].pop("suffix", None)
+
+ if isinstance(text, str):
+ text = [text]
+ elif not (isinstance(text, list) and isinstance(text[0], str)):
+ raise ValueError("Text must be a string or a list of strings")
+
+ # Default suffix: repeat the augmentation token to pad query embeddings
+ if suffix is None:
+ suffix = self.query_augmentation_token * 10
+
+ # Build final queries: prefix + original query + augmentation suffix
+ texts_query: list[str] = [self.query_prefix + query + suffix for query in text]
+
+ batch_query = self.__call__(
+ text=texts_query,
+ return_token_type_ids=False,
+ text_kwargs=output_kwargs["text_kwargs"],
+ )
+
+ return batch_query
+
+ def score_retrieval(
+ self,
+ query_embeddings: Union["torch.Tensor", list["torch.Tensor"]],
+ passage_embeddings: Union["torch.Tensor", list["torch.Tensor"]],
+ batch_size: int = 128,
+ output_dtype: Optional["torch.dtype"] = None,
+ output_device: Union["torch.device", str] = "cpu",
+ ) -> "torch.Tensor":
+ """
+ Compute the late-interaction/MaxSim score (ColBERT-like) for the given multi-vector
+ query embeddings (`qs`) and passage embeddings (`ps`). For ColQwen2, a passage is the
+ image of a document page.
+
+ Because the embedding tensors are multi-vector and can thus have different shapes, they
+ should be fed as:
+ (1) a list of tensors, where the i-th tensor is of shape (sequence_length_i, embedding_dim)
+ (2) a single tensor of shape (n_passages, max_sequence_length, embedding_dim) -> usually
+ obtained by padding the list of tensors.
+
+ Args:
+ query_embeddings (`Union[torch.Tensor, list[torch.Tensor]`): Query embeddings.
+ passage_embeddings (`Union[torch.Tensor, list[torch.Tensor]`): Passage embeddings.
+ batch_size (`int`, *optional*, defaults to 128): Batch size for computing scores.
+ output_dtype (`torch.dtype`, *optional*, defaults to `torch.float32`): The dtype of the output tensor.
+ If `None`, the dtype of the input embeddings is used.
+ output_device (`torch.device` or `str`, *optional*, defaults to "cpu"): The device of the output tensor.
+
+ Returns:
+ `torch.Tensor`: A tensor of shape `(n_queries, n_passages)` containing the scores. The score
+ tensor is saved on the "cpu" device.
+ """
+
+ if len(query_embeddings) == 0:
+ raise ValueError("No queries provided")
+ if len(passage_embeddings) == 0:
+ raise ValueError("No passages provided")
+
+ if query_embeddings[0].device != passage_embeddings[0].device:
+ raise ValueError("Queries and passages must be on the same device")
+
+ if query_embeddings[0].dtype != passage_embeddings[0].dtype:
+ raise ValueError("Queries and passages must have the same dtype")
+
+ if output_dtype is None:
+ output_dtype = query_embeddings[0].dtype
+
+ scores: list[torch.Tensor] = []
+
+ for i in range(0, len(query_embeddings), batch_size):
+ batch_scores: list[torch.Tensor] = []
+ batch_queries = torch.nn.utils.rnn.pad_sequence(
+ query_embeddings[i : i + batch_size], batch_first=True, padding_value=0
+ )
+ for j in range(0, len(passage_embeddings), batch_size):
+ batch_passages = torch.nn.utils.rnn.pad_sequence(
+ passage_embeddings[j : j + batch_size], batch_first=True, padding_value=0
+ )
+ batch_scores.append(
+ torch.einsum("bnd,csd->bcns", batch_queries, batch_passages).max(dim=3)[0].sum(dim=2)
+ )
+ scores.append(torch.cat(batch_scores, dim=1).to(output_dtype).to(output_device))
+
+ return torch.cat(scores, dim=0)
+
+
+__all__ = ["ColModernVBertProcessor"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/colqwen2/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/colqwen2/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d313293c0a0a7b5c56ac5bec1e54e8eb1e5a6e4a
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/colqwen2/__init__.py
@@ -0,0 +1,28 @@
+# Copyright 2025 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_colqwen2 import *
+ from .modeling_colqwen2 import *
+ from .processing_colqwen2 import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/colqwen2/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/colqwen2/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..90a85d7e1ce542628d7047a79999068a715945b2
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/colqwen2/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/colqwen2/__pycache__/configuration_colqwen2.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/colqwen2/__pycache__/configuration_colqwen2.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..178bf16ee8649bb33afd3fa34c62714e9da7d59a
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/colqwen2/__pycache__/configuration_colqwen2.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/colqwen2/__pycache__/modeling_colqwen2.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/colqwen2/__pycache__/modeling_colqwen2.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1125c3172cd959bc012511ada69c15ffe4b3f09b
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/colqwen2/__pycache__/modeling_colqwen2.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/colqwen2/__pycache__/modular_colqwen2.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/colqwen2/__pycache__/modular_colqwen2.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..da5bed6a3d70c29b96e696e3859c07bed04cdf74
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/colqwen2/__pycache__/modular_colqwen2.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/colqwen2/__pycache__/processing_colqwen2.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/colqwen2/__pycache__/processing_colqwen2.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fecbb4af034fc898877b70ac0bbb26ba2017fb47
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/colqwen2/__pycache__/processing_colqwen2.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/colqwen2/configuration_colqwen2.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/colqwen2/configuration_colqwen2.py
new file mode 100644
index 0000000000000000000000000000000000000000..ac9abcb5cfd91f0688bf6402b988207608f90d1c
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/colqwen2/configuration_colqwen2.py
@@ -0,0 +1,65 @@
+# Copyright 2025 The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring, logging
+from ..auto import CONFIG_MAPPING
+
+
+logger = logging.get_logger(__name__)
+
+
+@auto_docstring(checkpoint="vidore/colqwen2-v1.0-hf")
+@strict
+class ColQwen2Config(PreTrainedConfig):
+ r"""
+ Example:
+
+ ```python
+ from transformers.models.colqwen2 import ColQwen2Config, ColQwen2ForRetrieval
+
+ config = ColQwen2Config()
+ model = ColQwen2ForRetrieval(config)
+ ```
+ """
+
+ model_type = "colqwen2"
+ sub_configs = {"vlm_config": PreTrainedConfig}
+
+ vlm_config: dict | PreTrainedConfig | None = None
+ embedding_dim: int = 128
+ initializer_range: float = 0.02
+
+ def __post_init__(self, **kwargs):
+ if self.vlm_config is None:
+ self.vlm_config = CONFIG_MAPPING["qwen2_vl"]()
+ logger.info(
+ "`vlm_config` is `None`. Initializing `vlm_config` with the `Qwen2VLConfig` with default values."
+ )
+ elif isinstance(self.vlm_config, dict):
+ self.vlm_config = CONFIG_MAPPING[self.vlm_config["model_type"]](**self.vlm_config)
+
+ if not hasattr(self.vlm_config, "vocab_size"):
+ self.vlm_config.vocab_size = self.vlm_config.get_text_config().vocab_size
+
+ super().__post_init__(**kwargs)
+
+ def get_text_config(self, *args, **kwargs) -> PreTrainedConfig:
+ return self.vlm_config.get_text_config(*args, **kwargs)
+
+
+__all__ = ["ColQwen2Config"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/colqwen2/modeling_colqwen2.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/colqwen2/modeling_colqwen2.py
new file mode 100644
index 0000000000000000000000000000000000000000..57a15a4f64623455a30850b019846506907ce06f
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/colqwen2/modeling_colqwen2.py
@@ -0,0 +1,205 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/colqwen2/modular_colqwen2.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_colqwen2.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2025 The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from dataclasses import dataclass
+
+from torch import nn
+
+from transformers import AutoModel
+
+from ... import initialization as init
+from ...cache_utils import Cache
+from ...modeling_utils import PreTrainedModel
+from ...utils import ModelOutput, auto_docstring, can_return_tuple, is_torch_available
+from .configuration_colqwen2 import ColQwen2Config
+
+
+if is_torch_available():
+ import torch
+
+
+@auto_docstring
+class ColQwen2PreTrainedModel(PreTrainedModel):
+ config: ColQwen2Config
+ base_model_prefix = "model"
+ input_modalities = ("image", "text")
+ _no_split_modules = []
+ _supports_sdpa = True
+ _supports_flash_attn = True
+ _supports_flex_attn = True
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ std = (
+ self.config.initializer_range
+ if hasattr(self.config, "initializer_range")
+ else self.config.vlm_config.text_config.initializer_range
+ )
+
+ if isinstance(module, (nn.Linear, nn.Conv2d)):
+ init.normal_(module.weight, mean=0.0, std=std)
+ if module.bias is not None:
+ init.zeros_(module.bias)
+ elif isinstance(module, nn.Embedding):
+ init.normal_(module.weight, mean=0.0, std=std)
+ # Here we need the check explicitly, as we slice the weight in the `zeros_` call, so it looses the flag
+ if module.padding_idx is not None and not getattr(module.weight, "_is_hf_initialized", False):
+ init.zeros_(module.weight[module.padding_idx])
+
+
+@auto_docstring(
+ custom_intro="""
+ Base class for ColQwen2 embeddings output.
+ """
+)
+@dataclass
+class ColQwen2ForRetrievalOutput(ModelOutput):
+ r"""
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
+ Language modeling loss (for next-token prediction).
+ embeddings (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
+ The embeddings of the model.
+ past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
+ It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
+
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
+ `past_key_values` input) to speed up sequential decoding.
+ """
+
+ loss: torch.FloatTensor | None = None
+ embeddings: torch.Tensor | None = None
+ past_key_values: Cache | None = None
+ hidden_states: tuple[torch.FloatTensor] | None = None
+ attentions: tuple[torch.FloatTensor] | None = None
+
+
+@auto_docstring(
+ custom_intro="""
+ Following the ColPali approach, ColQwen2 leverages VLMs to construct efficient multi-vector embeddings directly
+ from document images (“screenshots”) for document retrieval. The model is trained to maximize the similarity
+ between these document embeddings and the corresponding query embeddings, using the late interaction method
+ introduced in ColBERT.
+
+ Using ColQwen2 removes the need for potentially complex and brittle layout recognition and OCR pipelines with
+ a single model that can take into account both the textual and visual content (layout, charts, ...) of a document.
+
+ ColQwen2 is part of the ColVision model family, which was introduced with ColPali in the following paper:
+ [*ColPali: Efficient Document Retrieval with Vision Language Models*](https://huggingface.co/papers/2407.01449).
+ """
+)
+class ColQwen2ForRetrieval(ColQwen2PreTrainedModel):
+ base_model_prefix = "vlm"
+
+ def __init__(self, config: ColQwen2Config):
+ super().__init__(config)
+ self.config = config
+ self.vocab_size = config.vlm_config.text_config.vocab_size
+
+ self.vlm = AutoModel.from_config(config.vlm_config)
+
+ self.embedding_dim = self.config.embedding_dim
+ self.embedding_proj_layer = nn.Linear(
+ self.config.vlm_config.text_config.hidden_size,
+ self.embedding_dim,
+ )
+
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ labels: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ use_cache: bool | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ pixel_values: torch.Tensor | None = None,
+ image_grid_thw: torch.LongTensor | None = None,
+ **kwargs,
+ ) -> ColQwen2ForRetrievalOutput:
+ r"""
+ image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
+ The temporal, height and width of feature shape of each image in LLM.
+ """
+ # Handle the custom "pixel_values" input obtained with `ColQwen2Processor` through unpadding
+ if pixel_values is not None and image_grid_thw is not None:
+ # NOTE: image_grid_thw: (batch_size, 3) where image_grid_thw[i] = (num_patches_h, num_patches_w, temporal_patch_size)
+ offsets = image_grid_thw[:, 1] * image_grid_thw[:, 2] # (batch_size,)
+ arange = torch.arange(pixel_values.shape[1], device=offsets.device) # (max_len,)
+ mask = arange.unsqueeze(0) < offsets.unsqueeze(1) # (batch_size, max_len)
+ pixel_values = pixel_values[mask] # (total_valid_patches, channels, height, width)
+
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ # Custom data preparation to fix an issue with the gradient flow when training with multiple GPUs.
+ if inputs_embeds is None:
+ inputs_embeds = self.vlm.get_input_embeddings()(input_ids)
+
+ if pixel_values is not None:
+ image_embeds = self.vlm.visual(pixel_values, grid_thw=image_grid_thw, return_dict=True).pooler_output
+ image_mask = (
+ (input_ids == self.config.vlm_config.image_token_id).unsqueeze(-1).expand_as(inputs_embeds)
+ )
+ image_embeds = image_embeds.to(inputs_embeds.device, inputs_embeds.dtype)
+ inputs_embeds = inputs_embeds.masked_scatter(image_mask, image_embeds)
+
+ vlm_output = self.vlm(
+ input_ids=None,
+ position_ids=position_ids,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ vlm_hidden_states = vlm_output.hidden_states if output_hidden_states else None
+
+ last_hidden_states = vlm_output[0] # (batch_size, sequence_length, hidden_size)
+ proj_dtype = self.embedding_proj_layer.weight.dtype
+ embeddings = self.embedding_proj_layer(last_hidden_states.to(proj_dtype)) # (batch_size, sequence_length, dim)
+
+ # L2 normalization
+ embeddings = embeddings / embeddings.norm(dim=-1, keepdim=True) # (batch_size, sequence_length, dim)
+ if attention_mask is not None:
+ embeddings = embeddings * attention_mask.unsqueeze(-1) # (batch_size, sequence_length, dim)
+
+ return ColQwen2ForRetrievalOutput(
+ embeddings=embeddings,
+ past_key_values=vlm_output.past_key_values,
+ hidden_states=vlm_hidden_states,
+ attentions=vlm_output.attentions,
+ )
+
+
+__all__ = ["ColQwen2ForRetrieval", "ColQwen2PreTrainedModel"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/colqwen2/modular_colqwen2.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/colqwen2/modular_colqwen2.py
new file mode 100644
index 0000000000000000000000000000000000000000..eb755e26313b50430f41c6a41fbc908764765e2d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/colqwen2/modular_colqwen2.py
@@ -0,0 +1,348 @@
+# Copyright 2025 The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from dataclasses import dataclass
+
+from ...cache_utils import Cache
+from ...feature_extraction_utils import BatchFeature
+from ...image_utils import ImageInput, is_valid_image
+from ...processing_utils import MultiModalData, ProcessingKwargs, ProcessorMixin, Unpack
+from ...tokenization_utils_base import PreTokenizedInput, TextInput
+from ...utils import ModelOutput, auto_docstring, can_return_tuple, is_torch_available, logging
+from ..colpali.modeling_colpali import ColPaliForRetrieval, ColPaliPreTrainedModel
+from ..colpali.processing_colpali import ColPaliProcessor
+from .configuration_colqwen2 import ColQwen2Config
+
+
+if is_torch_available():
+ import torch
+
+logger = logging.get_logger(__name__)
+
+
+class ColQwen2ProcessorKwargs(ProcessingKwargs, total=False):
+ _defaults = {
+ "text_kwargs": {
+ "padding": "longest",
+ },
+ "images_kwargs": {
+ "data_format": "channels_first",
+ "do_convert_rgb": True,
+ },
+ "common_kwargs": {"return_tensors": "pt"},
+ }
+
+
+class ColQwen2Processor(ColPaliProcessor):
+ def __init__(
+ self,
+ image_processor=None,
+ tokenizer=None,
+ chat_template=None,
+ visual_prompt_prefix: str | None = None,
+ query_prefix: str | None = None,
+ **kwargs,
+ ):
+ r"""
+ visual_prompt_prefix (`str`, *optional*, defaults to `"<|im_start|>user\n<|vision_start|><|image_pad|><|vision_end|>Describe the image.<|im_end|><|endoftext|>"`):
+ A string that gets tokenized and prepended to the image tokens.
+ query_prefix (`str`, *optional*, defaults to `"Query: "`):
+ A prefix to be used for the query.
+ """
+ ProcessorMixin.__init__(self, image_processor, tokenizer, chat_template=chat_template)
+ self.image_token = "<|image_pad|>" if not hasattr(tokenizer, "image_token") else tokenizer.image_token
+ self.video_token = "<|video_pad|>" if not hasattr(tokenizer, "video_token") else tokenizer.video_token
+
+ self.visual_prompt_prefix = visual_prompt_prefix or (
+ "<|im_start|>user\n<|vision_start|><|image_pad|><|vision_end|>Describe the image.<|im_end|><|endoftext|>"
+ )
+ self.query_prefix = query_prefix or "Query: "
+
+ def __call__(
+ self,
+ images: ImageInput | None = None,
+ text: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] = None,
+ **kwargs: Unpack[ColQwen2ProcessorKwargs],
+ ) -> BatchFeature:
+ r"""
+ Returns:
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
+
+ - **input_ids** -- List of token ids to be fed to a model.
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
+ `None`).
+ - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
+ """
+ output_kwargs = self._merge_kwargs(
+ ColQwen2ProcessorKwargs,
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
+ **kwargs,
+ )
+ suffix = output_kwargs["text_kwargs"].pop("suffix", None)
+
+ return_token_type_ids = suffix is not None
+
+ if text is None and images is None:
+ raise ValueError("Either text or images must be provided")
+ if text is not None and images is not None:
+ raise ValueError("Only one of text or images can be processed at a time")
+
+ if images is not None:
+ if is_valid_image(images):
+ images = [images]
+ elif isinstance(images, list) and is_valid_image(images[0]):
+ pass
+ elif not (isinstance(images, list) and isinstance(images[0], list) and is_valid_image(images[0][0])):
+ raise ValueError("images must be an image, list of images or list of list of images")
+
+ texts_doc = [self.visual_prompt_prefix] * len(images)
+
+ image_inputs = self.image_processor(images=images, **output_kwargs["images_kwargs"])
+ image_grid_thw = image_inputs["image_grid_thw"]
+
+ if image_grid_thw is not None:
+ merge_length = self.image_processor.merge_size**2
+ index = 0
+ for i in range(len(texts_doc)):
+ while self.image_token in texts_doc[i]:
+ texts_doc[i] = texts_doc[i].replace(
+ self.image_token, "<|placeholder|>" * (image_grid_thw[index].prod() // merge_length), 1
+ )
+ index += 1
+ texts_doc[i] = texts_doc[i].replace("<|placeholder|>", self.image_token)
+
+ text_inputs = self.tokenizer(
+ texts_doc,
+ return_token_type_ids=False,
+ **output_kwargs["text_kwargs"],
+ )
+
+ return_data = BatchFeature(data={**text_inputs, **image_inputs})
+
+ # NOTE: The following adjustment ensures correct behavior with DDP on multiple GPUs.
+ offsets = return_data["image_grid_thw"][:, 1] * return_data["image_grid_thw"][:, 2] # (batch_size,)
+
+ # Split the pixel_values tensor into a list of tensors, one per image
+ pixel_values = list(
+ torch.split(return_data["pixel_values"], offsets.tolist())
+ ) # [(num_patches_image_0, pixel_values), ..., (num_patches_image_n, pixel_values)]
+
+ # Pad the list of pixel_value tensors to the same length along the sequence dimension
+ return_data["pixel_values"] = torch.nn.utils.rnn.pad_sequence(
+ pixel_values, batch_first=True
+ ) # (batch_size, max_num_patches, pixel_values)
+
+ if return_token_type_ids:
+ labels = return_data["input_ids"].masked_fill(return_data["token_type_ids"] == 0, -100)
+ return_data.update({"labels": labels})
+
+ return return_data
+
+ elif text is not None:
+ if isinstance(text, str):
+ text = [text]
+ elif not (isinstance(text, list) and isinstance(text[0], str)):
+ raise ValueError("Text must be a string or a list of strings")
+
+ if suffix is None:
+ suffix = self.query_augmentation_token * 10
+
+ texts_query: list[str] = []
+
+ for query in text:
+ augmented_query = self.query_prefix + query + suffix
+ texts_query.append(augmented_query)
+
+ batch_query = self.tokenizer(
+ texts_query,
+ return_token_type_ids=False,
+ **output_kwargs["text_kwargs"],
+ )
+
+ return batch_query
+
+ def _get_num_multimodal_tokens(self, image_sizes=None, **kwargs):
+ """
+ Computes the number of placeholder tokens needed for multimodal inputs with the given sizes.
+ Args:
+ image_sizes (`list[list[int]]`, *optional*):
+ The input sizes formatted as (height, width) per each image.
+ Returns:
+ `MultiModalData`: A `MultiModalData` object holding number of tokens per each of the provided
+ input modalities, along with other useful data.
+ """
+
+ vision_data = {}
+ if image_sizes is not None:
+ images_kwargs = ColQwen2ProcessorKwargs._defaults.get("images_kwargs", {})
+ images_kwargs.update(kwargs)
+ merge_size = images_kwargs.get("merge_size", None) or self.image_processor.merge_size
+
+ num_image_patches = [
+ self.image_processor.get_number_of_image_patches(*image_size, images_kwargs)
+ for image_size in image_sizes
+ ]
+ num_image_tokens = [(num_patches // merge_size**2) for num_patches in num_image_patches]
+ vision_data.update({"num_image_tokens": num_image_tokens, "num_image_patches": num_image_patches})
+
+ return MultiModalData(**vision_data)
+
+ @property
+ def model_input_names(self):
+ tokenizer_input_names = self.tokenizer.model_input_names
+ image_processor_input_names = self.image_processor.model_input_names
+
+ # ColQwen doesn't process videos. Make a copy of list when removing
+ # otherwise `self.feature_extractor.model_input_names` is also modified
+ image_processor_input_names = [
+ name for name in image_processor_input_names if name not in ["pixel_values_videos", "video_grid_thw"]
+ ]
+ return tokenizer_input_names + image_processor_input_names
+
+
+class ColQwen2PreTrainedModel(ColPaliPreTrainedModel):
+ pass
+
+
+@auto_docstring(
+ custom_intro="""
+ Base class for ColQwen2 embeddings output.
+ """
+)
+@dataclass
+class ColQwen2ForRetrievalOutput(ModelOutput):
+ r"""
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
+ Language modeling loss (for next-token prediction).
+ embeddings (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
+ The embeddings of the model.
+ past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
+ It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
+
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
+ `past_key_values` input) to speed up sequential decoding.
+ """
+
+ loss: torch.FloatTensor | None = None
+ embeddings: torch.Tensor | None = None
+ past_key_values: Cache | None = None
+ hidden_states: tuple[torch.FloatTensor] | None = None
+ attentions: tuple[torch.FloatTensor] | None = None
+
+
+@auto_docstring(
+ custom_intro="""
+ Following the ColPali approach, ColQwen2 leverages VLMs to construct efficient multi-vector embeddings directly
+ from document images (“screenshots”) for document retrieval. The model is trained to maximize the similarity
+ between these document embeddings and the corresponding query embeddings, using the late interaction method
+ introduced in ColBERT.
+
+ Using ColQwen2 removes the need for potentially complex and brittle layout recognition and OCR pipelines with
+ a single model that can take into account both the textual and visual content (layout, charts, ...) of a document.
+
+ ColQwen2 is part of the ColVision model family, which was introduced with ColPali in the following paper:
+ [*ColPali: Efficient Document Retrieval with Vision Language Models*](https://huggingface.co/papers/2407.01449).
+ """
+)
+class ColQwen2ForRetrieval(ColPaliForRetrieval):
+ def __init__(self, config: ColQwen2Config):
+ super().__init__(config)
+ del self._tied_weights_keys
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ labels: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ use_cache: bool | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ pixel_values: torch.Tensor | None = None,
+ image_grid_thw: torch.LongTensor | None = None,
+ **kwargs,
+ ) -> ColQwen2ForRetrievalOutput:
+ r"""
+ image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
+ The temporal, height and width of feature shape of each image in LLM.
+ """
+ # Handle the custom "pixel_values" input obtained with `ColQwen2Processor` through unpadding
+ if pixel_values is not None and image_grid_thw is not None:
+ # NOTE: image_grid_thw: (batch_size, 3) where image_grid_thw[i] = (num_patches_h, num_patches_w, temporal_patch_size)
+ offsets = image_grid_thw[:, 1] * image_grid_thw[:, 2] # (batch_size,)
+ arange = torch.arange(pixel_values.shape[1], device=offsets.device) # (max_len,)
+ mask = arange.unsqueeze(0) < offsets.unsqueeze(1) # (batch_size, max_len)
+ pixel_values = pixel_values[mask] # (total_valid_patches, channels, height, width)
+
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ # Custom data preparation to fix an issue with the gradient flow when training with multiple GPUs.
+ if inputs_embeds is None:
+ inputs_embeds = self.vlm.get_input_embeddings()(input_ids)
+
+ if pixel_values is not None:
+ image_embeds = self.vlm.visual(pixel_values, grid_thw=image_grid_thw, return_dict=True).pooler_output
+ image_mask = (
+ (input_ids == self.config.vlm_config.image_token_id).unsqueeze(-1).expand_as(inputs_embeds)
+ )
+ image_embeds = image_embeds.to(inputs_embeds.device, inputs_embeds.dtype)
+ inputs_embeds = inputs_embeds.masked_scatter(image_mask, image_embeds)
+
+ vlm_output = self.vlm(
+ input_ids=None,
+ position_ids=position_ids,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ vlm_hidden_states = vlm_output.hidden_states if output_hidden_states else None
+
+ last_hidden_states = vlm_output[0] # (batch_size, sequence_length, hidden_size)
+ proj_dtype = self.embedding_proj_layer.weight.dtype
+ embeddings = self.embedding_proj_layer(last_hidden_states.to(proj_dtype)) # (batch_size, sequence_length, dim)
+
+ # L2 normalization
+ embeddings = embeddings / embeddings.norm(dim=-1, keepdim=True) # (batch_size, sequence_length, dim)
+ if attention_mask is not None:
+ embeddings = embeddings * attention_mask.unsqueeze(-1) # (batch_size, sequence_length, dim)
+
+ return ColQwen2ForRetrievalOutput(
+ embeddings=embeddings,
+ past_key_values=vlm_output.past_key_values,
+ hidden_states=vlm_hidden_states,
+ attentions=vlm_output.attentions,
+ )
+
+
+__all__ = [
+ "ColQwen2ForRetrieval",
+ "ColQwen2PreTrainedModel",
+ "ColQwen2Processor",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/colqwen2/processing_colqwen2.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/colqwen2/processing_colqwen2.py
new file mode 100644
index 0000000000000000000000000000000000000000..48af99206afeb55031853eadd875ab24d0f4cfa2
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/colqwen2/processing_colqwen2.py
@@ -0,0 +1,355 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/colqwen2/modular_colqwen2.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_colqwen2.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2025 The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from typing import Optional, Union
+
+from ...feature_extraction_utils import BatchFeature
+from ...image_utils import ImageInput, is_valid_image
+from ...processing_utils import MultiModalData, ProcessingKwargs, ProcessorMixin, Unpack
+from ...tokenization_utils_base import PreTokenizedInput, TextInput
+from ...utils import auto_docstring, is_torch_available
+
+
+if is_torch_available():
+ import torch
+
+
+class ColQwen2ProcessorKwargs(ProcessingKwargs, total=False):
+ _defaults = {
+ "text_kwargs": {
+ "padding": "longest",
+ },
+ "images_kwargs": {
+ "data_format": "channels_first",
+ "do_convert_rgb": True,
+ },
+ "common_kwargs": {"return_tensors": "pt"},
+ }
+
+
+@auto_docstring
+class ColQwen2Processor(ProcessorMixin):
+ def __init__(
+ self,
+ image_processor=None,
+ tokenizer=None,
+ chat_template=None,
+ visual_prompt_prefix: str | None = None,
+ query_prefix: str | None = None,
+ **kwargs,
+ ):
+ r"""
+ visual_prompt_prefix (`str`, *optional*, defaults to `"<|im_start|>user\n<|vision_start|><|image_pad|><|vision_end|>Describe the image.<|im_end|><|endoftext|>"`):
+ A string that gets tokenized and prepended to the image tokens.
+ query_prefix (`str`, *optional*, defaults to `"Query: "`):
+ A prefix to be used for the query.
+ """
+ super().__init__(image_processor, tokenizer, chat_template=chat_template)
+ self.image_token = "<|image_pad|>" if not hasattr(tokenizer, "image_token") else tokenizer.image_token
+ self.video_token = "<|video_pad|>" if not hasattr(tokenizer, "video_token") else tokenizer.video_token
+
+ self.visual_prompt_prefix = visual_prompt_prefix or (
+ "<|im_start|>user\n<|vision_start|><|image_pad|><|vision_end|>Describe the image.<|im_end|><|endoftext|>"
+ )
+ self.query_prefix = query_prefix or "Query: "
+
+ @auto_docstring
+ def __call__(
+ self,
+ images: ImageInput | None = None,
+ text: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] = None,
+ **kwargs: Unpack[ColQwen2ProcessorKwargs],
+ ) -> BatchFeature:
+ r"""
+ Returns:
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
+
+ - **input_ids** -- List of token ids to be fed to a model.
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
+ `None`).
+ - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
+ """
+ output_kwargs = self._merge_kwargs(
+ ColQwen2ProcessorKwargs,
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
+ **kwargs,
+ )
+ suffix = output_kwargs["text_kwargs"].pop("suffix", None)
+
+ return_token_type_ids = suffix is not None
+
+ if text is None and images is None:
+ raise ValueError("Either text or images must be provided")
+ if text is not None and images is not None:
+ raise ValueError("Only one of text or images can be processed at a time")
+
+ if images is not None:
+ if is_valid_image(images):
+ images = [images]
+ elif isinstance(images, list) and is_valid_image(images[0]):
+ pass
+ elif not (isinstance(images, list) and isinstance(images[0], list) and is_valid_image(images[0][0])):
+ raise ValueError("images must be an image, list of images or list of list of images")
+
+ texts_doc = [self.visual_prompt_prefix] * len(images)
+
+ image_inputs = self.image_processor(images=images, **output_kwargs["images_kwargs"])
+ image_grid_thw = image_inputs["image_grid_thw"]
+
+ if image_grid_thw is not None:
+ merge_length = self.image_processor.merge_size**2
+ index = 0
+ for i in range(len(texts_doc)):
+ while self.image_token in texts_doc[i]:
+ texts_doc[i] = texts_doc[i].replace(
+ self.image_token, "<|placeholder|>" * (image_grid_thw[index].prod() // merge_length), 1
+ )
+ index += 1
+ texts_doc[i] = texts_doc[i].replace("<|placeholder|>", self.image_token)
+
+ text_inputs = self.tokenizer(
+ texts_doc,
+ return_token_type_ids=False,
+ **output_kwargs["text_kwargs"],
+ )
+
+ return_data = BatchFeature(data={**text_inputs, **image_inputs})
+
+ # NOTE: The following adjustment ensures correct behavior with DDP on multiple GPUs.
+ offsets = return_data["image_grid_thw"][:, 1] * return_data["image_grid_thw"][:, 2] # (batch_size,)
+
+ # Split the pixel_values tensor into a list of tensors, one per image
+ pixel_values = list(
+ torch.split(return_data["pixel_values"], offsets.tolist())
+ ) # [(num_patches_image_0, pixel_values), ..., (num_patches_image_n, pixel_values)]
+
+ # Pad the list of pixel_value tensors to the same length along the sequence dimension
+ return_data["pixel_values"] = torch.nn.utils.rnn.pad_sequence(
+ pixel_values, batch_first=True
+ ) # (batch_size, max_num_patches, pixel_values)
+
+ if return_token_type_ids:
+ labels = return_data["input_ids"].masked_fill(return_data["token_type_ids"] == 0, -100)
+ return_data.update({"labels": labels})
+
+ return return_data
+
+ elif text is not None:
+ if isinstance(text, str):
+ text = [text]
+ elif not (isinstance(text, list) and isinstance(text[0], str)):
+ raise ValueError("Text must be a string or a list of strings")
+
+ if suffix is None:
+ suffix = self.query_augmentation_token * 10
+
+ texts_query: list[str] = []
+
+ for query in text:
+ augmented_query = self.query_prefix + query + suffix
+ texts_query.append(augmented_query)
+
+ batch_query = self.tokenizer(
+ texts_query,
+ return_token_type_ids=False,
+ **output_kwargs["text_kwargs"],
+ )
+
+ return batch_query
+
+ def _get_num_multimodal_tokens(self, image_sizes=None, **kwargs):
+ """
+ Computes the number of placeholder tokens needed for multimodal inputs with the given sizes.
+ Args:
+ image_sizes (`list[list[int]]`, *optional*):
+ The input sizes formatted as (height, width) per each image.
+ Returns:
+ `MultiModalData`: A `MultiModalData` object holding number of tokens per each of the provided
+ input modalities, along with other useful data.
+ """
+
+ vision_data = {}
+ if image_sizes is not None:
+ images_kwargs = ColQwen2ProcessorKwargs._defaults.get("images_kwargs", {})
+ images_kwargs.update(kwargs)
+ merge_size = images_kwargs.get("merge_size", None) or self.image_processor.merge_size
+
+ num_image_patches = [
+ self.image_processor.get_number_of_image_patches(*image_size, images_kwargs)
+ for image_size in image_sizes
+ ]
+ num_image_tokens = [(num_patches // merge_size**2) for num_patches in num_image_patches]
+ vision_data.update({"num_image_tokens": num_image_tokens, "num_image_patches": num_image_patches})
+
+ return MultiModalData(**vision_data)
+
+ @property
+ def model_input_names(self):
+ tokenizer_input_names = self.tokenizer.model_input_names
+ image_processor_input_names = self.image_processor.model_input_names
+
+ # ColQwen doesn't process videos. Make a copy of list when removing
+ # otherwise `self.feature_extractor.model_input_names` is also modified
+ image_processor_input_names = [
+ name for name in image_processor_input_names if name not in ["pixel_values_videos", "video_grid_thw"]
+ ]
+ return tokenizer_input_names + image_processor_input_names
+
+ @property
+ def query_augmentation_token(self) -> str:
+ """
+ Return the query augmentation token.
+
+ Query augmentation buffers are used as reasoning buffers during inference.
+ """
+ return self.tokenizer.pad_token
+
+ def process_images(
+ self,
+ images: ImageInput | None = None,
+ **kwargs: Unpack[ColQwen2ProcessorKwargs],
+ ) -> BatchFeature:
+ """
+ Prepare for the model one or several image(s). This method is a wrapper around the `__call__` method of the ColQwen2Processor's
+ [`ColQwen2Processor.__call__`].
+
+ This method forwards the `images` and `kwargs` arguments to the image processor.
+
+ Args:
+ images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `list[PIL.Image.Image]`, `list[np.ndarray]`, `list[torch.Tensor]`):
+ The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
+ tensor. In case of a NumPy array/PyTorch tensor, each image should be of shape (C, H, W), where C is a
+ number of channels, H and W are image height and width.
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
+ If set, will return tensors of a particular framework. Acceptable values are:
+
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
+ - `'np'`: Return NumPy `np.ndarray` objects.
+
+ Returns:
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
+
+ - **input_ids** -- List of token ids to be fed to a model.
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
+ `None`).
+ - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
+ """
+ return self.__call__(images=images, **kwargs)
+
+ def process_queries(
+ self,
+ text: TextInput | list[TextInput],
+ **kwargs: Unpack[ColQwen2ProcessorKwargs],
+ ) -> BatchFeature:
+ """
+ Prepare for the model one or several texts. This method is a wrapper around the `__call__` method of the ColQwen2Processor's
+ [`ColQwen2Processor.__call__`].
+
+ This method forwards the `text` and `kwargs` arguments to the tokenizer.
+
+ Args:
+ text (`str`, `list[str]`, `list[list[str]]`):
+ The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
+ (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
+ `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
+ If set, will return tensors of a particular framework. Acceptable values are:
+
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
+ - `'np'`: Return NumPy `np.ndarray` objects.
+
+ Returns:
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
+
+ - **input_ids** -- List of token ids to be fed to a model.
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
+ `None`).
+ """
+ return self.__call__(text=text, **kwargs)
+
+ def score_retrieval(
+ self,
+ query_embeddings: Union["torch.Tensor", list["torch.Tensor"]],
+ passage_embeddings: Union["torch.Tensor", list["torch.Tensor"]],
+ batch_size: int = 128,
+ output_dtype: Optional["torch.dtype"] = None,
+ output_device: Union["torch.device", str] = "cpu",
+ ) -> "torch.Tensor":
+ """
+ Compute the late-interaction/MaxSim score (ColBERT-like) for the given multi-vector
+ query embeddings (`qs`) and passage embeddings (`ps`). For ColQwen2, a passage is the
+ image of a document page.
+
+ Because the embedding tensors are multi-vector and can thus have different shapes, they
+ should be fed as:
+ (1) a list of tensors, where the i-th tensor is of shape (sequence_length_i, embedding_dim)
+ (2) a single tensor of shape (n_passages, max_sequence_length, embedding_dim) -> usually
+ obtained by padding the list of tensors.
+
+ Args:
+ query_embeddings (`Union[torch.Tensor, list[torch.Tensor]`): Query embeddings.
+ passage_embeddings (`Union[torch.Tensor, list[torch.Tensor]`): Passage embeddings.
+ batch_size (`int`, *optional*, defaults to 128): Batch size for computing scores.
+ output_dtype (`torch.dtype`, *optional*, defaults to `torch.float32`): The dtype of the output tensor.
+ If `None`, the dtype of the input embeddings is used.
+ output_device (`torch.device` or `str`, *optional*, defaults to "cpu"): The device of the output tensor.
+
+ Returns:
+ `torch.Tensor`: A tensor of shape `(n_queries, n_passages)` containing the scores. The score
+ tensor is saved on the "cpu" device.
+ """
+
+ if len(query_embeddings) == 0:
+ raise ValueError("No queries provided")
+ if len(passage_embeddings) == 0:
+ raise ValueError("No passages provided")
+
+ if query_embeddings[0].device != passage_embeddings[0].device:
+ raise ValueError("Queries and passages must be on the same device")
+
+ if query_embeddings[0].dtype != passage_embeddings[0].dtype:
+ raise ValueError("Queries and passages must have the same dtype")
+
+ if output_dtype is None:
+ output_dtype = query_embeddings[0].dtype
+
+ scores: list[torch.Tensor] = []
+
+ for i in range(0, len(query_embeddings), batch_size):
+ batch_scores: list[torch.Tensor] = []
+ batch_queries = torch.nn.utils.rnn.pad_sequence(
+ query_embeddings[i : i + batch_size], batch_first=True, padding_value=0
+ )
+ for j in range(0, len(passage_embeddings), batch_size):
+ batch_passages = torch.nn.utils.rnn.pad_sequence(
+ passage_embeddings[j : j + batch_size], batch_first=True, padding_value=0
+ )
+ batch_scores.append(
+ torch.einsum("bnd,csd->bcns", batch_queries, batch_passages).max(dim=3)[0].sum(dim=2)
+ )
+ scores.append(torch.cat(batch_scores, dim=1).to(output_dtype).to(output_device))
+
+ return torch.cat(scores, dim=0)
+
+
+__all__ = ["ColQwen2Processor"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/conditional_detr/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/conditional_detr/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..98371606d8eedd6d4c930228300bacf9c808be79
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/conditional_detr/__init__.py
@@ -0,0 +1,29 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_conditional_detr import *
+ from .image_processing_conditional_detr import *
+ from .image_processing_pil_conditional_detr import *
+ from .modeling_conditional_detr import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/conditional_detr/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/conditional_detr/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f746d7758e32f7ae43318862cb0796a57ac2f624
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/conditional_detr/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/conditional_detr/__pycache__/configuration_conditional_detr.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/conditional_detr/__pycache__/configuration_conditional_detr.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..31969d76c264041d2957566df347e2a5e6899218
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/conditional_detr/__pycache__/configuration_conditional_detr.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/conditional_detr/__pycache__/image_processing_conditional_detr.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/conditional_detr/__pycache__/image_processing_conditional_detr.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8ae614915d6ae480abba699bf11145f47814a668
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/conditional_detr/__pycache__/image_processing_conditional_detr.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/conditional_detr/__pycache__/image_processing_pil_conditional_detr.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/conditional_detr/__pycache__/image_processing_pil_conditional_detr.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2a132fd3c7d31e6bab5d9204404f5439ad02bab1
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/conditional_detr/__pycache__/image_processing_pil_conditional_detr.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/conditional_detr/__pycache__/modular_conditional_detr.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/conditional_detr/__pycache__/modular_conditional_detr.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2edcfc52e40339c003b92bf085d676d4c6c12c66
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/conditional_detr/__pycache__/modular_conditional_detr.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/conditional_detr/configuration_conditional_detr.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/conditional_detr/configuration_conditional_detr.py
new file mode 100644
index 0000000000000000000000000000000000000000..12f7977d7423d532f32aef41dd197dadb22a117c
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/conditional_detr/configuration_conditional_detr.py
@@ -0,0 +1,119 @@
+# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Conditional DETR model configuration"""
+
+from huggingface_hub.dataclasses import strict
+
+from ...backbone_utils import consolidate_backbone_kwargs_to_config
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring
+from ..auto import AutoConfig
+
+
+@auto_docstring(checkpoint="microsoft/conditional-detr-resnet-50")
+@strict
+class ConditionalDetrConfig(PreTrainedConfig):
+ r"""
+ num_queries (`int`, *optional*, defaults to 100):
+ Number of object queries, i.e. detection slots. This is the maximal number of objects
+ [`ConditionalDetrModel`] can detect in a single image. For COCO, we recommend 100 queries.
+ auxiliary_loss (`bool`, *optional*, defaults to `False`):
+ Whether auxiliary decoding losses (loss at each decoder layer) are to be used.
+ position_embedding_type (`str`, *optional*, defaults to `"sine"`):
+ Type of position embeddings to be used on top of the image features. One of `"sine"` or `"learned"`.
+ dilation (`bool`, *optional*, defaults to `False`):
+ Whether to replace stride with dilation in the last convolutional block (DC5). Only supported when
+ `use_timm_backbone` = `True`.
+
+ Examples:
+
+ ```python
+ >>> from transformers import ConditionalDetrConfig, ConditionalDetrModel
+
+ >>> # Initializing a Conditional DETR microsoft/conditional-detr-resnet-50 style configuration
+ >>> configuration = ConditionalDetrConfig()
+
+ >>> # Initializing a model (with random weights) from the microsoft/conditional-detr-resnet-50 style configuration
+ >>> model = ConditionalDetrModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "conditional_detr"
+ sub_configs = {"backbone_config": AutoConfig}
+ keys_to_ignore_at_inference = ["past_key_values"]
+ attribute_map = {
+ "hidden_size": "d_model",
+ "num_attention_heads": "encoder_attention_heads",
+ "num_hidden_layers": "encoder_layers",
+ }
+
+ backbone_config: dict | PreTrainedConfig | None = None
+ num_channels: int = 3
+ num_queries: int = 300
+ encoder_layers: int = 6
+ encoder_ffn_dim: int = 2048
+ encoder_attention_heads: int = 8
+ decoder_layers: int = 6
+ decoder_ffn_dim: int = 2048
+ decoder_attention_heads: int = 8
+ encoder_layerdrop: float | int = 0.0
+ decoder_layerdrop: float | int = 0.0
+ is_encoder_decoder: bool = True
+ activation_function: str = "relu"
+ d_model: int = 256
+ dropout: float | int = 0.1
+ attention_dropout: float | int = 0.0
+ activation_dropout: float | int = 0.0
+ init_std: float = 0.02
+ init_xavier_std: float = 1.0
+ auxiliary_loss: bool = False
+ position_embedding_type: str = "sine"
+ dilation: bool = False
+ class_cost: int = 2
+ bbox_cost: int = 5
+ giou_cost: int = 2
+ mask_loss_coefficient: int = 1
+ dice_loss_coefficient: int = 1
+ cls_loss_coefficient: int = 2
+ bbox_loss_coefficient: int = 5
+ giou_loss_coefficient: int = 2
+ focal_alpha: float = 0.25
+
+ def __post_init__(self, **kwargs):
+ # Init timm backbone with hardcoded values for BC
+ backbone_kwargs = kwargs.get("backbone_kwargs", {})
+ timm_default_kwargs = {
+ "num_channels": backbone_kwargs.get("num_channels", self.num_channels),
+ "features_only": True,
+ "use_pretrained_backbone": False,
+ "out_indices": backbone_kwargs.get("out_indices", [1, 2, 3, 4]),
+ }
+ if self.dilation:
+ timm_default_kwargs["output_stride"] = backbone_kwargs.get("output_stride", 16)
+
+ self.backbone_config, kwargs = consolidate_backbone_kwargs_to_config(
+ backbone_config=self.backbone_config,
+ default_backbone="resnet50",
+ default_config_type="resnet",
+ default_config_kwargs={"out_features": ["stage4"]},
+ timm_default_kwargs=timm_default_kwargs,
+ **kwargs,
+ )
+
+ super().__post_init__(**kwargs)
+
+
+__all__ = ["ConditionalDetrConfig"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/conditional_detr/image_processing_conditional_detr.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/conditional_detr/image_processing_conditional_detr.py
new file mode 100644
index 0000000000000000000000000000000000000000..539fe152f6061bcfbc719903a5cb81f0bd680976
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/conditional_detr/image_processing_conditional_detr.py
@@ -0,0 +1,1083 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/conditional_detr/modular_conditional_detr.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_conditional_detr.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2022 Microsoft Research Asia and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import pathlib
+from typing import Any, Optional
+
+import numpy as np
+import torch
+from torch import nn
+from torchvision.io import read_image
+from torchvision.transforms.v2 import functional as tvF
+
+from ...image_processing_backends import TorchvisionBackend
+from ...image_processing_utils import BatchFeature, get_size_dict
+from ...image_transforms import (
+ center_to_corners_format,
+ corners_to_center_format,
+ get_size_with_aspect_ratio,
+ safe_squeeze,
+)
+from ...image_utils import (
+ IMAGENET_DEFAULT_MEAN,
+ IMAGENET_DEFAULT_STD,
+ AnnotationFormat,
+ AnnotationType,
+ ChannelDimension,
+ ImageInput,
+ PILImageResampling,
+ SizeDict,
+ get_image_size,
+ get_image_size_for_max_height_width,
+ get_max_height_width,
+ validate_annotations,
+)
+from ...processing_utils import ImagesKwargs, Unpack
+from ...utils import TensorType, auto_docstring, logging
+
+
+logger = logging.get_logger(__name__)
+
+
+class ConditionalDetrImageProcessorKwargs(ImagesKwargs, total=False):
+ r"""
+ format (`str`, *optional*, defaults to `AnnotationFormat.COCO_DETECTION`):
+ Data format of the annotations. One of "coco_detection" or "coco_panoptic".
+ do_convert_annotations (`bool`, *optional*, defaults to `True`):
+ Controls whether to convert the annotations to the format expected by the CONDITIONAL_DETR model. Converts the
+ bounding boxes to the format `(center_x, center_y, width, height)` and in the range `[0, 1]`.
+ Can be overridden by the `do_convert_annotations` parameter in the `preprocess` method.
+ """
+
+ format: str | AnnotationFormat
+ do_convert_annotations: bool
+
+
+SUPPORTED_ANNOTATION_FORMATS = (AnnotationFormat.COCO_DETECTION, AnnotationFormat.COCO_PANOPTIC)
+
+
+def binary_mask_to_rle(mask):
+ """
+ Converts given binary mask of shape `(height, width)` to the run-length encoding (RLE) format.
+
+ Args:
+ mask (`torch.Tensor` or `numpy.array`):
+ A binary mask tensor of shape `(height, width)` where 0 denotes background and 1 denotes the target
+ segment_id or class_id.
+ Returns:
+ `List`: Run-length encoded list of the binary mask. Refer to COCO API for more information about the RLE
+ format.
+ """
+ from ...utils import is_torch_tensor
+
+ if is_torch_tensor(mask):
+ mask = mask.numpy()
+
+ pixels = mask.flatten()
+ pixels = np.concatenate([[0], pixels, [0]])
+ runs = np.where(pixels[1:] != pixels[:-1])[0] + 1
+ runs[1::2] -= runs[::2]
+ return list(runs)
+
+
+def convert_segmentation_to_rle(segmentation):
+ """
+ Converts given segmentation map of shape `(height, width)` to the run-length encoding (RLE) format.
+
+ Args:
+ segmentation (`torch.Tensor` or `numpy.array`):
+ A segmentation map of shape `(height, width)` where each value denotes a segment or class id.
+ Returns:
+ `list[List]`: A list of lists, where each list is the run-length encoding of a segment / class id.
+ """
+ segment_ids = torch.unique(segmentation)
+
+ run_length_encodings = []
+ for idx in segment_ids:
+ mask = torch.where(segmentation == idx, 1, 0)
+ rle = binary_mask_to_rle(mask)
+ run_length_encodings.append(rle)
+
+ return run_length_encodings
+
+
+def remove_low_and_no_objects(masks, scores, labels, object_mask_threshold, num_labels):
+ """
+ Binarize the given masks using `object_mask_threshold`, it returns the associated values of `masks`, `scores` and
+ `labels`.
+
+ Args:
+ masks (`torch.Tensor`):
+ A tensor of shape `(num_queries, height, width)`.
+ scores (`torch.Tensor`):
+ A tensor of shape `(num_queries)`.
+ labels (`torch.Tensor`):
+ A tensor of shape `(num_queries)`.
+ object_mask_threshold (`float`):
+ A number between 0 and 1 used to binarize the masks.
+ Raises:
+ `ValueError`: Raised when the first dimension doesn't match in all input tensors.
+ Returns:
+ `tuple[`torch.Tensor`, `torch.Tensor`, `torch.Tensor`]`: The `masks`, `scores` and `labels` without the region
+ < `object_mask_threshold`.
+ """
+ if not (masks.shape[0] == scores.shape[0] == labels.shape[0]):
+ raise ValueError("mask, scores and labels must have the same shape!")
+
+ to_keep = labels.ne(num_labels) & (scores > object_mask_threshold)
+
+ return masks[to_keep], scores[to_keep], labels[to_keep]
+
+
+def check_segment_validity(mask_labels, mask_probs, k, mask_threshold=0.5, overlap_mask_area_threshold=0.8):
+ # Get the mask associated with the k class
+ mask_k = mask_labels == k
+ mask_k_area = mask_k.sum()
+
+ # Compute the area of all the stuff in query k
+ original_area = (mask_probs[k] >= mask_threshold).sum()
+ mask_exists = mask_k_area > 0 and original_area > 0
+
+ # Eliminate disconnected tiny segments
+ if mask_exists:
+ area_ratio = mask_k_area / original_area
+ if not area_ratio.item() > overlap_mask_area_threshold:
+ mask_exists = False
+
+ return mask_exists, mask_k
+
+
+def compute_segments(
+ mask_probs,
+ pred_scores,
+ pred_labels,
+ mask_threshold: float = 0.5,
+ overlap_mask_area_threshold: float = 0.8,
+ label_ids_to_fuse: set[int] | None = None,
+ target_size: tuple[int, int] | None = None,
+):
+ height = mask_probs.shape[1] if target_size is None else target_size[0]
+ width = mask_probs.shape[2] if target_size is None else target_size[1]
+
+ segmentation = torch.zeros((height, width), dtype=torch.int32, device=mask_probs.device)
+ segments: list[dict] = []
+
+ if target_size is not None:
+ mask_probs = nn.functional.interpolate(
+ mask_probs.unsqueeze(0), size=target_size, mode="bilinear", align_corners=False
+ )[0]
+
+ current_segment_id = 0
+
+ # Weigh each mask by its prediction score
+ mask_probs *= pred_scores.view(-1, 1, 1)
+ mask_labels = mask_probs.argmax(0) # [height, width]
+
+ # Keep track of instances of each class
+ stuff_memory_list: dict[str, int] = {}
+ for k in range(pred_labels.shape[0]):
+ pred_class = pred_labels[k].item()
+ should_fuse = pred_class in label_ids_to_fuse
+
+ # Check if mask exists and large enough to be a segment
+ mask_exists, mask_k = check_segment_validity(
+ mask_labels, mask_probs, k, mask_threshold, overlap_mask_area_threshold
+ )
+
+ if mask_exists:
+ if pred_class in stuff_memory_list:
+ current_segment_id = stuff_memory_list[pred_class]
+ else:
+ current_segment_id += 1
+
+ # Add current object segment to final segmentation map
+ segmentation[mask_k] = current_segment_id
+ segment_score = round(pred_scores[k].item(), 6)
+ segments.append(
+ {
+ "id": current_segment_id,
+ "label_id": pred_class,
+ "was_fused": should_fuse,
+ "score": segment_score,
+ }
+ )
+ if should_fuse:
+ stuff_memory_list[pred_class] = current_segment_id
+
+ return segmentation, segments
+
+
+# inspired by https://github.com/facebookresearch/conditional_detr/blob/master/datasets/coco.py#L33
+def convert_coco_poly_to_mask(segmentations, height: int, width: int, device: torch.device) -> torch.Tensor:
+ """
+ Convert a COCO polygon annotation to a mask.
+
+ Args:
+ segmentations (`list[list[float]]`):
+ List of polygons, each polygon represented by a list of x-y coordinates.
+ height (`int`):
+ Height of the mask.
+ width (`int`):
+ Width of the mask.
+ """
+ try:
+ from pycocotools import mask as coco_mask
+ except ImportError:
+ raise ImportError("Pycocotools is not installed in your environment.")
+
+ masks = []
+ for polygons in segmentations:
+ rles = coco_mask.frPyObjects(polygons, height, width)
+ mask = coco_mask.decode(rles)
+ if len(mask.shape) < 3:
+ mask = mask[..., None]
+ mask = torch.as_tensor(mask, dtype=torch.uint8, device=device)
+ mask = torch.any(mask, axis=2)
+ masks.append(mask)
+ if masks:
+ masks = torch.stack(masks, axis=0)
+ else:
+ masks = torch.zeros((0, height, width), dtype=torch.uint8, device=device)
+
+ return masks
+
+
+# inspired by https://github.com/facebookresearch/conditional_detr/blob/master/datasets/coco.py#L50
+def prepare_coco_detection_annotation(
+ image,
+ target,
+ return_segmentation_masks: bool = False,
+ input_data_format: ChannelDimension | str | None = None,
+):
+ """
+ Convert the target in COCO format into the format expected by CONDITIONAL_DETR.
+ """
+ image_height, image_width = image.size()[-2:]
+
+ image_id = target["image_id"]
+ image_id = torch.as_tensor([image_id], dtype=torch.int64, device=image.device)
+
+ # Get all COCO annotations for the given image.
+ annotations = target["annotations"]
+ classes = []
+ area = []
+ boxes = []
+ keypoints = []
+ for obj in annotations:
+ if "iscrowd" not in obj or obj["iscrowd"] == 0:
+ classes.append(obj["category_id"])
+ area.append(obj["area"])
+ boxes.append(obj["bbox"])
+ if "keypoints" in obj:
+ keypoints.append(obj["keypoints"])
+
+ classes = torch.as_tensor(classes, dtype=torch.int64, device=image.device)
+ area = torch.as_tensor(area, dtype=torch.float32, device=image.device)
+ iscrowd = torch.zeros_like(classes, dtype=torch.int64, device=image.device)
+ # guard against no boxes via resizing
+ boxes = torch.as_tensor(boxes, dtype=torch.float32, device=image.device).reshape(-1, 4)
+ boxes[:, 2:] += boxes[:, :2]
+ boxes[:, 0::2] = boxes[:, 0::2].clip(min=0, max=image_width)
+ boxes[:, 1::2] = boxes[:, 1::2].clip(min=0, max=image_height)
+
+ keep = (boxes[:, 3] > boxes[:, 1]) & (boxes[:, 2] > boxes[:, 0])
+
+ new_target = {
+ "image_id": image_id,
+ "class_labels": classes[keep],
+ "boxes": boxes[keep],
+ "area": area[keep],
+ "iscrowd": iscrowd[keep],
+ "orig_size": torch.as_tensor([int(image_height), int(image_width)], dtype=torch.int64, device=image.device),
+ }
+
+ if keypoints:
+ keypoints = torch.as_tensor(keypoints, dtype=torch.float32, device=image.device)
+ # Apply the keep mask here to filter the relevant annotations
+ keypoints = keypoints[keep]
+ num_keypoints = keypoints.shape[0]
+ keypoints = keypoints.reshape((-1, 3)) if num_keypoints else keypoints
+ new_target["keypoints"] = keypoints
+
+ if return_segmentation_masks:
+ segmentation_masks = [obj["segmentation"] for obj in annotations]
+ masks = convert_coco_poly_to_mask(segmentation_masks, image_height, image_width, device=image.device)
+ new_target["masks"] = masks[keep]
+
+ return new_target
+
+
+def masks_to_boxes(masks: torch.Tensor) -> torch.Tensor:
+ """
+ Compute the bounding boxes around the provided panoptic segmentation masks.
+
+ Args:
+ masks: masks in format `[number_masks, height, width]` where N is the number of masks
+
+ Returns:
+ boxes: bounding boxes in format `[number_masks, 4]` in xyxy format
+ """
+ if masks.numel() == 0:
+ return torch.zeros((0, 4), device=masks.device)
+
+ h, w = masks.shape[-2:]
+ y = torch.arange(0, h, dtype=torch.float32, device=masks.device)
+ x = torch.arange(0, w, dtype=torch.float32, device=masks.device)
+ # see https://github.com/pytorch/pytorch/issues/50276
+ y, x = torch.meshgrid(y, x, indexing="ij")
+
+ x_mask = masks * torch.unsqueeze(x, 0)
+ x_max = x_mask.view(x_mask.shape[0], -1).max(-1)[0]
+ x_min = (
+ torch.where(masks, x.unsqueeze(0), torch.tensor(1e8, device=masks.device)).view(masks.shape[0], -1).min(-1)[0]
+ )
+
+ y_mask = masks * torch.unsqueeze(y, 0)
+ y_max = y_mask.view(y_mask.shape[0], -1).max(-1)[0]
+ y_min = (
+ torch.where(masks, y.unsqueeze(0), torch.tensor(1e8, device=masks.device)).view(masks.shape[0], -1).min(-1)[0]
+ )
+
+ return torch.stack([x_min, y_min, x_max, y_max], 1)
+
+
+# 2 functions below adapted from https://github.com/cocodataset/panopticapi/blob/master/panopticapi/utils.py
+# Copyright (c) 2018, Alexander Kirillov
+# All rights reserved.
+def rgb_to_id(color):
+ """
+ Converts RGB color to unique ID.
+ """
+ if isinstance(color, torch.Tensor) and len(color.shape) == 3:
+ if color.dtype == torch.uint8:
+ color = color.to(torch.int32)
+ return color[:, :, 0] + 256 * color[:, :, 1] + 256 * 256 * color[:, :, 2]
+ return int(color[0] + 256 * color[1] + 256 * 256 * color[2])
+
+
+def prepare_coco_panoptic_annotation(
+ image: torch.Tensor,
+ target: dict,
+ masks_path: str | pathlib.Path,
+ return_masks: bool = True,
+ input_data_format: ChannelDimension | str = None,
+) -> dict:
+ """
+ Prepare a coco panoptic annotation for CONDITIONAL_DETR.
+ """
+ image_height, image_width = get_image_size(image, channel_dim=input_data_format)
+ annotation_path = pathlib.Path(masks_path) / target["file_name"]
+
+ new_target = {}
+ new_target["image_id"] = torch.as_tensor(
+ [target["image_id"] if "image_id" in target else target["id"]], dtype=torch.int64, device=image.device
+ )
+ new_target["size"] = torch.as_tensor([image_height, image_width], dtype=torch.int64, device=image.device)
+ new_target["orig_size"] = torch.as_tensor([image_height, image_width], dtype=torch.int64, device=image.device)
+
+ if "segments_info" in target:
+ masks = read_image(annotation_path).permute(1, 2, 0).to(dtype=torch.int32, device=image.device)
+ masks = rgb_to_id(masks)
+
+ ids = torch.as_tensor([segment_info["id"] for segment_info in target["segments_info"]], device=image.device)
+ masks = masks == ids[:, None, None]
+ masks = masks.to(torch.bool)
+ if return_masks:
+ new_target["masks"] = masks
+ new_target["boxes"] = masks_to_boxes(masks)
+ new_target["class_labels"] = torch.as_tensor(
+ [segment_info["category_id"] for segment_info in target["segments_info"]],
+ dtype=torch.int64,
+ device=image.device,
+ )
+ new_target["iscrowd"] = torch.as_tensor(
+ [segment_info["iscrowd"] for segment_info in target["segments_info"]],
+ dtype=torch.int64,
+ device=image.device,
+ )
+ new_target["area"] = torch.as_tensor(
+ [segment_info["area"] for segment_info in target["segments_info"]],
+ dtype=torch.float32,
+ device=image.device,
+ )
+
+ return new_target
+
+
+@auto_docstring
+class ConditionalDetrImageProcessor(TorchvisionBackend):
+ valid_kwargs = ConditionalDetrImageProcessorKwargs
+ resample = PILImageResampling.BILINEAR
+ image_mean = IMAGENET_DEFAULT_MEAN
+ image_std = IMAGENET_DEFAULT_STD
+ format = AnnotationFormat.COCO_DETECTION
+ do_resize = True
+ do_rescale = True
+ do_normalize = True
+ do_pad = True
+ size = {"shortest_edge": 800, "longest_edge": 1333}
+ default_to_square = False
+ model_input_names = ["pixel_values", "pixel_mask"]
+
+ def __init__(self, **kwargs: Unpack[ConditionalDetrImageProcessorKwargs]) -> None:
+ kwargs.setdefault("do_pad", kwargs.pop("pad_and_return_pixel_mask", self.do_pad))
+
+ size = kwargs.pop("size", None)
+ max_size = None if size is None else kwargs.pop("max_size", 1333)
+ size = size if size is not None else {"shortest_edge": 800, "longest_edge": 1333}
+ # Convert size dict for backwards compat with max_size parameter
+ kwargs["size"] = get_size_dict(size, max_size=max_size, default_to_square=False)
+
+ # Backwards compatibility
+ do_convert_annotations = kwargs.get("do_convert_annotations")
+ do_normalize = kwargs.get("do_normalize")
+ if do_convert_annotations is None and getattr(self, "do_convert_annotations", None) is None:
+ self.do_convert_annotations = do_normalize if do_normalize is not None else self.do_normalize
+
+ super().__init__(**kwargs)
+
+ def prepare_annotation(
+ self,
+ image: torch.Tensor,
+ target: dict,
+ format: AnnotationFormat | None = None,
+ return_segmentation_masks: bool | None = None,
+ masks_path: str | pathlib.Path | None = None,
+ input_data_format: str | ChannelDimension | None = None,
+ ) -> dict:
+ """
+ Prepare an annotation for feeding into CONDITIONAL_DETR model.
+ """
+ format = format if format is not None else self.format
+
+ if format == AnnotationFormat.COCO_DETECTION:
+ return_segmentation_masks = False if return_segmentation_masks is None else return_segmentation_masks
+ target = prepare_coco_detection_annotation(
+ image, target, return_segmentation_masks, input_data_format=input_data_format
+ )
+ elif format == AnnotationFormat.COCO_PANOPTIC:
+ return_segmentation_masks = True if return_segmentation_masks is None else return_segmentation_masks
+ target = prepare_coco_panoptic_annotation(
+ image,
+ target,
+ masks_path=masks_path,
+ return_masks=return_segmentation_masks,
+ input_data_format=input_data_format,
+ )
+ else:
+ raise ValueError(f"Format {format} is not supported.")
+ return target
+
+ def resize(
+ self,
+ image: torch.Tensor,
+ size: SizeDict,
+ resample: Optional["PILImageResampling | tvF.InterpolationMode | int"] = None,
+ **kwargs,
+ ) -> torch.Tensor:
+ """
+ Resize the image to the given size. Size can be `min_size` (scalar) or `(height, width)` tuple. If size is an
+ int, smaller edge of the image will be matched to this number.
+
+ Args:
+ image (`torch.Tensor`):
+ Image to resize.
+ size (`SizeDict`):
+ Size of the image's `(height, width)` dimensions after resizing. Available options are:
+ - `{"height": int, "width": int}`: The image will be resized to the exact size `(height, width)`.
+ Do NOT keep the aspect ratio.
+ - `{"shortest_edge": int, "longest_edge": int}`: The image will be resized to a maximum size respecting
+ the aspect ratio and keeping the shortest edge less or equal to `shortest_edge` and the longest edge
+ less or equal to `longest_edge`.
+ - `{"max_height": int, "max_width": int}`: The image will be resized to the maximum size respecting the
+ aspect ratio and keeping the height less or equal to `max_height` and the width less or equal to
+ `max_width`.
+ resample (`PILImageResampling | tvF.InterpolationMode | int`, *optional*, defaults to `PILImageResampling.BILINEAR`):
+ Resampling filter to use if resizing the image.
+ """
+ if size.shortest_edge and size.longest_edge:
+ # Resize the image so that the shortest edge or the longest edge is of the given size
+ # while maintaining the aspect ratio of the original image.
+ new_size = get_size_with_aspect_ratio(image.shape[-2:], size.shortest_edge, size.longest_edge)
+ elif size.max_height and size.max_width:
+ new_size = get_image_size_for_max_height_width(image.shape[-2:], size.max_height, size.max_width)
+ elif size.height and size.width:
+ new_size = (size.height, size.width)
+ else:
+ raise ValueError(
+ f"Size must contain 'height' and 'width' keys or 'shortest_edge' and 'longest_edge' keys. Got {size}."
+ )
+
+ image = super().resize(
+ image, size=SizeDict(height=new_size[0], width=new_size[1]), resample=resample, **kwargs
+ )
+ return image
+
+ def resize_annotation(
+ self,
+ annotation: dict[str, Any],
+ orig_size: tuple[int, int],
+ target_size: tuple[int, int],
+ threshold: float = 0.5,
+ resample: Optional["PILImageResampling | tvF.InterpolationMode | int"] = PILImageResampling.NEAREST,
+ ):
+ """
+ Resizes an annotation to a target size.
+
+ Args:
+ annotation (`dict[str, Any]`):
+ The annotation dictionary.
+ orig_size (`tuple[int, int]`):
+ The original size of the input image.
+ target_size (`tuple[int, int]`):
+ The target size of the image, as returned by the preprocessing `resize` step.
+ threshold (`float`, *optional*, defaults to 0.5):
+ The threshold used to binarize the segmentation masks.
+ resample (`PILImageResampling | tvF.InterpolationMode | int`, defaults to `tvF.InterpolationMode.NEAREST_EXACT`):
+ The resampling filter to use when resizing the masks.
+ """
+ ratio_height, ratio_width = [target / orig for target, orig in zip(target_size, orig_size)]
+
+ new_annotation = {}
+ new_annotation["size"] = target_size
+
+ for key, value in annotation.items():
+ if key == "boxes":
+ boxes = value
+ scaled_boxes = boxes * torch.as_tensor(
+ [ratio_width, ratio_height, ratio_width, ratio_height], dtype=torch.float32, device=boxes.device
+ )
+ new_annotation["boxes"] = scaled_boxes
+ elif key == "area":
+ area = value
+ scaled_area = area * (ratio_width * ratio_height)
+ new_annotation["area"] = scaled_area
+ elif key == "masks":
+ masks = value[:, None]
+ masks = [
+ super(ConditionalDetrImageProcessor, self).resize(
+ mask, size=SizeDict(height=target_size[0], width=target_size[1]), resample=resample
+ )
+ for mask in masks
+ ]
+ masks = torch.stack(masks).to(torch.float32)
+ masks = masks[:, 0] > threshold
+ new_annotation["masks"] = masks
+ elif key == "size":
+ new_annotation["size"] = target_size
+ else:
+ new_annotation[key] = value
+
+ return new_annotation
+
+ def normalize_annotation(self, annotation: dict, image_size: tuple[int, int]) -> dict:
+ image_height, image_width = image_size
+ norm_annotation = {}
+ for key, value in annotation.items():
+ if key == "boxes":
+ boxes = value
+ boxes = corners_to_center_format(boxes)
+ boxes /= torch.as_tensor(
+ [image_width, image_height, image_width, image_height], dtype=torch.float32, device=boxes.device
+ )
+ norm_annotation[key] = boxes
+ else:
+ norm_annotation[key] = value
+ return norm_annotation
+
+ def _update_annotation_for_padded_image(
+ self,
+ annotation: dict,
+ input_image_size: tuple[int, int],
+ output_image_size: tuple[int, int],
+ padding,
+ update_bboxes,
+ ) -> dict:
+ """
+ Update the annotation for a padded image.
+ """
+ new_annotation = {}
+ new_annotation["size"] = output_image_size
+ ratio_height, ratio_width = (input / output for output, input in zip(output_image_size, input_image_size))
+
+ for key, value in annotation.items():
+ if key == "masks":
+ masks = value
+ masks = tvF.pad(
+ masks,
+ padding,
+ fill=0,
+ )
+ masks = safe_squeeze(masks, 1)
+ new_annotation["masks"] = masks
+ elif key == "boxes" and update_bboxes:
+ boxes = value
+ boxes *= torch.as_tensor([ratio_width, ratio_height, ratio_width, ratio_height], device=boxes.device)
+ new_annotation["boxes"] = boxes
+ elif key == "size":
+ new_annotation["size"] = output_image_size
+ else:
+ new_annotation[key] = value
+ return new_annotation
+
+ def pad(
+ self,
+ image: torch.Tensor,
+ padded_size: tuple[int, int],
+ annotation: dict[str, Any] | None = None,
+ update_bboxes: bool = True,
+ fill: int = 0,
+ ):
+ original_size = image.size()[-2:]
+ padding_bottom = padded_size[0] - original_size[0]
+ padding_right = padded_size[1] - original_size[1]
+ if padding_bottom < 0 or padding_right < 0:
+ raise ValueError(
+ f"Padding dimensions are negative. Please make sure that the padded size is larger than the "
+ f"original size. Got padded size: {padded_size}, original size: {original_size}."
+ )
+ if original_size != padded_size:
+ padding = [0, 0, padding_right, padding_bottom]
+ image = tvF.pad(image, padding, fill=fill)
+ if annotation is not None:
+ annotation = self._update_annotation_for_padded_image(
+ annotation, original_size, padded_size, padding, update_bboxes
+ )
+
+ # Make a pixel mask for the image, where 1 indicates a valid pixel and 0 indicates padding.
+ pixel_mask = torch.zeros(padded_size, dtype=torch.int64, device=image.device)
+ pixel_mask[: original_size[0], : original_size[1]] = 1
+
+ return image, pixel_mask, annotation
+
+ @auto_docstring
+ def preprocess(
+ self,
+ images: ImageInput,
+ annotations: AnnotationType | list[AnnotationType] | None = None,
+ return_segmentation_masks: bool | None = None,
+ masks_path: str | pathlib.Path | None = None,
+ **kwargs: Unpack[ConditionalDetrImageProcessorKwargs],
+ ) -> BatchFeature:
+ r"""
+ annotations (`AnnotationType` or `list[AnnotationType]`, *optional*):
+ Annotations to transform according to the padding that is applied to the images.
+ return_segmentation_masks (`bool`, *optional*, defaults to `self.return_segmentation_masks`):
+ Whether to return segmentation masks.
+ masks_path (`str` or `pathlib.Path`, *optional*):
+ Path to the directory containing the segmentation masks.
+ """
+ return super().preprocess(images, annotations, return_segmentation_masks, masks_path, **kwargs)
+
+ def _preprocess(
+ self,
+ images: list["torch.Tensor"],
+ annotations: AnnotationType | list[AnnotationType] | None,
+ return_segmentation_masks: bool,
+ masks_path: str | pathlib.Path | None,
+ do_resize: bool,
+ size: SizeDict,
+ resample: "PILImageResampling | tvF.InterpolationMode | int | None",
+ do_rescale: bool,
+ rescale_factor: float,
+ do_normalize: bool,
+ do_convert_annotations: bool,
+ image_mean: float | list[float] | None,
+ image_std: float | list[float] | None,
+ do_pad: bool,
+ pad_size: SizeDict | None,
+ format: str | AnnotationFormat | None,
+ return_tensors: str | TensorType | None,
+ **kwargs,
+ ) -> BatchFeature:
+ """
+ Preprocess an image or a batch of images so that it can be used by the model.
+ """
+ if annotations is not None and isinstance(annotations, dict):
+ annotations = [annotations]
+
+ if annotations is not None and len(images) != len(annotations):
+ raise ValueError(
+ f"The number of images ({len(images)}) and annotations ({len(annotations)}) do not match."
+ )
+
+ format = AnnotationFormat(format)
+ if annotations is not None:
+ validate_annotations(format, SUPPORTED_ANNOTATION_FORMATS, annotations)
+
+ if (
+ masks_path is not None
+ and format == AnnotationFormat.COCO_PANOPTIC
+ and not isinstance(masks_path, (pathlib.Path, str))
+ ):
+ raise ValueError(
+ "The path to the directory containing the mask PNG files should be provided as a"
+ f" `pathlib.Path` or string object, but is {type(masks_path)} instead."
+ )
+
+ data = {}
+
+ processed_images = []
+ processed_annotations = []
+ pixel_masks = [] # Initialize pixel_masks here
+ for image, annotation in zip(images, annotations if annotations is not None else [None] * len(images)):
+ # prepare (COCO annotations as a list of Dict -> CONDITIONAL_DETR target as a single Dict per image)
+ if annotations is not None:
+ annotation = self.prepare_annotation(
+ image,
+ annotation,
+ format,
+ return_segmentation_masks=return_segmentation_masks,
+ masks_path=masks_path,
+ input_data_format=ChannelDimension.FIRST,
+ )
+
+ if do_resize:
+ resized_image = self.resize(image, size=size, resample=resample)
+ if annotations is not None:
+ annotation = self.resize_annotation(
+ annotation,
+ orig_size=image.size()[-2:],
+ target_size=resized_image.size()[-2:],
+ )
+ image = resized_image
+ # Fused rescale and normalize
+ image = self.rescale_and_normalize(image, do_rescale, rescale_factor, do_normalize, image_mean, image_std)
+ if do_convert_annotations and annotations is not None:
+ annotation = self.normalize_annotation(annotation, get_image_size(image, ChannelDimension.FIRST))
+
+ processed_images.append(image)
+ processed_annotations.append(annotation)
+ images = processed_images
+ annotations = processed_annotations if annotations is not None else None
+
+ if do_pad:
+ # depends on all resized image shapes so we need another loop
+ if pad_size is not None:
+ padded_size = (pad_size.height, pad_size.width)
+ else:
+ padded_size = get_max_height_width(images)
+
+ padded_images = []
+ padded_annotations = []
+ for image, annotation in zip(images, annotations if annotations is not None else [None] * len(images)):
+ # Pads images and returns their mask: {'pixel_values': ..., 'pixel_mask': ...}
+ if padded_size == image.size()[-2:]:
+ padded_images.append(image)
+ pixel_masks.append(torch.ones(padded_size, dtype=torch.int64, device=image.device))
+ padded_annotations.append(annotation)
+ continue
+ image, pixel_mask, annotation = self.pad(
+ image, padded_size, annotation=annotation, update_bboxes=do_convert_annotations
+ )
+ padded_images.append(image)
+ padded_annotations.append(annotation)
+ pixel_masks.append(pixel_mask)
+ images = padded_images
+ annotations = padded_annotations if annotations is not None else None
+ data.update({"pixel_mask": torch.stack(pixel_masks, dim=0)})
+
+ data.update({"pixel_values": torch.stack(images, dim=0)})
+ encoded_inputs = BatchFeature(data, tensor_type=return_tensors)
+ if annotations is not None:
+ encoded_inputs["labels"] = [
+ BatchFeature(annotation, tensor_type=return_tensors) for annotation in annotations
+ ]
+ return encoded_inputs
+
+ def post_process_object_detection(
+ self, outputs, threshold: float = 0.5, target_sizes: TensorType | list[tuple] = None, top_k: int = 100
+ ):
+ """
+ Converts the raw output of [`ConditionalDetrForObjectDetection`] into final bounding boxes in (top_left_x,
+ top_left_y, bottom_right_x, bottom_right_y) format. Only supports PyTorch.
+
+ Args:
+ outputs ([`ConditionalDetrObjectDetectionOutput`]):
+ Raw outputs of the model.
+ threshold (`float`, *optional*):
+ Score threshold to keep object detection predictions.
+ target_sizes (`torch.Tensor` or `list[tuple[int, int]]`, *optional*):
+ Tensor of shape `(batch_size, 2)` or list of tuples (`tuple[int, int]`) containing the target size
+ (height, width) of each image in the batch. If left to None, predictions will not be resized.
+ top_k (`int`, *optional*, defaults to 100):
+ Keep only top k bounding boxes before filtering by thresholding.
+
+ Returns:
+ `list[Dict]`: A list of dictionaries, each dictionary containing the scores, labels and boxes for an image
+ in the batch as predicted by the model.
+ """
+ out_logits, out_bbox = outputs.logits, outputs.pred_boxes
+
+ if target_sizes is not None:
+ if len(out_logits) != len(target_sizes):
+ raise ValueError(
+ "Make sure that you pass in as many target sizes as the batch dimension of the logits"
+ )
+
+ prob = out_logits.sigmoid()
+ prob = prob.view(out_logits.shape[0], -1)
+ k_value = min(top_k, prob.size(1))
+ topk_values, topk_indexes = torch.topk(prob, k_value, dim=1)
+ scores = topk_values
+ topk_boxes = torch.div(topk_indexes, out_logits.shape[2], rounding_mode="floor")
+ labels = topk_indexes % out_logits.shape[2]
+ boxes = center_to_corners_format(out_bbox)
+ boxes = torch.gather(boxes, 1, topk_boxes.unsqueeze(-1).repeat(1, 1, 4))
+
+ # and from relative [0, 1] to absolute [0, height] coordinates
+ if target_sizes is not None:
+ if isinstance(target_sizes, list):
+ img_h = torch.Tensor([i[0] for i in target_sizes])
+ img_w = torch.Tensor([i[1] for i in target_sizes])
+ else:
+ img_h, img_w = target_sizes.unbind(1)
+ scale_fct = torch.stack([img_w, img_h, img_w, img_h], dim=1).to(boxes.device)
+ boxes = boxes * scale_fct[:, None, :]
+
+ results = []
+ for s, l, b in zip(scores, labels, boxes):
+ score = s[s > threshold]
+ label = l[s > threshold]
+ box = b[s > threshold]
+ results.append({"scores": score, "labels": label, "boxes": box})
+
+ return results
+
+ def post_process_semantic_segmentation(self, outputs, target_sizes: list[tuple[int, int]] | None = None):
+ """
+ Converts the output of [`ConditionalDetrForSegmentation`] into semantic segmentation maps. Only supports PyTorch.
+
+ Args:
+ outputs ([`ConditionalDetrForSegmentation`]):
+ Raw outputs of the model.
+ target_sizes (`list[tuple[int, int]]`, *optional*):
+ A list of tuples (`tuple[int, int]`) containing the target size (height, width) of each image in the
+ batch. If unset, predictions will not be resized.
+ Returns:
+ `list[torch.Tensor]`:
+ A list of length `batch_size`, where each item is a semantic segmentation map of shape (height, width)
+ corresponding to the target_sizes entry (if `target_sizes` is specified). Each entry of each
+ `torch.Tensor` correspond to a semantic class id.
+ """
+ class_queries_logits = outputs.logits # [batch_size, num_queries, num_classes]
+ masks_queries_logits = outputs.pred_masks # [batch_size, num_queries, height, width]
+
+ # Conditional DETR does not have a null class, so we use all classes
+ masks_classes = class_queries_logits.softmax(dim=-1)
+ masks_probs = masks_queries_logits.sigmoid() # [batch_size, num_queries, height, width]
+
+ # Semantic segmentation logits of shape (batch_size, num_classes, height, width)
+ segmentation = torch.einsum("bqc, bqhw -> bchw", masks_classes, masks_probs)
+ batch_size = class_queries_logits.shape[0]
+
+ # Resize logits and compute semantic segmentation maps
+ if target_sizes is not None:
+ if batch_size != len(target_sizes):
+ raise ValueError(
+ "Make sure that you pass in as many target sizes as the batch dimension of the logits"
+ )
+
+ semantic_segmentation = []
+ for idx in range(batch_size):
+ resized_logits = nn.functional.interpolate(
+ segmentation[idx].unsqueeze(dim=0), size=target_sizes[idx], mode="bilinear", align_corners=False
+ )
+ semantic_map = resized_logits[0].argmax(dim=0)
+ semantic_segmentation.append(semantic_map)
+ else:
+ semantic_segmentation = segmentation.argmax(dim=1)
+ semantic_segmentation = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0])]
+
+ return semantic_segmentation
+
+ def post_process_instance_segmentation(
+ self,
+ outputs,
+ threshold: float = 0.5,
+ mask_threshold: float = 0.5,
+ overlap_mask_area_threshold: float = 0.8,
+ target_sizes: list[tuple[int, int]] | None = None,
+ return_coco_annotation: bool | None = False,
+ ) -> list[dict]:
+ """
+ Converts the output of [`ConditionalDetrForSegmentation`] into instance segmentation predictions. Only supports PyTorch.
+
+ Args:
+ outputs ([`ConditionalDetrForSegmentation`]):
+ Raw outputs of the model.
+ threshold (`float`, *optional*, defaults to 0.5):
+ The probability score threshold to keep predicted instance masks.
+ mask_threshold (`float`, *optional*, defaults to 0.5):
+ Threshold to use when turning the predicted masks into binary values.
+ overlap_mask_area_threshold (`float`, *optional*, defaults to 0.8):
+ The overlap mask area threshold to merge or discard small disconnected parts within each binary
+ instance mask.
+ target_sizes (`list[Tuple]`, *optional*):
+ List of length (batch_size), where each list item (`tuple[int, int]]`) corresponds to the requested
+ final size (height, width) of each prediction. If unset, predictions will not be resized.
+ return_coco_annotation (`bool`, *optional*):
+ Defaults to `False`. If set to `True`, segmentation maps are returned in COCO run-length encoding (RLE)
+ format.
+ Returns:
+ `list[Dict]`: A list of dictionaries, one per image, each dictionary containing two keys:
+ - **segmentation** -- A tensor of shape `(height, width)` where each pixel represents a `segment_id` or
+ `list[List]` run-length encoding (RLE) of the segmentation map if return_coco_annotation is set to
+ `True`. Set to `None` if no mask if found above `threshold`.
+ - **segments_info** -- A dictionary that contains additional information on each segment.
+ - **id** -- An integer representing the `segment_id`.
+ - **label_id** -- An integer representing the label / semantic class id corresponding to `segment_id`.
+ - **score** -- Prediction score of segment with `segment_id`.
+ """
+ class_queries_logits = outputs.logits # [batch_size, num_queries, num_classes+1]
+ masks_queries_logits = outputs.pred_masks # [batch_size, num_queries, height, width]
+
+ batch_size = class_queries_logits.shape[0]
+ num_labels = class_queries_logits.shape[-1] - 1
+
+ mask_probs = masks_queries_logits.sigmoid() # [batch_size, num_queries, height, width]
+
+ # Predicted label and score of each query (batch_size, num_queries)
+ pred_scores, pred_labels = nn.functional.softmax(class_queries_logits, dim=-1).max(-1)
+
+ # Loop over items in batch size
+ results: list[dict[str, TensorType]] = []
+
+ for i in range(batch_size):
+ mask_probs_item, pred_scores_item, pred_labels_item = remove_low_and_no_objects(
+ mask_probs[i], pred_scores[i], pred_labels[i], threshold, num_labels
+ )
+
+ # No mask found
+ if mask_probs_item.shape[0] <= 0:
+ height, width = target_sizes[i] if target_sizes is not None else mask_probs_item.shape[1:]
+ segmentation = torch.zeros((height, width)) - 1
+ results.append({"segmentation": segmentation, "segments_info": []})
+ continue
+
+ # Get segmentation map and segment information of batch item
+ target_size = target_sizes[i] if target_sizes is not None else None
+ segmentation, segments = compute_segments(
+ mask_probs=mask_probs_item,
+ pred_scores=pred_scores_item,
+ pred_labels=pred_labels_item,
+ mask_threshold=mask_threshold,
+ overlap_mask_area_threshold=overlap_mask_area_threshold,
+ label_ids_to_fuse=[],
+ target_size=target_size,
+ )
+
+ # Return segmentation map in run-length encoding (RLE) format
+ if return_coco_annotation:
+ segmentation = convert_segmentation_to_rle(segmentation)
+
+ results.append({"segmentation": segmentation, "segments_info": segments})
+ return results
+
+ def post_process_panoptic_segmentation(
+ self,
+ outputs,
+ threshold: float = 0.5,
+ mask_threshold: float = 0.5,
+ overlap_mask_area_threshold: float = 0.8,
+ label_ids_to_fuse: set[int] | None = None,
+ target_sizes: list[tuple[int, int]] | None = None,
+ ) -> list[dict]:
+ """
+ Converts the output of [`ConditionalDetrForSegmentation`] into image panoptic segmentation predictions. Only supports
+ PyTorch.
+
+ Args:
+ outputs ([`ConditionalDetrForSegmentation`]):
+ The outputs from [`ConditionalDetrForSegmentation`].
+ threshold (`float`, *optional*, defaults to 0.5):
+ The probability score threshold to keep predicted instance masks.
+ mask_threshold (`float`, *optional*, defaults to 0.5):
+ Threshold to use when turning the predicted masks into binary values.
+ overlap_mask_area_threshold (`float`, *optional*, defaults to 0.8):
+ The overlap mask area threshold to merge or discard small disconnected parts within each binary
+ instance mask.
+ label_ids_to_fuse (`Set[int]`, *optional*):
+ The labels in this state will have all their instances be fused together. For instance we could say
+ there can only be one sky in an image, but several persons, so the label ID for sky would be in that
+ set, but not the one for person.
+ target_sizes (`list[Tuple]`, *optional*):
+ List of length (batch_size), where each list item (`tuple[int, int]]`) corresponds to the requested
+ final size (height, width) of each prediction in batch. If unset, predictions will not be resized.
+ Returns:
+ `list[Dict]`: A list of dictionaries, one per image, each dictionary containing two keys:
+ - **segmentation** -- a tensor of shape `(height, width)` where each pixel represents a `segment_id` or
+ `None` if no mask if found above `threshold`. If `target_sizes` is specified, segmentation is resized to
+ the corresponding `target_sizes` entry.
+ - **segments_info** -- A dictionary that contains additional information on each segment.
+ - **id** -- an integer representing the `segment_id`.
+ - **label_id** -- An integer representing the label / semantic class id corresponding to `segment_id`.
+ - **was_fused** -- a boolean, `True` if `label_id` was in `label_ids_to_fuse`, `False` otherwise.
+ Multiple instances of the same class / label were fused and assigned a single `segment_id`.
+ - **score** -- Prediction score of segment with `segment_id`.
+ """
+
+ if label_ids_to_fuse is None:
+ logger.warning_once("`label_ids_to_fuse` unset. No instance will be fused.")
+ label_ids_to_fuse = set()
+
+ class_queries_logits = outputs.logits # [batch_size, num_queries, num_classes+1]
+ masks_queries_logits = outputs.pred_masks # [batch_size, num_queries, height, width]
+
+ batch_size = class_queries_logits.shape[0]
+ num_labels = class_queries_logits.shape[-1] - 1
+
+ mask_probs = masks_queries_logits.sigmoid() # [batch_size, num_queries, height, width]
+
+ # Predicted label and score of each query (batch_size, num_queries)
+ pred_scores, pred_labels = nn.functional.softmax(class_queries_logits, dim=-1).max(-1)
+
+ # Loop over items in batch size
+ results: list[dict[str, TensorType]] = []
+
+ for i in range(batch_size):
+ mask_probs_item, pred_scores_item, pred_labels_item = remove_low_and_no_objects(
+ mask_probs[i], pred_scores[i], pred_labels[i], threshold, num_labels
+ )
+
+ # No mask found
+ if mask_probs_item.shape[0] <= 0:
+ height, width = target_sizes[i] if target_sizes is not None else mask_probs_item.shape[1:]
+ segmentation = torch.zeros((height, width)) - 1
+ results.append({"segmentation": segmentation, "segments_info": []})
+ continue
+
+ # Get segmentation map and segment information of batch item
+ target_size = target_sizes[i] if target_sizes is not None else None
+ segmentation, segments = compute_segments(
+ mask_probs=mask_probs_item,
+ pred_scores=pred_scores_item,
+ pred_labels=pred_labels_item,
+ mask_threshold=mask_threshold,
+ overlap_mask_area_threshold=overlap_mask_area_threshold,
+ label_ids_to_fuse=label_ids_to_fuse,
+ target_size=target_size,
+ )
+
+ results.append({"segmentation": segmentation, "segments_info": segments})
+ return results
+
+
+__all__ = ["ConditionalDetrImageProcessor"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/conditional_detr/image_processing_pil_conditional_detr.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/conditional_detr/image_processing_pil_conditional_detr.py
new file mode 100644
index 0000000000000000000000000000000000000000..30740114d5f06ee6f93eabe2f73f4096571595d9
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/conditional_detr/image_processing_pil_conditional_detr.py
@@ -0,0 +1,1135 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/conditional_detr/modular_conditional_detr.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_conditional_detr.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2022 Microsoft Research Asia and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import pathlib
+from typing import Any, Optional
+
+import numpy as np
+
+from ...image_processing_backends import PilBackend
+from ...image_processing_utils import BatchFeature
+from ...image_transforms import (
+ PaddingMode,
+ center_to_corners_format,
+ corners_to_center_format,
+ get_size_with_aspect_ratio,
+ pad,
+ resize,
+ safe_squeeze,
+)
+from ...image_utils import (
+ IMAGENET_DEFAULT_MEAN,
+ IMAGENET_DEFAULT_STD,
+ AnnotationFormat,
+ AnnotationType,
+ ChannelDimension,
+ ImageInput,
+ PILImageResampling,
+ SizeDict,
+ get_image_size,
+ get_image_size_for_max_height_width,
+ get_max_height_width,
+ validate_annotations,
+)
+from ...processing_utils import ImagesKwargs, Unpack
+from ...utils import TensorType, auto_docstring, is_torch_available, is_vision_available, logging, requires_backends
+from ...utils.import_utils import requires
+
+
+if is_vision_available():
+ import PIL.Image
+if is_torch_available():
+ import torch
+ from torch import nn
+
+logger = logging.get_logger(__name__)
+
+SUPPORTED_ANNOTATION_FORMATS = (AnnotationFormat.COCO_DETECTION, AnnotationFormat.COCO_PANOPTIC)
+
+
+class ConditionalDetrImageProcessorKwargs(ImagesKwargs, total=False):
+ r"""
+ format (`str`, *optional*, defaults to `AnnotationFormat.COCO_DETECTION`):
+ Data format of the annotations. One of "coco_detection" or "coco_panoptic".
+ do_convert_annotations (`bool`, *optional*, defaults to `True`):
+ Controls whether to convert the annotations to the format expected by the CONDITIONAL_DETR model. Converts the
+ bounding boxes to the format `(center_x, center_y, width, height)` and in the range `[0, 1]`.
+ Can be overridden by the `do_convert_annotations` parameter in the `preprocess` method.
+ """
+
+ format: str | AnnotationFormat
+ do_convert_annotations: bool
+
+
+# inspired by https://github.com/facebookresearch/conditional_detr/blob/master/datasets/coco.py#L33
+def convert_coco_poly_to_mask(segmentations, height: int, width: int) -> np.ndarray:
+ """
+ Convert a COCO polygon annotation to a mask.
+
+ Args:
+ segmentations (`list[list[float]]`):
+ List of polygons, each polygon represented by a list of x-y coordinates.
+ height (`int`):
+ Height of the mask.
+ width (`int`):
+ Width of the mask.
+ """
+ try:
+ from pycocotools import mask as coco_mask
+ except ImportError:
+ raise ImportError("Pycocotools is not installed in your environment.")
+
+ masks = []
+ for polygons in segmentations:
+ rles = coco_mask.frPyObjects(polygons, height, width)
+ mask = coco_mask.decode(rles)
+ if len(mask.shape) < 3:
+ mask = mask[..., None]
+ mask = np.asarray(mask, dtype=np.uint8)
+ mask = np.any(mask, axis=2)
+ masks.append(mask)
+ if masks:
+ masks = np.stack(masks, axis=0)
+ else:
+ masks = np.zeros((0, height, width), dtype=np.uint8)
+
+ return masks
+
+
+# inspired by https://github.com/facebookresearch/conditional_detr/blob/master/datasets/coco.py#L50
+def prepare_coco_detection_annotation(
+ image,
+ target,
+ return_segmentation_masks: bool = False,
+ input_data_format: ChannelDimension | str | None = None,
+):
+ """
+ Convert the target in COCO format into the format expected by CONDITIONAL_DETR.
+ """
+ image_height, image_width = get_image_size(image, channel_dim=input_data_format)
+
+ image_id = target["image_id"]
+ image_id = np.asarray([image_id], dtype=np.int64)
+
+ # Get all COCO annotations for the given image.
+ annotations = target["annotations"]
+ annotations = [obj for obj in annotations if "iscrowd" not in obj or obj["iscrowd"] == 0]
+
+ classes = [obj["category_id"] for obj in annotations]
+ classes = np.asarray(classes, dtype=np.int64)
+
+ # for conversion to coco api
+ area = np.asarray([obj["area"] for obj in annotations], dtype=np.float32)
+ iscrowd = np.asarray([obj.get("iscrowd", 0) for obj in annotations], dtype=np.int64)
+
+ boxes = [obj["bbox"] for obj in annotations]
+ # guard against no boxes via resizing
+ boxes = np.asarray(boxes, dtype=np.float32).reshape(-1, 4)
+ boxes[:, 2:] += boxes[:, :2]
+ boxes[:, 0::2] = boxes[:, 0::2].clip(min=0, max=image_width)
+ boxes[:, 1::2] = boxes[:, 1::2].clip(min=0, max=image_height)
+
+ keep = (boxes[:, 3] > boxes[:, 1]) & (boxes[:, 2] > boxes[:, 0])
+
+ new_target = {}
+ new_target["image_id"] = image_id
+ new_target["class_labels"] = classes[keep]
+ new_target["boxes"] = boxes[keep]
+ new_target["area"] = area[keep]
+ new_target["iscrowd"] = iscrowd[keep]
+ new_target["orig_size"] = np.asarray([int(image_height), int(image_width)], dtype=np.int64)
+
+ if annotations and "keypoints" in annotations[0]:
+ keypoints = [obj["keypoints"] for obj in annotations]
+ # Converting the filtered keypoints list to a numpy array
+ keypoints = np.asarray(keypoints, dtype=np.float32)
+ # Apply the keep mask here to filter the relevant annotations
+ keypoints = keypoints[keep]
+ num_keypoints = keypoints.shape[0]
+ keypoints = keypoints.reshape((-1, 3)) if num_keypoints else keypoints
+ new_target["keypoints"] = keypoints
+
+ if return_segmentation_masks:
+ segmentation_masks = [obj["segmentation"] for obj in annotations]
+ masks = convert_coco_poly_to_mask(segmentation_masks, image_height, image_width)
+ new_target["masks"] = masks[keep]
+
+ return new_target
+
+
+def masks_to_boxes(masks: np.ndarray) -> np.ndarray:
+ """
+ Compute the bounding boxes around the provided panoptic segmentation masks.
+
+ Args:
+ masks: masks in format `[number_masks, height, width]` where N is the number of masks
+
+ Returns:
+ boxes: bounding boxes in format `[number_masks, 4]` in xyxy format
+ """
+ if masks.size == 0:
+ return np.zeros((0, 4))
+
+ h, w = masks.shape[-2:]
+ y = np.arange(0, h, dtype=np.float32)
+ x = np.arange(0, w, dtype=np.float32)
+ # see https://github.com/pytorch/pytorch/issues/50276
+ y, x = np.meshgrid(y, x, indexing="ij")
+
+ x_mask = masks * np.expand_dims(x, axis=0)
+ x_max = x_mask.reshape(x_mask.shape[0], -1).max(-1)
+ x = np.ma.array(x_mask, mask=~(np.array(masks, dtype=bool)))
+ x_min = x.filled(fill_value=1e8)
+ x_min = x_min.reshape(x_min.shape[0], -1).min(-1)
+
+ y_mask = masks * np.expand_dims(y, axis=0)
+ y_max = y_mask.reshape(x_mask.shape[0], -1).max(-1)
+ y = np.ma.array(y_mask, mask=~(np.array(masks, dtype=bool)))
+ y_min = y.filled(fill_value=1e8)
+ y_min = y_min.reshape(y_min.shape[0], -1).min(-1)
+
+ return np.stack([x_min, y_min, x_max, y_max], 1)
+
+
+# 2 functions below adapted from https://github.com/cocodataset/panopticapi/blob/master/panopticapi/utils.py
+# Copyright (c) 2018, Alexander Kirillov
+# All rights reserved.
+def rgb_to_id(color):
+ """
+ Converts RGB color to unique ID.
+ """
+ if isinstance(color, np.ndarray) and len(color.shape) == 3:
+ if color.dtype == np.uint8:
+ color = color.astype(np.int32)
+ return color[:, :, 0] + 256 * color[:, :, 1] + 256 * 256 * color[:, :, 2]
+ return int(color[0] + 256 * color[1] + 256 * 256 * color[2])
+
+
+def prepare_coco_panoptic_annotation(
+ image: np.ndarray,
+ target: dict,
+ masks_path: str | pathlib.Path,
+ return_masks: bool = True,
+ input_data_format: ChannelDimension | str = None,
+) -> dict:
+ """
+ Prepare a coco panoptic annotation for CONDITIONAL_DETR.
+ """
+ image_height, image_width = get_image_size(image, channel_dim=input_data_format)
+ annotation_path = pathlib.Path(masks_path) / target["file_name"]
+
+ new_target = {}
+ new_target["image_id"] = np.asarray([target["image_id"] if "image_id" in target else target["id"]], dtype=np.int64)
+ new_target["size"] = np.asarray([image_height, image_width], dtype=np.int64)
+ new_target["orig_size"] = np.asarray([image_height, image_width], dtype=np.int64)
+
+ if "segments_info" in target:
+ masks = np.asarray(PIL.Image.open(annotation_path), dtype=np.uint32)
+ masks = rgb_to_id(masks)
+
+ ids = np.array([segment_info["id"] for segment_info in target["segments_info"]])
+ masks = masks == ids[:, None, None]
+ masks = masks.astype(np.uint8)
+ if return_masks:
+ new_target["masks"] = masks
+ new_target["boxes"] = masks_to_boxes(masks)
+ new_target["class_labels"] = np.array(
+ [segment_info["category_id"] for segment_info in target["segments_info"]], dtype=np.int64
+ )
+ new_target["iscrowd"] = np.asarray(
+ [segment_info["iscrowd"] for segment_info in target["segments_info"]], dtype=np.int64
+ )
+ new_target["area"] = np.asarray(
+ [segment_info["area"] for segment_info in target["segments_info"]], dtype=np.float32
+ )
+
+ return new_target
+
+
+# Adapted from transformers.models.conditional_detr.image_processing_conditional_detr.binary_mask_to_rle
+def binary_mask_to_rle(mask):
+ """
+ Converts given binary mask of shape `(height, width)` to the run-length encoding (RLE) format.
+
+ Args:
+ mask (`torch.Tensor` or `numpy.array`):
+ A binary mask tensor of shape `(height, width)` where 0 denotes background and 1 denotes the target
+ segment_id or class_id.
+ Returns:
+ `List`: Run-length encoded list of the binary mask. Refer to COCO API for more information about the RLE
+ format.
+ """
+ from ...utils import is_torch_tensor
+
+ if is_torch_tensor(mask):
+ mask = mask.numpy()
+
+ pixels = mask.flatten()
+ pixels = np.concatenate([[0], pixels, [0]])
+ runs = np.where(pixels[1:] != pixels[:-1])[0] + 1
+ runs[1::2] -= runs[::2]
+ return list(runs)
+
+
+# Adapted from transformers.models.conditional_detr.image_processing_conditional_detr.check_segment_validity
+def check_segment_validity(mask_labels, mask_probs, k, mask_threshold=0.5, overlap_mask_area_threshold=0.8):
+ # Get the mask associated with the k class
+ mask_k = mask_labels == k
+ mask_k_area = mask_k.sum()
+
+ # Compute the area of all the stuff in query k
+ original_area = (mask_probs[k] >= mask_threshold).sum()
+ mask_exists = mask_k_area > 0 and original_area > 0
+
+ # Eliminate disconnected tiny segments
+ if mask_exists:
+ area_ratio = mask_k_area / original_area
+ if not area_ratio.item() > overlap_mask_area_threshold:
+ mask_exists = False
+
+ return mask_exists, mask_k
+
+
+# Adapted from transformers.models.conditional_detr.image_processing_conditional_detr.compute_segments
+def compute_segments(
+ mask_probs,
+ pred_scores,
+ pred_labels,
+ mask_threshold: float = 0.5,
+ overlap_mask_area_threshold: float = 0.8,
+ label_ids_to_fuse: set[int] | None = None,
+ target_size: tuple[int, int] | None = None,
+):
+ import torch
+ from torch import nn
+
+ height = mask_probs.shape[1] if target_size is None else target_size[0]
+ width = mask_probs.shape[2] if target_size is None else target_size[1]
+
+ segmentation = torch.zeros((height, width), dtype=torch.int32, device=mask_probs.device)
+ segments: list[dict] = []
+
+ if target_size is not None:
+ mask_probs = nn.functional.interpolate(
+ mask_probs.unsqueeze(0), size=target_size, mode="bilinear", align_corners=False
+ )[0]
+
+ current_segment_id = 0
+
+ # Weigh each mask by its prediction score
+ mask_probs *= pred_scores.view(-1, 1, 1)
+ mask_labels = mask_probs.argmax(0) # [height, width]
+
+ # Keep track of instances of each class
+ stuff_memory_list: dict[str, int] = {}
+ for k in range(pred_labels.shape[0]):
+ pred_class = pred_labels[k].item()
+ should_fuse = pred_class in label_ids_to_fuse
+
+ # Check if mask exists and large enough to be a segment
+ mask_exists, mask_k = check_segment_validity(
+ mask_labels, mask_probs, k, mask_threshold, overlap_mask_area_threshold
+ )
+
+ if mask_exists:
+ if pred_class in stuff_memory_list:
+ current_segment_id = stuff_memory_list[pred_class]
+ else:
+ current_segment_id += 1
+
+ # Add current object segment to final segmentation map
+ segmentation[mask_k] = current_segment_id
+ segment_score = round(pred_scores[k].item(), 6)
+ segments.append(
+ {
+ "id": current_segment_id,
+ "label_id": pred_class,
+ "was_fused": should_fuse,
+ "score": segment_score,
+ }
+ )
+ if should_fuse:
+ stuff_memory_list[pred_class] = current_segment_id
+
+ return segmentation, segments
+
+
+# Adapted from transformers.models.conditional_detr.image_processing_conditional_detr.convert_segmentation_to_rle
+def convert_segmentation_to_rle(segmentation):
+ """
+ Converts given segmentation map of shape `(height, width)` to the run-length encoding (RLE) format.
+
+ Args:
+ segmentation (`torch.Tensor` or `numpy.array`):
+ A segmentation map of shape `(height, width)` where each value denotes a segment or class id.
+ Returns:
+ `list[List]`: A list of lists, where each list is the run-length encoding of a segment / class id.
+ """
+ import torch
+
+ segment_ids = torch.unique(segmentation)
+
+ run_length_encodings = []
+ for idx in segment_ids:
+ mask = torch.where(segmentation == idx, 1, 0)
+ rle = binary_mask_to_rle(mask)
+ run_length_encodings.append(rle)
+
+ return run_length_encodings
+
+
+# Adapted from transformers.models.conditional_detr.image_processing_conditional_detr.remove_low_and_no_objects
+def remove_low_and_no_objects(masks, scores, labels, object_mask_threshold, num_labels):
+ """
+ Binarize the given masks using `object_mask_threshold`, it returns the associated values of `masks`, `scores` and
+ `labels`.
+
+ Args:
+ masks (`torch.Tensor`):
+ A tensor of shape `(num_queries, height, width)`.
+ scores (`torch.Tensor`):
+ A tensor of shape `(num_queries)`.
+ labels (`torch.Tensor`):
+ A tensor of shape `(num_queries)`.
+ object_mask_threshold (`float`):
+ A number between 0 and 1 used to binarize the masks.
+ Raises:
+ `ValueError`: Raised when the first dimension doesn't match in all input tensors.
+ Returns:
+ `tuple[`torch.Tensor`, `torch.Tensor`, `torch.Tensor`]`: The `masks`, `scores` and `labels` without the region
+ < `object_mask_threshold`.
+ """
+ if not (masks.shape[0] == scores.shape[0] == labels.shape[0]):
+ raise ValueError("mask, scores and labels must have the same shape!")
+
+ to_keep = labels.ne(num_labels) & (scores > object_mask_threshold)
+
+ return masks[to_keep], scores[to_keep], labels[to_keep]
+
+
+@auto_docstring
+class ConditionalDetrImageProcessorPil(PilBackend):
+ resample = PILImageResampling.BILINEAR
+ image_mean = IMAGENET_DEFAULT_MEAN
+ image_std = IMAGENET_DEFAULT_STD
+ format = AnnotationFormat.COCO_DETECTION
+ do_resize = True
+ do_rescale = True
+ do_normalize = True
+ do_pad = True
+ size = {"shortest_edge": 800, "longest_edge": 1333}
+ default_to_square = False
+ model_input_names = ["pixel_values", "pixel_mask"]
+ valid_kwargs = ConditionalDetrImageProcessorKwargs
+
+ def __init__(self, **kwargs: Unpack[ConditionalDetrImageProcessorKwargs]) -> None:
+ kwargs.setdefault("do_pad", kwargs.pop("pad_and_return_pixel_mask", self.do_pad))
+
+ size = kwargs.pop("size", None)
+ max_size = None if size is None else kwargs.pop("max_size", 1333)
+ size = size if size is not None else {"shortest_edge": 800, "longest_edge": 1333}
+ # Convert size dict for backwards compat with max_size parameter
+ if size is not None:
+ from ...image_processing_utils import get_size_dict
+
+ kwargs["size"] = get_size_dict(size, max_size=max_size, default_to_square=False)
+
+ # Backwards compatibility
+ do_convert_annotations = kwargs.get("do_convert_annotations")
+ do_normalize = kwargs.get("do_normalize")
+ if do_convert_annotations is None and getattr(self, "do_convert_annotations", None) is None:
+ self.do_convert_annotations = do_normalize if do_normalize is not None else self.do_normalize
+
+ super().__init__(**kwargs)
+
+ def prepare_annotation(
+ self,
+ image: np.ndarray,
+ target: dict,
+ format: AnnotationFormat | None = None,
+ return_segmentation_masks: bool | None = None,
+ masks_path: str | pathlib.Path | None = None,
+ input_data_format: str | ChannelDimension | None = None,
+ ) -> dict:
+ """
+ Prepare an annotation for feeding into CONDITIONAL_DETR model.
+ """
+ format = format if format is not None else self.format
+
+ if format == AnnotationFormat.COCO_DETECTION:
+ return_segmentation_masks = False if return_segmentation_masks is None else return_segmentation_masks
+ target = prepare_coco_detection_annotation(
+ image, target, return_segmentation_masks, input_data_format=input_data_format
+ )
+ elif format == AnnotationFormat.COCO_PANOPTIC:
+ return_segmentation_masks = True if return_segmentation_masks is None else return_segmentation_masks
+ target = prepare_coco_panoptic_annotation(
+ image,
+ target,
+ masks_path=masks_path,
+ return_masks=return_segmentation_masks,
+ input_data_format=input_data_format,
+ )
+ else:
+ raise ValueError(f"Format {format} is not supported.")
+ return target
+
+ def resize(
+ self,
+ image: np.ndarray,
+ size: SizeDict,
+ resample: Optional["PILImageResampling"] = None,
+ **kwargs,
+ ) -> np.ndarray:
+ """
+ Resize the image to the given size. Size can be `min_size` (scalar) or `(height, width)` tuple. If size is an
+ int, smaller edge of the image will be matched to this number.
+
+ Args:
+ image (`np.ndarray`):
+ Image to resize.
+ size (`SizeDict`):
+ Size of the image's `(height, width)` dimensions after resizing. Available options are:
+ - `{"height": int, "width": int}`: The image will be resized to the exact size `(height, width)`.
+ Do NOT keep the aspect ratio.
+ - `{"shortest_edge": int, "longest_edge": int}`: The image will be resized to a maximum size respecting
+ the aspect ratio and keeping the shortest edge less or equal to `shortest_edge` and the longest edge
+ less or equal to `longest_edge`.
+ - `{"max_height": int, "max_width": int}`: The image will be resized to the maximum size respecting the
+ aspect ratio and keeping the height less or equal to `max_height` and the width less or equal to
+ `max_width`.
+ resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`):
+ Resampling filter to use if resizing the image.
+ """
+ resample = resample if resample is not None else self.resample
+
+ if size.shortest_edge and size.longest_edge:
+ # Resize the image so that the shortest edge or the longest edge is of the given size
+ # while maintaining the aspect ratio of the original image.
+ new_size = get_size_with_aspect_ratio(
+ image.shape[-2:],
+ size.shortest_edge,
+ size.longest_edge or size.shortest_edge,
+ )
+ elif size.max_height and size.max_width:
+ new_size = get_image_size_for_max_height_width(image.shape[-2:], size.max_height, size.max_width)
+ elif size.height and size.width:
+ new_size = (size.height, size.width)
+ else:
+ raise ValueError(
+ f"Size must contain 'height' and 'width' keys or 'shortest_edge' and 'longest_edge' keys. Got {size}."
+ )
+
+ image = super().resize(
+ image,
+ size=SizeDict(height=new_size[0], width=new_size[1]),
+ resample=resample,
+ **kwargs,
+ )
+ return image
+
+ def resize_annotation(
+ self,
+ annotation: dict[str, Any],
+ orig_size: tuple[int, int],
+ target_size: tuple[int, int],
+ threshold: float = 0.5,
+ resample: Optional["PILImageResampling"] = PILImageResampling.NEAREST,
+ ):
+ """
+ Resizes an annotation to a target size.
+
+ Args:
+ annotation (`dict[str, Any]`):
+ The annotation dictionary.
+ orig_size (`tuple[int, int]`):
+ The original size of the input image.
+ target_size (`tuple[int, int]`):
+ The target size of the image, as returned by the preprocessing `resize` step.
+ threshold (`float`, *optional*, defaults to 0.5):
+ The threshold used to binarize the segmentation masks.
+ resample (`PILImageResampling`, defaults to `PILImageResampling.NEAREST`):
+ The resampling filter to use when resizing the masks.
+ """
+ ratios = tuple(float(s) / float(s_orig) for s, s_orig in zip(target_size, orig_size))
+ ratio_height, ratio_width = ratios
+
+ new_annotation = {}
+ new_annotation["size"] = target_size
+
+ for key, value in annotation.items():
+ if key == "boxes":
+ boxes = value
+ scaled_boxes = boxes * np.asarray(
+ [ratio_width, ratio_height, ratio_width, ratio_height], dtype=np.float32
+ )
+ new_annotation["boxes"] = scaled_boxes
+ elif key == "area":
+ area = value
+ scaled_area = area * (ratio_width * ratio_height)
+ new_annotation["area"] = scaled_area
+ elif key == "masks":
+ masks = value[:, None]
+ masks = np.array([resize(mask, target_size, resample=resample) for mask in masks])
+ masks = masks.astype(np.float32)
+ masks = masks[:, 0] > threshold
+ new_annotation["masks"] = masks
+ elif key == "size":
+ new_annotation["size"] = target_size
+ else:
+ new_annotation[key] = value
+
+ return new_annotation
+
+ def normalize_annotation(self, annotation: dict, image_size: tuple[int, int]) -> dict:
+ image_height, image_width = image_size
+ norm_annotation = {}
+ for key, value in annotation.items():
+ if key == "boxes":
+ boxes = value
+ boxes = corners_to_center_format(boxes)
+ boxes /= np.asarray([image_width, image_height, image_width, image_height], dtype=np.float32)
+ norm_annotation[key] = boxes
+ else:
+ norm_annotation[key] = value
+ return norm_annotation
+
+ def _update_annotation_for_padded_image(
+ self,
+ annotation: dict,
+ input_image_size: tuple[int, int],
+ output_image_size: tuple[int, int],
+ padding,
+ update_bboxes,
+ ) -> dict:
+ """
+ Update the annotation for a padded image.
+ """
+ new_annotation = {}
+ new_annotation["size"] = output_image_size
+ ratio_height, ratio_width = (input / output for output, input in zip(output_image_size, input_image_size))
+
+ for key, value in annotation.items():
+ if key == "masks":
+ masks = value
+ masks = pad(
+ masks,
+ padding,
+ mode=PaddingMode.CONSTANT,
+ constant_values=0,
+ input_data_format=ChannelDimension.FIRST,
+ )
+ masks = safe_squeeze(masks, 1)
+ new_annotation["masks"] = masks
+ elif key == "boxes" and update_bboxes:
+ boxes = value
+ boxes *= np.asarray(
+ [
+ input_image_size[1] / output_image_size[1],
+ input_image_size[0] / output_image_size[0],
+ input_image_size[1] / output_image_size[1],
+ input_image_size[0] / output_image_size[0],
+ ]
+ )
+ new_annotation["boxes"] = boxes
+ elif key == "size":
+ new_annotation["size"] = output_image_size
+ else:
+ new_annotation[key] = value
+ return new_annotation
+
+ def pad(
+ self,
+ image: np.ndarray,
+ padded_size: tuple[int, int],
+ annotation: dict[str, Any] | None = None,
+ update_bboxes: bool = True,
+ fill: int = 0,
+ ):
+ input_height, input_width = get_image_size(image, channel_dim=ChannelDimension.FIRST)
+ output_height, output_width = padded_size
+ padding_bottom = output_height - input_height
+ padding_right = output_width - input_width
+ if padding_bottom < 0 or padding_right < 0:
+ raise ValueError(
+ f"Padding dimensions are negative. Please make sure that the padded size is larger than the "
+ f"original size. Got padded size: {padded_size}, original size: {(input_height, input_width)}."
+ )
+ if (input_height, input_width) != padded_size:
+ padding = ((0, padding_bottom), (0, padding_right))
+ image = pad(
+ image,
+ padding,
+ mode=PaddingMode.CONSTANT,
+ constant_values=fill,
+ data_format=ChannelDimension.FIRST,
+ input_data_format=ChannelDimension.FIRST,
+ )
+ if annotation is not None:
+ annotation = self._update_annotation_for_padded_image(
+ annotation, (input_height, input_width), (output_height, output_width), padding, update_bboxes
+ )
+
+ # Make a pixel mask for the image, where 1 indicates a valid pixel and 0 indicates padding.
+ pixel_mask = np.zeros(padded_size, dtype=np.int64)
+ pixel_mask[:input_height, :input_width] = 1
+
+ return image, pixel_mask, annotation
+
+ @auto_docstring
+ def preprocess(
+ self,
+ images: ImageInput,
+ annotations: AnnotationType | list[AnnotationType] | None = None,
+ return_segmentation_masks: bool | None = None,
+ masks_path: str | pathlib.Path | None = None,
+ **kwargs: Unpack[ConditionalDetrImageProcessorKwargs],
+ ) -> BatchFeature:
+ r"""
+ annotations (`AnnotationType` or `list[AnnotationType]`, *optional*):
+ Annotations to transform according to the padding that is applied to the images.
+ return_segmentation_masks (`bool`, *optional*, defaults to `self.return_segmentation_masks`):
+ Whether to return segmentation masks.
+ masks_path (`str` or `pathlib.Path`, *optional*):
+ Path to the directory containing the segmentation masks.
+ """
+ return super().preprocess(images, annotations, return_segmentation_masks, masks_path, **kwargs)
+
+ def _preprocess(
+ self,
+ images: list[np.ndarray],
+ annotations: AnnotationType | list[AnnotationType] | None,
+ return_segmentation_masks: bool,
+ masks_path: str | pathlib.Path | None,
+ do_resize: bool,
+ size: SizeDict,
+ resample: "PILImageResampling | None",
+ do_rescale: bool,
+ rescale_factor: float,
+ do_normalize: bool,
+ do_convert_annotations: bool,
+ image_mean: float | list[float] | None,
+ image_std: float | list[float] | None,
+ do_pad: bool,
+ pad_size: SizeDict | None,
+ format: str | AnnotationFormat | None,
+ return_tensors: str | TensorType | None,
+ **kwargs,
+ ) -> BatchFeature:
+ """
+ Preprocess an image or a batch of images so that it can be used by the model.
+ """
+ if annotations is not None and isinstance(annotations, dict):
+ annotations = [annotations]
+
+ if annotations is not None and len(images) != len(annotations):
+ raise ValueError(
+ f"The number of images ({len(images)}) and annotations ({len(annotations)}) do not match."
+ )
+
+ format = AnnotationFormat(format)
+ if annotations is not None:
+ validate_annotations(format, SUPPORTED_ANNOTATION_FORMATS, annotations)
+
+ if (
+ masks_path is not None
+ and format == AnnotationFormat.COCO_PANOPTIC
+ and not isinstance(masks_path, (pathlib.Path, str))
+ ):
+ raise ValueError(
+ "The path to the directory containing the mask PNG files should be provided as a"
+ f" `pathlib.Path` or string object, but is {type(masks_path)} instead."
+ )
+
+ data = {}
+
+ # Import torch if needed for tensor conversion
+ if return_tensors == "pt":
+ if not is_torch_available():
+ raise ImportError("PyTorch is required for tensor conversion.")
+
+ processed_images = []
+ processed_annotations = []
+ pixel_masks = [] # Initialize pixel_masks here
+ for image, annotation in zip(images, annotations if annotations is not None else [None] * len(images)):
+ # prepare (COCO annotations as a list of Dict -> CONDITIONAL_DETR target as a single Dict per image)
+ if annotations is not None:
+ annotation = self.prepare_annotation(
+ image,
+ annotation,
+ format,
+ return_segmentation_masks=return_segmentation_masks,
+ masks_path=masks_path,
+ input_data_format=ChannelDimension.FIRST,
+ )
+
+ if do_resize:
+ resized_image = self.resize(image, size=size, resample=resample)
+ if annotations is not None:
+ annotation = self.resize_annotation(
+ annotation,
+ orig_size=get_image_size(image, channel_dim=ChannelDimension.FIRST),
+ target_size=get_image_size(resized_image, channel_dim=ChannelDimension.FIRST),
+ )
+ image = resized_image
+
+ if do_rescale:
+ image = self.rescale(image, rescale_factor)
+ if do_normalize:
+ image = self.normalize(image, image_mean, image_std)
+
+ if do_convert_annotations and annotations is not None:
+ annotation = self.normalize_annotation(annotation, get_image_size(image, ChannelDimension.FIRST))
+
+ processed_images.append(image)
+ processed_annotations.append(annotation)
+ images = processed_images
+ annotations = processed_annotations if annotations is not None else None
+
+ if do_pad:
+ # depends on all resized image shapes so we need another loop
+ if pad_size is not None:
+ padded_size = (pad_size.height, pad_size.width)
+ else:
+ padded_size = get_max_height_width(images, input_data_format=ChannelDimension.FIRST)
+
+ padded_images = []
+ padded_annotations = []
+ for image, annotation in zip(images, annotations if annotations is not None else [None] * len(images)):
+ # Pads images and returns their mask: {'pixel_values': ..., 'pixel_mask': ...}
+ image_height, image_width = get_image_size(image, channel_dim=ChannelDimension.FIRST)
+ if padded_size == (image_height, image_width):
+ padded_images.append(image)
+ pixel_masks.append(np.ones(padded_size, dtype=np.int64))
+ padded_annotations.append(annotation)
+ continue
+ image, pixel_mask, annotation = self.pad(
+ image, padded_size, annotation=annotation, update_bboxes=do_convert_annotations
+ )
+ padded_images.append(image)
+ padded_annotations.append(annotation)
+ pixel_masks.append(pixel_mask)
+ images = padded_images
+ annotations = padded_annotations if annotations is not None else None
+ data.update({"pixel_mask": pixel_masks})
+
+ data.update({"pixel_values": images})
+ encoded_inputs = BatchFeature(data, tensor_type=return_tensors)
+ if annotations is not None:
+ encoded_inputs["labels"] = [
+ BatchFeature(annotation, tensor_type=return_tensors) for annotation in annotations
+ ]
+ return encoded_inputs
+
+ @requires(backends=("torch",))
+ def post_process_object_detection(
+ self, outputs, threshold: float = 0.5, target_sizes: TensorType | list[tuple] = None, top_k: int = 100
+ ):
+ """
+ Converts the raw output of [`ConditionalDetrForObjectDetection`] into final bounding boxes in (top_left_x,
+ top_left_y, bottom_right_x, bottom_right_y) format. Only supports PyTorch.
+
+ Args:
+ outputs ([`ConditionalDetrObjectDetectionOutput`]):
+ Raw outputs of the model.
+ threshold (`float`, *optional*):
+ Score threshold to keep object detection predictions.
+ target_sizes (`torch.Tensor` or `list[tuple[int, int]]`, *optional*):
+ Tensor of shape `(batch_size, 2)` or list of tuples (`tuple[int, int]`) containing the target size
+ (height, width) of each image in the batch. If left to None, predictions will not be resized.
+ top_k (`int`, *optional*, defaults to 100):
+ Keep only top k bounding boxes before filtering by thresholding.
+
+ Returns:
+ `list[Dict]`: A list of dictionaries, each dictionary containing the scores, labels and boxes for an image
+ in the batch as predicted by the model.
+ """
+ requires_backends(self, ["torch"])
+ out_logits, out_bbox = outputs.logits, outputs.pred_boxes
+
+ if target_sizes is not None:
+ if len(out_logits) != len(target_sizes):
+ raise ValueError(
+ "Make sure that you pass in as many target sizes as the batch dimension of the logits"
+ )
+
+ prob = out_logits.sigmoid()
+ prob = prob.view(out_logits.shape[0], -1)
+ k_value = min(top_k, prob.size(1))
+ topk_values, topk_indexes = torch.topk(prob, k_value, dim=1)
+ scores = topk_values
+ topk_boxes = torch.div(topk_indexes, out_logits.shape[2], rounding_mode="floor")
+ labels = topk_indexes % out_logits.shape[2]
+ boxes = center_to_corners_format(out_bbox)
+ boxes = torch.gather(boxes, 1, topk_boxes.unsqueeze(-1).repeat(1, 1, 4))
+
+ # and from relative [0, 1] to absolute [0, height] coordinates
+ if target_sizes is not None:
+ if isinstance(target_sizes, list):
+ img_h = torch.Tensor([i[0] for i in target_sizes])
+ img_w = torch.Tensor([i[1] for i in target_sizes])
+ else:
+ img_h, img_w = target_sizes.unbind(1)
+ scale_fct = torch.stack([img_w, img_h, img_w, img_h], dim=1).to(boxes.device)
+ boxes = boxes * scale_fct[:, None, :]
+
+ results = []
+ for s, l, b in zip(scores, labels, boxes):
+ score = s[s > threshold]
+ label = l[s > threshold]
+ box = b[s > threshold]
+ results.append({"scores": score, "labels": label, "boxes": box})
+
+ return results
+
+ @requires(backends=("torch",))
+ def post_process_semantic_segmentation(self, outputs, target_sizes: list[tuple[int, int]] | None = None):
+ """
+ Converts the output of [`ConditionalDetrForSegmentation`] into semantic segmentation maps. Only supports PyTorch.
+
+ Args:
+ outputs ([`ConditionalDetrForSegmentation`]):
+ Raw outputs of the model.
+ target_sizes (`list[tuple[int, int]]`, *optional*):
+ A list of tuples (`tuple[int, int]`) containing the target size (height, width) of each image in the
+ batch. If unset, predictions will not be resized.
+ Returns:
+ `list[torch.Tensor]`:
+ A list of length `batch_size`, where each item is a semantic segmentation map of shape (height, width)
+ corresponding to the target_sizes entry (if `target_sizes` is specified). Each entry of each
+ `torch.Tensor` correspond to a semantic class id.
+ """
+ requires_backends(self, ["torch"])
+ class_queries_logits = outputs.logits # [batch_size, num_queries, num_classes]
+ masks_queries_logits = outputs.pred_masks # [batch_size, num_queries, height, width]
+
+ # Conditional DETR does not have a null class, so we use all classes
+ masks_classes = class_queries_logits.softmax(dim=-1)
+ masks_probs = masks_queries_logits.sigmoid() # [batch_size, num_queries, height, width]
+
+ # Semantic segmentation logits of shape (batch_size, num_classes, height, width)
+ segmentation = torch.einsum("bqc, bqhw -> bchw", masks_classes, masks_probs)
+ batch_size = class_queries_logits.shape[0]
+
+ # Resize logits and compute semantic segmentation maps
+ if target_sizes is not None:
+ if batch_size != len(target_sizes):
+ raise ValueError(
+ "Make sure that you pass in as many target sizes as the batch dimension of the logits"
+ )
+
+ semantic_segmentation = []
+ for idx in range(batch_size):
+ resized_logits = nn.functional.interpolate(
+ segmentation[idx].unsqueeze(dim=0), size=target_sizes[idx], mode="bilinear", align_corners=False
+ )
+ semantic_map = resized_logits[0].argmax(dim=0)
+ semantic_segmentation.append(semantic_map)
+ else:
+ semantic_segmentation = segmentation.argmax(dim=1)
+ semantic_segmentation = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0])]
+
+ return semantic_segmentation
+
+ @requires(backends=("torch",))
+ def post_process_instance_segmentation(
+ self,
+ outputs,
+ threshold: float = 0.5,
+ mask_threshold: float = 0.5,
+ overlap_mask_area_threshold: float = 0.8,
+ target_sizes: list[tuple[int, int]] | None = None,
+ return_coco_annotation: bool | None = False,
+ ) -> list[dict]:
+ """
+ Converts the output of [`ConditionalDetrForSegmentation`] into instance segmentation predictions. Only supports PyTorch.
+
+ Args:
+ outputs ([`ConditionalDetrForSegmentation`]):
+ Raw outputs of the model.
+ threshold (`float`, *optional*, defaults to 0.5):
+ The probability score threshold to keep predicted instance masks.
+ mask_threshold (`float`, *optional*, defaults to 0.5):
+ Threshold to use when turning the predicted masks into binary values.
+ overlap_mask_area_threshold (`float`, *optional*, defaults to 0.8):
+ The overlap mask area threshold to merge or discard small disconnected parts within each binary
+ instance mask.
+ target_sizes (`list[Tuple]`, *optional*):
+ List of length (batch_size), where each list item (`tuple[int, int]]`) corresponds to the requested
+ final size (height, width) of each prediction. If unset, predictions will not be resized.
+ return_coco_annotation (`bool`, *optional*):
+ Defaults to `False`. If set to `True`, segmentation maps are returned in COCO run-length encoding (RLE)
+ format.
+ Returns:
+ `list[Dict]`: A list of dictionaries, one per image, each dictionary containing two keys:
+ - **segmentation** -- A tensor of shape `(height, width)` where each pixel represents a `segment_id` or
+ `list[List]` run-length encoding (RLE) of the segmentation map if return_coco_annotation is set to
+ `True`. Set to `None` if no mask if found above `threshold`.
+ - **segments_info** -- A dictionary that contains additional information on each segment.
+ - **id** -- An integer representing the `segment_id`.
+ - **label_id** -- An integer representing the label / semantic class id corresponding to `segment_id`.
+ - **score** -- Prediction score of segment with `segment_id`.
+ """
+ if not is_torch_available():
+ raise ImportError("PyTorch is required for post-processing.")
+ import torch
+ from torch import nn
+
+ class_queries_logits = outputs.logits # [batch_size, num_queries, num_classes+1]
+ masks_queries_logits = outputs.pred_masks # [batch_size, num_queries, height, width]
+
+ batch_size = class_queries_logits.shape[0]
+ num_labels = class_queries_logits.shape[-1] - 1
+
+ mask_probs = masks_queries_logits.sigmoid() # [batch_size, num_queries, height, width]
+
+ # Predicted label and score of each query (batch_size, num_queries)
+ pred_scores, pred_labels = nn.functional.softmax(class_queries_logits, dim=-1).max(-1)
+
+ # Loop over items in batch size
+ results: list[dict[str, TensorType]] = []
+
+ for i in range(batch_size):
+ mask_probs_item, pred_scores_item, pred_labels_item = remove_low_and_no_objects(
+ mask_probs[i], pred_scores[i], pred_labels[i], threshold, num_labels
+ )
+
+ # No mask found
+ if mask_probs_item.shape[0] <= 0:
+ height, width = target_sizes[i] if target_sizes is not None else mask_probs_item.shape[1:]
+ segmentation = torch.zeros((height, width)) - 1
+ results.append({"segmentation": segmentation, "segments_info": []})
+ continue
+
+ # Get segmentation map and segment information of batch item
+ target_size = target_sizes[i] if target_sizes is not None else None
+ segmentation, segments = compute_segments(
+ mask_probs=mask_probs_item,
+ pred_scores=pred_scores_item,
+ pred_labels=pred_labels_item,
+ mask_threshold=mask_threshold,
+ overlap_mask_area_threshold=overlap_mask_area_threshold,
+ label_ids_to_fuse=[],
+ target_size=target_size,
+ )
+
+ # Return segmentation map in run-length encoding (RLE) format
+ if return_coco_annotation:
+ segmentation = convert_segmentation_to_rle(segmentation)
+
+ results.append({"segmentation": segmentation, "segments_info": segments})
+ return results
+
+ @requires(backends=("torch",))
+ def post_process_panoptic_segmentation(
+ self,
+ outputs,
+ threshold: float = 0.5,
+ mask_threshold: float = 0.5,
+ overlap_mask_area_threshold: float = 0.8,
+ label_ids_to_fuse: set[int] | None = None,
+ target_sizes: list[tuple[int, int]] | None = None,
+ ) -> list[dict]:
+ """
+ Converts the output of [`ConditionalDetrForSegmentation`] into image panoptic segmentation predictions. Only supports
+ PyTorch.
+
+ Args:
+ outputs ([`ConditionalDetrForSegmentation`]):
+ The outputs from [`ConditionalDetrForSegmentation`].
+ threshold (`float`, *optional*, defaults to 0.5):
+ The probability score threshold to keep predicted instance masks.
+ mask_threshold (`float`, *optional*, defaults to 0.5):
+ Threshold to use when turning the predicted masks into binary values.
+ overlap_mask_area_threshold (`float`, *optional*, defaults to 0.8):
+ The overlap mask area threshold to merge or discard small disconnected parts within each binary
+ instance mask.
+ label_ids_to_fuse (`Set[int]`, *optional*):
+ The labels in this state will have all their instances be fused together. For instance we could say
+ there can only be one sky in an image, but several persons, so the label ID for sky would be in that
+ set, but not the one for person.
+ target_sizes (`list[Tuple]`, *optional*):
+ List of length (batch_size), where each list item (`tuple[int, int]]`) corresponds to the requested
+ final size (height, width) of each prediction in batch. If unset, predictions will not be resized.
+ Returns:
+ `list[Dict]`: A list of dictionaries, one per image, each dictionary containing two keys:
+ - **segmentation** -- a tensor of shape `(height, width)` where each pixel represents a `segment_id` or
+ `None` if no mask if found above `threshold`. If `target_sizes` is specified, segmentation is resized to
+ the corresponding `target_sizes` entry.
+ - **segments_info** -- A dictionary that contains additional information on each segment.
+ - **id** -- an integer representing the `segment_id`.
+ - **label_id** -- An integer representing the label / semantic class id corresponding to `segment_id`.
+ - **was_fused** -- a boolean, `True` if `label_id` was in `label_ids_to_fuse`, `False` otherwise.
+ Multiple instances of the same class / label were fused and assigned a single `segment_id`.
+ - **score** -- Prediction score of segment with `segment_id`.
+ """
+
+ if label_ids_to_fuse is None:
+ logger.warning_once("`label_ids_to_fuse` unset. No instance will be fused.")
+ label_ids_to_fuse = set()
+
+ if not is_torch_available():
+ raise ImportError("PyTorch is required for post-processing.")
+ import torch
+ from torch import nn
+
+ class_queries_logits = outputs.logits # [batch_size, num_queries, num_classes+1]
+ masks_queries_logits = outputs.pred_masks # [batch_size, num_queries, height, width]
+
+ batch_size = class_queries_logits.shape[0]
+ num_labels = class_queries_logits.shape[-1] - 1
+
+ mask_probs = masks_queries_logits.sigmoid() # [batch_size, num_queries, height, width]
+
+ # Predicted label and score of each query (batch_size, num_queries)
+ pred_scores, pred_labels = nn.functional.softmax(class_queries_logits, dim=-1).max(-1)
+
+ # Loop over items in batch size
+ results: list[dict[str, TensorType]] = []
+
+ for i in range(batch_size):
+ mask_probs_item, pred_scores_item, pred_labels_item = remove_low_and_no_objects(
+ mask_probs[i], pred_scores[i], pred_labels[i], threshold, num_labels
+ )
+
+ # No mask found
+ if mask_probs_item.shape[0] <= 0:
+ height, width = target_sizes[i] if target_sizes is not None else mask_probs_item.shape[1:]
+ segmentation = torch.zeros((height, width)) - 1
+ results.append({"segmentation": segmentation, "segments_info": []})
+ continue
+
+ # Get segmentation map and segment information of batch item
+ target_size = target_sizes[i] if target_sizes is not None else None
+ segmentation, segments = compute_segments(
+ mask_probs=mask_probs_item,
+ pred_scores=pred_scores_item,
+ pred_labels=pred_labels_item,
+ mask_threshold=mask_threshold,
+ overlap_mask_area_threshold=overlap_mask_area_threshold,
+ label_ids_to_fuse=label_ids_to_fuse,
+ target_size=target_size,
+ )
+
+ results.append({"segmentation": segmentation, "segments_info": segments})
+ return results
+
+
+__all__ = ["ConditionalDetrImageProcessorPil"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/conditional_detr/modeling_conditional_detr.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/conditional_detr/modeling_conditional_detr.py
new file mode 100644
index 0000000000000000000000000000000000000000..2e323d09d517a2f9504fc60aa9aba71e987bba26
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/conditional_detr/modeling_conditional_detr.py
@@ -0,0 +1,1866 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/conditional_detr/modular_conditional_detr.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_conditional_detr.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2022 Microsoft Research Asia and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import math
+from collections.abc import Callable
+from dataclasses import dataclass
+
+import torch
+from torch import nn
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...backbone_utils import load_backbone
+from ...masking_utils import create_bidirectional_mask
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import BaseModelOutput, BaseModelOutputWithCrossAttentions, Seq2SeqModelOutput
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
+from ...processing_utils import Unpack
+from ...pytorch_utils import compile_compatible_method_lru_cache
+from ...utils import ModelOutput, TransformersKwargs, auto_docstring
+from ...utils.generic import can_return_tuple, merge_with_config_defaults
+from ...utils.output_capturing import OutputRecorder, capture_outputs
+from .configuration_conditional_detr import ConditionalDetrConfig
+
+
+@auto_docstring(
+ custom_intro="""
+ Base class for outputs of the CONDITIONAL_DETR decoder. This class adds one attribute to BaseModelOutputWithCrossAttentions,
+ namely an optional stack of intermediate decoder activations, i.e. the output of each decoder layer, each of them
+ gone through a layernorm. This is useful when training the model with auxiliary decoding losses.
+ """
+)
+@dataclass
+class ConditionalDetrDecoderOutput(BaseModelOutputWithCrossAttentions):
+ r"""
+ cross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` and `config.add_cross_attention=True` is passed or when `config.output_attentions=True`):
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
+ sequence_length)`. Attentions weights of the decoder's cross-attention layer, after the attention softmax,
+ used to compute the weighted average in the cross-attention heads.
+ intermediate_hidden_states (`torch.FloatTensor` of shape `(config.decoder_layers, batch_size, num_queries, hidden_size)`, *optional*, returned when `config.auxiliary_loss=True`):
+ Intermediate decoder activations, i.e. the output of each decoder layer, each of them gone through a
+ layernorm.
+ reference_points (`torch.FloatTensor` of shape `(config.decoder_layers, batch_size, num_queries, 2 (anchor points))`):
+ Reference points (reference points of each layer of the decoder).
+ """
+
+ intermediate_hidden_states: torch.FloatTensor | None = None
+
+ reference_points: tuple[torch.FloatTensor] | None = None
+
+
+@auto_docstring(
+ custom_intro="""
+ Base class for outputs of the CONDITIONAL_DETR encoder-decoder model. This class adds one attribute to Seq2SeqModelOutput,
+ namely an optional stack of intermediate decoder activations, i.e. the output of each decoder layer, each of them
+ gone through a layernorm. This is useful when training the model with auxiliary decoding losses.
+ """
+)
+@dataclass
+class ConditionalDetrModelOutput(Seq2SeqModelOutput):
+ r"""
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
+ Sequence of hidden-states at the output of the last layer of the decoder of the model.
+ intermediate_hidden_states (`torch.FloatTensor` of shape `(config.decoder_layers, batch_size, sequence_length, hidden_size)`, *optional*, returned when `config.auxiliary_loss=True`):
+ Intermediate decoder activations, i.e. the output of each decoder layer, each of them gone through a
+ layernorm.
+ reference_points (`torch.FloatTensor` of shape `(config.decoder_layers, batch_size, num_queries, 2 (anchor points))`):
+ Reference points (reference points of each layer of the decoder).
+ """
+
+ intermediate_hidden_states: torch.FloatTensor | None = None
+
+ reference_points: tuple[torch.FloatTensor] | None = None
+
+
+@auto_docstring(
+ custom_intro="""
+ Output type of [`ConditionalDetrForObjectDetection`].
+ """
+)
+@dataclass
+class ConditionalDetrObjectDetectionOutput(ModelOutput):
+ r"""
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` are provided)):
+ Total loss as a linear combination of a negative log-likehood (cross-entropy) for class prediction and a
+ bounding box loss. The latter is defined as a linear combination of the L1 loss and the generalized
+ scale-invariant IoU loss.
+ loss_dict (`Dict`, *optional*):
+ A dictionary containing the individual losses. Useful for logging.
+ logits (`torch.FloatTensor` of shape `(batch_size, num_queries, num_classes + 1)`):
+ Classification logits (including no-object) for all queries.
+ pred_boxes (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)`):
+ Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height). These
+ values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding
+ possible padding). You can use [`~ConditionalDetrImageProcessor.post_process_object_detection`] to retrieve the
+ unnormalized bounding boxes.
+ auxiliary_outputs (`list[Dict]`, *optional*):
+ Optional, only returned when auxiliary losses are activated (i.e. `config.auxiliary_loss` is set to `True`)
+ and labels are provided. It is a list of dictionaries containing the two above keys (`logits` and
+ `pred_boxes`) for each decoder layer.
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
+ Sequence of hidden-states at the output of the last layer of the decoder of the model.
+ """
+
+ loss: torch.FloatTensor | None = None
+ loss_dict: dict | None = None
+ logits: torch.FloatTensor | None = None
+ pred_boxes: torch.FloatTensor | None = None
+ auxiliary_outputs: list[dict] | None = None
+ last_hidden_state: torch.FloatTensor | None = None
+ decoder_hidden_states: tuple[torch.FloatTensor] | None = None
+ decoder_attentions: tuple[torch.FloatTensor] | None = None
+ cross_attentions: tuple[torch.FloatTensor] | None = None
+ encoder_last_hidden_state: torch.FloatTensor | None = None
+ encoder_hidden_states: tuple[torch.FloatTensor] | None = None
+ encoder_attentions: tuple[torch.FloatTensor] | None = None
+
+
+@auto_docstring(
+ custom_intro="""
+ Output type of [`ConditionalDetrForSegmentation`].
+ """
+)
+@dataclass
+class ConditionalDetrSegmentationOutput(ModelOutput):
+ r"""
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` are provided)):
+ Total loss as a linear combination of a negative log-likehood (cross-entropy) for class prediction and a
+ bounding box loss. The latter is defined as a linear combination of the L1 loss and the generalized
+ scale-invariant IoU loss.
+ loss_dict (`Dict`, *optional*):
+ A dictionary containing the individual losses. Useful for logging.
+ logits (`torch.FloatTensor` of shape `(batch_size, num_queries, num_classes + 1)`):
+ Classification logits (including no-object) for all queries.
+ pred_boxes (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)`):
+ Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height). These
+ values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding
+ possible padding). You can use [`~ConditionalDetrImageProcessor.post_process_object_detection`] to retrieve the
+ unnormalized bounding boxes.
+ pred_masks (`torch.FloatTensor` of shape `(batch_size, num_queries, height/4, width/4)`):
+ Segmentation masks logits for all queries. See also
+ [`~ConditionalDetrImageProcessor.post_process_semantic_segmentation`] or
+ [`~ConditionalDetrImageProcessor.post_process_instance_segmentation`]
+ [`~ConditionalDetrImageProcessor.post_process_panoptic_segmentation`] to evaluate semantic, instance and panoptic
+ segmentation masks respectively.
+ auxiliary_outputs (`list[Dict]`, *optional*):
+ Optional, only returned when auxiliary losses are activated (i.e. `config.auxiliary_loss` is set to `True`)
+ and labels are provided. It is a list of dictionaries containing the two above keys (`logits` and
+ `pred_boxes`) for each decoder layer.
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
+ Sequence of hidden-states at the output of the last layer of the decoder of the model.
+ """
+
+ loss: torch.FloatTensor | None = None
+ loss_dict: dict | None = None
+ logits: torch.FloatTensor | None = None
+ pred_boxes: torch.FloatTensor | None = None
+ pred_masks: torch.FloatTensor | None = None
+ auxiliary_outputs: list[dict] | None = None
+ last_hidden_state: torch.FloatTensor | None = None
+ decoder_hidden_states: tuple[torch.FloatTensor] | None = None
+ decoder_attentions: tuple[torch.FloatTensor] | None = None
+ cross_attentions: tuple[torch.FloatTensor] | None = None
+ encoder_last_hidden_state: torch.FloatTensor | None = None
+ encoder_hidden_states: tuple[torch.FloatTensor] | None = None
+ encoder_attentions: tuple[torch.FloatTensor] | None = None
+
+
+class ConditionalDetrFrozenBatchNorm2d(nn.Module):
+ """
+ BatchNorm2d where the batch statistics and the affine parameters are fixed.
+
+ Copy-paste from torchvision.misc.ops with added eps before rqsrt, without which any other models than
+ torchvision.models.resnet[18,34,50,101] produce nans.
+ """
+
+ def __init__(self, n):
+ super().__init__()
+ self.register_buffer("weight", torch.ones(n))
+ self.register_buffer("bias", torch.zeros(n))
+ self.register_buffer("running_mean", torch.zeros(n))
+ self.register_buffer("running_var", torch.ones(n))
+
+ def _load_from_state_dict(
+ self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs
+ ):
+ num_batches_tracked_key = prefix + "num_batches_tracked"
+ if num_batches_tracked_key in state_dict:
+ del state_dict[num_batches_tracked_key]
+
+ super()._load_from_state_dict(
+ state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs
+ )
+
+ def forward(self, x):
+ # move reshapes to the beginning
+ # to make it user-friendly
+ weight = self.weight.reshape(1, -1, 1, 1)
+ bias = self.bias.reshape(1, -1, 1, 1)
+ running_var = self.running_var.reshape(1, -1, 1, 1)
+ running_mean = self.running_mean.reshape(1, -1, 1, 1)
+ epsilon = 1e-5
+ scale = weight * (running_var + epsilon).rsqrt()
+ bias = bias - running_mean * scale
+ return x * scale + bias
+
+
+def replace_batch_norm(model):
+ r"""
+ Recursively replace all `torch.nn.BatchNorm2d` with `ConditionalDetrFrozenBatchNorm2d`.
+
+ Args:
+ model (torch.nn.Module):
+ input model
+ """
+ for name, module in model.named_children():
+ if isinstance(module, nn.BatchNorm2d):
+ new_module = ConditionalDetrFrozenBatchNorm2d(module.num_features)
+
+ if module.weight.device != torch.device("meta"):
+ new_module.weight.copy_(module.weight)
+ new_module.bias.copy_(module.bias)
+ new_module.running_mean.copy_(module.running_mean)
+ new_module.running_var.copy_(module.running_var)
+
+ model._modules[name] = new_module
+
+ if len(list(module.children())) > 0:
+ replace_batch_norm(module)
+
+
+class ConditionalDetrConvEncoder(nn.Module):
+ """
+ Convolutional backbone, using either the AutoBackbone API or one from the timm library.
+
+ nn.BatchNorm2d layers are replaced by ConditionalDetrFrozenBatchNorm2d as defined above.
+
+ """
+
+ def __init__(self, config):
+ super().__init__()
+
+ self.config = config
+
+ backbone = load_backbone(config)
+ self.intermediate_channel_sizes = backbone.channels
+
+ # replace batch norm by frozen batch norm
+ with torch.no_grad():
+ replace_batch_norm(backbone)
+
+ # We used to load with timm library directly instead of the AutoBackbone API
+ # so we need to unwrap the `backbone._backbone` module to load weights without mismatch
+ is_timm_model = False
+ if hasattr(backbone, "_backbone"):
+ backbone = backbone._backbone
+ is_timm_model = True
+ self.model = backbone
+
+ backbone_model_type = config.backbone_config.model_type
+ if "resnet" in backbone_model_type:
+ for name, parameter in self.model.named_parameters():
+ if is_timm_model:
+ if "layer2" not in name and "layer3" not in name and "layer4" not in name:
+ parameter.requires_grad_(False)
+ else:
+ if "stage.1" not in name and "stage.2" not in name and "stage.3" not in name:
+ parameter.requires_grad_(False)
+
+ def forward(self, pixel_values: torch.Tensor, pixel_mask: torch.Tensor):
+ # send pixel_values through the model to get list of feature maps
+ features = self.model(pixel_values)
+ if isinstance(features, dict):
+ features = features.feature_maps
+
+ out = []
+ for feature_map in features:
+ # downsample pixel_mask to match shape of corresponding feature_map
+ mask = nn.functional.interpolate(pixel_mask[None].float(), size=feature_map.shape[-2:]).to(torch.bool)[0]
+ out.append((feature_map, mask))
+ return out
+
+
+class ConditionalDetrSinePositionEmbedding(nn.Module):
+ """
+ This is a more standard version of the position embedding, very similar to the one used by the Attention is all you
+ need paper, generalized to work on images.
+ """
+
+ def __init__(
+ self,
+ num_position_features: int = 64,
+ temperature: int = 10000,
+ normalize: bool = False,
+ scale: float | None = None,
+ ):
+ super().__init__()
+ if scale is not None and normalize is False:
+ raise ValueError("normalize should be True if scale is passed")
+ self.num_position_features = num_position_features
+ self.temperature = temperature
+ self.normalize = normalize
+ self.scale = 2 * math.pi if scale is None else scale
+
+ @staticmethod
+ @compile_compatible_method_lru_cache(maxsize=1)
+ def build_sine_position_embedding(
+ shape: torch.Size,
+ device: torch.device | str,
+ dtype: torch.dtype,
+ num_position_features: int,
+ normalize: bool = False,
+ scale: float | None = None,
+ temperature: int = 10000,
+ mask: torch.Tensor | None = None,
+ ) -> torch.Tensor:
+ if mask is None:
+ mask = torch.ones((shape[0], shape[2], shape[3]), device=device, dtype=torch.bool)
+ y_embed = mask.cumsum(1, dtype=dtype)
+ x_embed = mask.cumsum(2, dtype=dtype)
+ if normalize:
+ eps = 1e-6
+ y_embed = y_embed / (y_embed[:, -1:, :] + eps) * scale
+ x_embed = x_embed / (x_embed[:, :, -1:] + eps) * scale
+
+ dim_t = torch.arange(num_position_features, dtype=torch.int64, device=device).to(dtype)
+ dim_t = temperature ** (2 * torch.div(dim_t, 2, rounding_mode="floor") / num_position_features)
+
+ pos_x = x_embed[:, :, :, None] / dim_t
+ pos_y = y_embed[:, :, :, None] / dim_t
+ pos_x = torch.stack((pos_x[:, :, :, 0::2].sin(), pos_x[:, :, :, 1::2].cos()), dim=4).flatten(3)
+ pos_y = torch.stack((pos_y[:, :, :, 0::2].sin(), pos_y[:, :, :, 1::2].cos()), dim=4).flatten(3)
+ pos = torch.cat((pos_y, pos_x), dim=3).permute(0, 3, 1, 2)
+ return pos
+
+ def forward(
+ self,
+ shape: torch.Size,
+ device: torch.device | str,
+ dtype: torch.dtype,
+ mask: torch.Tensor | None = None,
+ ) -> torch.Tensor:
+ return self.build_sine_position_embedding(
+ shape, device, dtype, self.num_position_features, self.normalize, self.scale, self.temperature, mask
+ )
+
+
+class ConditionalDetrLearnedPositionEmbedding(nn.Module):
+ """
+ This module learns positional embeddings up to a fixed maximum size.
+ """
+
+ def __init__(self, embedding_dim=256):
+ super().__init__()
+ self.row_embeddings = nn.Embedding(50, embedding_dim)
+ self.column_embeddings = nn.Embedding(50, embedding_dim)
+
+ @compile_compatible_method_lru_cache(maxsize=1)
+ def forward(
+ self,
+ shape: torch.Size,
+ device: torch.device | str,
+ dtype: torch.dtype,
+ mask: torch.Tensor | None = None,
+ ):
+ height, width = shape[-2:]
+ width_values = torch.arange(width, device=device)
+ height_values = torch.arange(height, device=device)
+ x_emb = self.column_embeddings(width_values)
+ y_emb = self.row_embeddings(height_values)
+ pos = torch.cat([x_emb.unsqueeze(0).repeat(height, 1, 1), y_emb.unsqueeze(1).repeat(1, width, 1)], dim=-1)
+ pos = pos.permute(2, 0, 1)
+ pos = pos.unsqueeze(0)
+ pos = pos.repeat(shape[0], 1, 1, 1)
+ return pos
+
+
+def eager_attention_forward(
+ module: nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: torch.Tensor | None,
+ scaling: float | None = None,
+ dropout: float = 0.0,
+ **kwargs: Unpack[TransformersKwargs],
+):
+ if scaling is None:
+ scaling = query.size(-1) ** -0.5
+
+ # Take the dot product between "query" and "key" to get the raw attention scores.
+ attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
+
+ if attention_mask is not None:
+ attn_weights = attn_weights + attention_mask
+
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
+
+ attn_output = torch.matmul(attn_weights, value)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+
+ return attn_output, attn_weights
+
+
+class ConditionalDetrSelfAttention(nn.Module):
+ """
+ Multi-headed self-attention from 'Attention Is All You Need' paper.
+
+ In CONDITIONAL_DETR, position embeddings are added to both queries and keys (but not values) in self-attention.
+ """
+
+ def __init__(
+ self,
+ config: ConditionalDetrConfig,
+ hidden_size: int,
+ num_attention_heads: int,
+ dropout: float = 0.0,
+ bias: bool = True,
+ ):
+ super().__init__()
+ self.config = config
+ self.head_dim = hidden_size // num_attention_heads
+ self.scaling = self.head_dim**-0.5
+ self.attention_dropout = dropout
+ self.is_causal = False
+
+ self.k_proj = nn.Linear(hidden_size, hidden_size, bias=bias)
+ self.v_proj = nn.Linear(hidden_size, hidden_size, bias=bias)
+ self.q_proj = nn.Linear(hidden_size, hidden_size, bias=bias)
+ self.o_proj = nn.Linear(hidden_size, hidden_size, bias=bias)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor | None = None,
+ position_embeddings: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor, torch.Tensor]:
+ """
+ Position embeddings are added to both queries and keys (but not values).
+ """
+ input_shape = hidden_states.shape[:-1]
+ hidden_shape = (*input_shape, -1, self.head_dim)
+
+ query_key_input = hidden_states + position_embeddings if position_embeddings is not None else hidden_states
+
+ query_states = self.q_proj(query_key_input).view(hidden_shape).transpose(1, 2)
+ key_states = self.k_proj(query_key_input).view(hidden_shape).transpose(1, 2)
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_states,
+ key_states,
+ value_states,
+ attention_mask,
+ dropout=0.0 if not self.training else self.attention_dropout,
+ scaling=self.scaling,
+ **kwargs,
+ )
+
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ attn_output = self.o_proj(attn_output)
+ return attn_output, attn_weights
+
+
+class ConditionalDetrDecoderSelfAttention(nn.Module):
+ """
+ Multi-headed self-attention for Conditional DETR decoder layers.
+
+ This attention module handles separate content and position projections, which are then combined
+ before applying standard self-attention. Position embeddings are added to both queries and keys.
+ """
+
+ def __init__(
+ self,
+ config: ConditionalDetrConfig,
+ hidden_size: int,
+ num_attention_heads: int,
+ dropout: float | int = 0.0,
+ ):
+ super().__init__()
+ self.config = config
+ self.hidden_size = hidden_size
+ self.head_dim = hidden_size // num_attention_heads
+ self.scaling = self.head_dim**-0.5
+ self.attention_dropout = dropout
+ self.is_causal = False
+
+ # Content and position projections
+ self.q_content_proj = nn.Linear(hidden_size, hidden_size)
+ self.q_pos_proj = nn.Linear(hidden_size, hidden_size)
+ self.k_content_proj = nn.Linear(hidden_size, hidden_size)
+ self.k_pos_proj = nn.Linear(hidden_size, hidden_size)
+ self.v_proj = nn.Linear(hidden_size, hidden_size)
+ self.o_proj = nn.Linear(hidden_size, hidden_size)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ query_position_embeddings: torch.Tensor,
+ attention_mask: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor, torch.Tensor]:
+ """
+ Args:
+ hidden_states (`torch.Tensor` of shape `(batch_size, num_queries, hidden_size)`):
+ Input hidden states from the decoder layer.
+ query_position_embeddings (`torch.Tensor` of shape `(batch_size, num_queries, hidden_size)`):
+ Position embeddings for queries and keys. Required (unlike standard attention). Processed through
+ separate position projections (`q_pos_proj`, `k_pos_proj`) and added to content projections.
+ attention_mask (`torch.Tensor` of shape `(batch_size, 1, num_queries, num_queries)`, *optional*):
+ Attention mask to avoid attending to padding tokens.
+ """
+ input_shape = hidden_states.shape[:-1]
+ hidden_shape = (*input_shape, -1, self.head_dim)
+
+ query_states = (
+ (self.q_content_proj(hidden_states) + self.q_pos_proj(query_position_embeddings))
+ .view(hidden_shape)
+ .transpose(1, 2)
+ )
+ key_states = (
+ (self.k_content_proj(hidden_states) + self.k_pos_proj(query_position_embeddings))
+ .view(hidden_shape)
+ .transpose(1, 2)
+ )
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_states,
+ key_states,
+ value_states,
+ attention_mask,
+ dropout=0.0 if not self.training else self.attention_dropout,
+ scaling=self.scaling,
+ **kwargs,
+ )
+
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ attn_output = self.o_proj(attn_output)
+ return attn_output, attn_weights
+
+
+class ConditionalDetrDecoderCrossAttention(nn.Module):
+ """
+ Multi-headed cross-attention for Conditional DETR decoder layers.
+
+ This attention module handles the special cross-attention logic in Conditional DETR:
+ - Separate content and position projections for queries and keys
+ - Concatenation of query sine embeddings with queries (doubling query dimension)
+ - Concatenation of key position embeddings with keys (doubling key dimension)
+ - Output dimension remains hidden_size despite doubled input dimensions
+ """
+
+ def __init__(
+ self,
+ config: ConditionalDetrConfig,
+ hidden_size: int,
+ num_attention_heads: int,
+ dropout: float | int = 0.0,
+ ):
+ super().__init__()
+ self.config = config
+ self.hidden_size = hidden_size
+ self.num_attention_heads = num_attention_heads
+ self.head_dim = hidden_size // num_attention_heads
+ self.attention_dropout = dropout
+ self.is_causal = False
+
+ # Content and position projections
+ self.q_content_proj = nn.Linear(hidden_size, hidden_size)
+ self.q_pos_proj = nn.Linear(hidden_size, hidden_size)
+ self.k_content_proj = nn.Linear(hidden_size, hidden_size)
+ self.k_pos_proj = nn.Linear(hidden_size, hidden_size)
+ self.v_proj = nn.Linear(hidden_size, hidden_size)
+ self.q_pos_sine_proj = nn.Linear(hidden_size, hidden_size)
+
+ # Output projection: input is hidden_size * 2 (from concatenated q/k), output is hidden_size
+ self.o_proj = nn.Linear(hidden_size, hidden_size)
+
+ # Compute scaling for expanded head_dim (q and k have doubled dimensions after concatenation)
+ # This matches the original Conditional DETR implementation where embed_dim * 2 is used
+ expanded_head_dim = (hidden_size * 2) // num_attention_heads
+ self.scaling = expanded_head_dim**-0.5
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: torch.Tensor,
+ query_sine_embed: torch.Tensor,
+ encoder_position_embeddings: torch.Tensor,
+ query_position_embeddings: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor, torch.Tensor]:
+ """
+ Args:
+ hidden_states (`torch.Tensor` of shape `(batch_size, num_queries, hidden_size)`):
+ Decoder hidden states (queries).
+ encoder_hidden_states (`torch.Tensor` of shape `(batch_size, encoder_seq_len, hidden_size)`):
+ Encoder output hidden states (keys and values).
+ query_sine_embed (`torch.Tensor` of shape `(batch_size, num_queries, hidden_size)`):
+ Sine position embeddings for queries. **Concatenated** (not added) with query content,
+ doubling the query dimension.
+ encoder_position_embeddings (`torch.Tensor` of shape `(batch_size, encoder_seq_len, hidden_size)`):
+ Position embeddings for keys. **Concatenated** (not added) with key content, doubling the key dimension.
+ query_position_embeddings (`torch.Tensor` of shape `(batch_size, num_queries, hidden_size)`, *optional*):
+ Additional position embeddings. When provided (first layer only), **added** to query content
+ before concatenation with `query_sine_embed`. Also causes `encoder_position_embeddings` to be
+ added to key content before concatenation.
+ attention_mask (`torch.Tensor` of shape `(batch_size, 1, num_queries, encoder_seq_len)`, *optional*):
+ Attention mask to avoid attending to padding tokens.
+ """
+ query_input_shape = hidden_states.shape[:-1]
+ kv_input_shape = encoder_hidden_states.shape[:-1]
+ query_hidden_shape = (*query_input_shape, self.num_attention_heads, self.head_dim)
+ kv_hidden_shape = (*kv_input_shape, self.num_attention_heads, self.head_dim)
+
+ # Apply content and position projections
+ query_input = self.q_content_proj(hidden_states)
+ key_input = self.k_content_proj(encoder_hidden_states)
+ value_states = self.v_proj(encoder_hidden_states)
+ key_pos = self.k_pos_proj(encoder_position_embeddings)
+
+ # Combine content and position embeddings
+ if query_position_embeddings is not None:
+ query_input = query_input + self.q_pos_proj(query_position_embeddings)
+ key_input = key_input + key_pos
+
+ # Reshape and concatenate position embeddings (doubling head_dim)
+ query_input = query_input.view(query_hidden_shape)
+ key_input = key_input.view(kv_hidden_shape)
+ query_sine_embed = self.q_pos_sine_proj(query_sine_embed).view(query_hidden_shape)
+ key_pos = key_pos.view(kv_hidden_shape)
+
+ query_states = torch.cat([query_input, query_sine_embed], dim=-1).view(*query_input_shape, -1)
+ key_states = torch.cat([key_input, key_pos], dim=-1).view(*kv_input_shape, -1)
+
+ # Reshape for attention computation
+ expanded_head_dim = query_states.shape[-1] // self.num_attention_heads
+ query_states = query_states.view(*query_input_shape, self.num_attention_heads, expanded_head_dim).transpose(
+ 1, 2
+ )
+ key_states = key_states.view(*kv_input_shape, self.num_attention_heads, expanded_head_dim).transpose(1, 2)
+ value_states = value_states.view(kv_hidden_shape).transpose(1, 2)
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_states,
+ key_states,
+ value_states,
+ attention_mask,
+ dropout=0.0 if not self.training else self.attention_dropout,
+ scaling=self.scaling,
+ **kwargs,
+ )
+
+ attn_output = attn_output.reshape(*query_input_shape, -1).contiguous()
+ attn_output = self.o_proj(attn_output)
+ return attn_output, attn_weights
+
+
+class ConditionalDetrMLP(nn.Module):
+ def __init__(self, config: ConditionalDetrConfig, hidden_size: int, intermediate_size: int):
+ super().__init__()
+ self.fc1 = nn.Linear(hidden_size, intermediate_size)
+ self.fc2 = nn.Linear(intermediate_size, hidden_size)
+ self.activation_fn = ACT2FN[config.activation_function]
+ self.activation_dropout = config.activation_dropout
+ self.dropout = config.dropout
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
+ hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
+ hidden_states = self.fc2(hidden_states)
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
+ return hidden_states
+
+
+class ConditionalDetrEncoderLayer(GradientCheckpointingLayer):
+ def __init__(self, config: ConditionalDetrConfig):
+ super().__init__()
+ self.hidden_size = config.d_model
+ self.self_attn = ConditionalDetrSelfAttention(
+ config=config,
+ hidden_size=self.hidden_size,
+ num_attention_heads=config.encoder_attention_heads,
+ dropout=config.attention_dropout,
+ )
+ self.self_attn_layer_norm = nn.LayerNorm(self.hidden_size)
+ self.dropout = config.dropout
+ self.mlp = ConditionalDetrMLP(config, self.hidden_size, config.encoder_ffn_dim)
+ self.final_layer_norm = nn.LayerNorm(self.hidden_size)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor,
+ spatial_position_embeddings: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.Tensor:
+ """
+ Args:
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, hidden_size)`
+ attention_mask (`torch.FloatTensor`): attention mask of size
+ `(batch, 1, target_len, source_len)` where padding elements are indicated by very large negative
+ values.
+ spatial_position_embeddings (`torch.FloatTensor`, *optional*):
+ Spatial position embeddings (2D positional encodings of image locations), to be added to both
+ the queries and keys in self-attention (but not to values).
+ """
+ residual = hidden_states
+ hidden_states, _ = self.self_attn(
+ hidden_states=hidden_states,
+ attention_mask=attention_mask,
+ position_embeddings=spatial_position_embeddings,
+ **kwargs,
+ )
+
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
+ hidden_states = residual + hidden_states
+ hidden_states = self.self_attn_layer_norm(hidden_states)
+
+ residual = hidden_states
+ hidden_states = self.mlp(hidden_states)
+ hidden_states = residual + hidden_states
+ hidden_states = self.final_layer_norm(hidden_states)
+
+ if self.training:
+ if not torch.isfinite(hidden_states).all():
+ clamp_value = torch.finfo(hidden_states.dtype).max - 1000
+ hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
+
+ return hidden_states
+
+
+class ConditionalDetrDecoderLayer(GradientCheckpointingLayer):
+ def __init__(self, config: ConditionalDetrConfig):
+ super().__init__()
+ self.hidden_size = config.d_model
+ self.self_attn = ConditionalDetrDecoderSelfAttention(
+ config=config,
+ hidden_size=self.hidden_size,
+ num_attention_heads=config.decoder_attention_heads,
+ dropout=config.attention_dropout,
+ )
+ self.dropout = config.dropout
+
+ self.self_attn_layer_norm = nn.LayerNorm(self.hidden_size)
+ self.encoder_attn = ConditionalDetrDecoderCrossAttention(
+ config=config,
+ hidden_size=self.hidden_size,
+ num_attention_heads=config.decoder_attention_heads,
+ dropout=config.attention_dropout,
+ )
+ self.encoder_attn_layer_norm = nn.LayerNorm(self.hidden_size)
+ self.mlp = ConditionalDetrMLP(config, self.hidden_size, config.decoder_ffn_dim)
+ self.final_layer_norm = nn.LayerNorm(self.hidden_size)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor | None = None,
+ spatial_position_embeddings: torch.Tensor | None = None,
+ query_position_embeddings: torch.Tensor | None = None,
+ query_sine_embed: torch.Tensor | None = None,
+ encoder_hidden_states: torch.Tensor | None = None,
+ encoder_attention_mask: torch.Tensor | None = None,
+ is_first: bool | None = False,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.Tensor:
+ """
+ Args:
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(seq_len, batch, embed_dim)`
+ attention_mask (`torch.FloatTensor`): attention mask of size
+ `(batch, 1, target_len, source_len)` where padding elements are indicated by very large negative
+ values.
+ spatial_position_embeddings (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
+ Spatial position embeddings (2D positional encodings) that are added to the queries and keys in each self-attention layer.
+ query_position_embeddings (`torch.FloatTensor`, *optional*):
+ object_queries that are added to the queries and keys
+ in the self-attention layer.
+ encoder_hidden_states (`torch.FloatTensor`):
+ cross attention input to the layer of shape `(seq_len, batch, embed_dim)`
+ encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size
+ `(batch, 1, target_len, source_len)` where padding elements are indicated by very large negative
+ values.
+ output_attentions (`bool`, *optional*):
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
+ returned tensors for more detail.
+ """
+ residual = hidden_states
+
+ hidden_states, _ = self.self_attn(
+ hidden_states=hidden_states,
+ query_position_embeddings=query_position_embeddings,
+ attention_mask=attention_mask,
+ **kwargs,
+ )
+
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
+ hidden_states = residual + hidden_states
+ hidden_states = self.self_attn_layer_norm(hidden_states)
+
+ if encoder_hidden_states is not None:
+ residual = hidden_states
+
+ hidden_states, _ = self.encoder_attn(
+ hidden_states=hidden_states,
+ encoder_hidden_states=encoder_hidden_states,
+ attention_mask=encoder_attention_mask,
+ query_sine_embed=query_sine_embed,
+ encoder_position_embeddings=spatial_position_embeddings,
+ # Only pass query_position_embeddings for the first layer
+ query_position_embeddings=query_position_embeddings if is_first else None,
+ **kwargs,
+ )
+
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
+ hidden_states = residual + hidden_states
+ hidden_states = self.encoder_attn_layer_norm(hidden_states)
+
+ # Fully Connected
+ residual = hidden_states
+ hidden_states = self.mlp(hidden_states)
+ hidden_states = residual + hidden_states
+ hidden_states = self.final_layer_norm(hidden_states)
+
+ return hidden_states
+
+
+class ConditionalDetrMLPPredictionHead(nn.Module):
+ """
+ Very simple multi-layer perceptron (MLP, also called FFN), used to predict the normalized center coordinates,
+ height and width of a bounding box w.r.t. an image.
+
+ """
+
+ def __init__(self, input_dim, hidden_dim, output_dim, num_layers):
+ super().__init__()
+ self.num_layers = num_layers
+ h = [hidden_dim] * (num_layers - 1)
+ self.layers = nn.ModuleList(nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim]))
+
+ def forward(self, x):
+ for i, layer in enumerate(self.layers):
+ x = nn.functional.relu(layer(x)) if i < self.num_layers - 1 else layer(x)
+ return x
+
+
+class ConditionalDetrConvBlock(nn.Module):
+ """Basic conv block: Conv3x3 -> GroupNorm -> Activation."""
+
+ def __init__(self, in_channels: int, out_channels: int, activation: str = "relu"):
+ super().__init__()
+ self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1)
+ self.norm = nn.GroupNorm(min(8, out_channels), out_channels)
+ self.activation = ACT2FN[activation]
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ return self.activation(self.norm(self.conv(x)))
+
+
+class ConditionalDetrFPNFusionStage(nn.Module):
+ """Single FPN fusion stage combining low-resolution features with high-resolution FPN features."""
+
+ def __init__(self, fpn_channels: int, current_channels: int, output_channels: int, activation: str = "relu"):
+ super().__init__()
+ self.fpn_adapter = nn.Conv2d(fpn_channels, current_channels, kernel_size=1)
+ self.refine = ConditionalDetrConvBlock(current_channels, output_channels, activation)
+
+ def forward(self, features: torch.Tensor, fpn_features: torch.Tensor) -> torch.Tensor:
+ """
+ Args:
+ features: Current features to upsample, shape (B*Q, current_channels, H_in, W_in)
+ fpn_features: FPN features at target resolution, shape (B*Q, fpn_channels, H_out, W_out)
+
+ Returns:
+ Fused and refined features, shape (B*Q, output_channels, H_out, W_out)
+ """
+ fpn_features = self.fpn_adapter(fpn_features)
+ features = nn.functional.interpolate(features, size=fpn_features.shape[-2:], mode="nearest")
+ return self.refine(fpn_features + features)
+
+
+class ConditionalDetrMaskHeadSmallConv(nn.Module):
+ """
+ Segmentation mask head that generates per-query masks using FPN-based progressive upsampling.
+
+ Combines attention maps (spatial localization) with encoder features (semantics) and progressively
+ upsamples through multiple scales, fusing with FPN features for high-resolution detail.
+ """
+
+ def __init__(
+ self,
+ input_channels: int,
+ fpn_channels: list[int],
+ hidden_size: int,
+ activation_function: str = "relu",
+ ):
+ super().__init__()
+ if input_channels % 8 != 0:
+ raise ValueError(f"input_channels must be divisible by 8, got {input_channels}")
+
+ self.conv1 = ConditionalDetrConvBlock(input_channels, input_channels, activation_function)
+ self.conv2 = ConditionalDetrConvBlock(input_channels, hidden_size // 2, activation_function)
+
+ # Progressive channel reduction: /2 -> /4 -> /8 -> /16
+ self.fpn_stages = nn.ModuleList(
+ [
+ ConditionalDetrFPNFusionStage(
+ fpn_channels[0], hidden_size // 2, hidden_size // 4, activation_function
+ ),
+ ConditionalDetrFPNFusionStage(
+ fpn_channels[1], hidden_size // 4, hidden_size // 8, activation_function
+ ),
+ ConditionalDetrFPNFusionStage(
+ fpn_channels[2], hidden_size // 8, hidden_size // 16, activation_function
+ ),
+ ]
+ )
+
+ self.output_conv = nn.Conv2d(hidden_size // 16, 1, kernel_size=3, padding=1)
+
+ def forward(
+ self,
+ features: torch.Tensor,
+ attention_masks: torch.Tensor,
+ fpn_features: list[torch.Tensor],
+ ) -> torch.Tensor:
+ """
+ Args:
+ features: Encoder output features, shape (batch_size, hidden_size, H, W)
+ attention_masks: Cross-attention maps from decoder, shape (batch_size, num_queries, num_heads, H, W)
+ fpn_features: List of 3 FPN features from low to high resolution, each (batch_size, C, H, W)
+
+ Returns:
+ Predicted masks, shape (batch_size * num_queries, 1, output_H, output_W)
+ """
+ num_queries = attention_masks.shape[1]
+
+ # Expand to (batch_size * num_queries) dimension
+ features = features.unsqueeze(1).expand(-1, num_queries, -1, -1, -1).flatten(0, 1)
+ attention_masks = attention_masks.flatten(0, 1)
+ fpn_features = [
+ fpn_feat.unsqueeze(1).expand(-1, num_queries, -1, -1, -1).flatten(0, 1) for fpn_feat in fpn_features
+ ]
+
+ hidden_states = torch.cat([features, attention_masks], dim=1)
+ hidden_states = self.conv1(hidden_states)
+ hidden_states = self.conv2(hidden_states)
+
+ for fpn_stage, fpn_feat in zip(self.fpn_stages, fpn_features):
+ hidden_states = fpn_stage(hidden_states, fpn_feat)
+
+ return self.output_conv(hidden_states)
+
+
+class ConditionalDetrMHAttentionMap(nn.Module):
+ """This is a 2D attention module, which only returns the attention softmax (no multiplication by value)"""
+
+ def __init__(
+ self,
+ hidden_size: int,
+ num_attention_heads: int,
+ dropout: float = 0.0,
+ bias: bool = True,
+ ):
+ super().__init__()
+ self.head_dim = hidden_size // num_attention_heads
+ self.scaling = self.head_dim**-0.5
+ self.attention_dropout = dropout
+
+ self.q_proj = nn.Linear(hidden_size, hidden_size, bias=bias)
+ self.k_proj = nn.Linear(hidden_size, hidden_size, bias=bias)
+
+ def forward(
+ self, query_states: torch.Tensor, key_states: torch.Tensor, attention_mask: torch.Tensor | None = None
+ ):
+ query_hidden_shape = (*query_states.shape[:-1], -1, self.head_dim)
+ key_hidden_shape = (key_states.shape[0], -1, self.head_dim, *key_states.shape[-2:])
+
+ query_states = self.q_proj(query_states).view(query_hidden_shape)
+ key_states = nn.functional.conv2d(
+ key_states, self.k_proj.weight.unsqueeze(-1).unsqueeze(-1), self.k_proj.bias
+ ).view(key_hidden_shape)
+
+ batch_size, num_queries, num_heads, head_dim = query_states.shape
+ _, _, _, height, width = key_states.shape
+ query_shape = (batch_size * num_heads, num_queries, head_dim)
+ key_shape = (batch_size * num_heads, height * width, head_dim)
+ attn_weights_shape = (batch_size, num_heads, num_queries, height, width)
+
+ query = query_states.transpose(1, 2).contiguous().view(query_shape)
+ key = key_states.permute(0, 1, 3, 4, 2).contiguous().view(key_shape)
+
+ attn_weights = (
+ (torch.matmul(query * self.scaling, key.transpose(1, 2))).view(attn_weights_shape).transpose(1, 2)
+ )
+
+ if attention_mask is not None:
+ attn_weights = attn_weights + attention_mask
+
+ attn_weights = nn.functional.softmax(attn_weights.flatten(2), dim=-1).view(attn_weights.size())
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
+
+ return attn_weights
+
+
+@auto_docstring
+class ConditionalDetrPreTrainedModel(PreTrainedModel):
+ config: ConditionalDetrConfig
+ base_model_prefix = "model"
+ main_input_name = "pixel_values"
+ input_modalities = ("image",)
+ _no_split_modules = [r"ConditionalDetrConvEncoder", r"ConditionalDetrEncoderLayer", r"ConditionalDetrDecoderLayer"]
+ supports_gradient_checkpointing = True
+ _supports_sdpa = True
+ _supports_flash_attn = True
+ _supports_attention_backend = True
+ _supports_flex_attn = True # Uses create_bidirectional_masks for attention masking
+ _keys_to_ignore_on_load_unexpected = [
+ r"detr\.model\.backbone\.model\.layer\d+\.0\.downsample\.1\.num_batches_tracked"
+ ]
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ std = self.config.init_std
+ xavier_std = self.config.init_xavier_std
+
+ if isinstance(module, ConditionalDetrMaskHeadSmallConv):
+ # ConditionalDetrMaskHeadSmallConv uses kaiming initialization for all its Conv2d layers
+ for m in module.modules():
+ if isinstance(m, nn.Conv2d):
+ init.kaiming_uniform_(m.weight, a=1)
+ if m.bias is not None:
+ init.constant_(m.bias, 0)
+ elif isinstance(module, ConditionalDetrMHAttentionMap):
+ init.zeros_(module.k_proj.bias)
+ init.zeros_(module.q_proj.bias)
+ init.xavier_uniform_(module.k_proj.weight, gain=xavier_std)
+ init.xavier_uniform_(module.q_proj.weight, gain=xavier_std)
+ elif isinstance(module, ConditionalDetrLearnedPositionEmbedding):
+ init.uniform_(module.row_embeddings.weight)
+ init.uniform_(module.column_embeddings.weight)
+ elif isinstance(module, (nn.Linear, nn.Conv2d)):
+ init.normal_(module.weight, mean=0.0, std=std)
+ if module.bias is not None:
+ init.zeros_(module.bias)
+ elif isinstance(module, nn.Embedding):
+ init.normal_(module.weight, mean=0.0, std=std)
+ # Here we need the check explicitly, as we slice the weight in the `zeros_` call, so it looses the flag
+ if module.padding_idx is not None and not getattr(module.weight, "_is_hf_initialized", False):
+ init.zeros_(module.weight[module.padding_idx])
+ elif isinstance(module, (nn.LayerNorm, nn.GroupNorm)):
+ init.ones_(module.weight)
+ init.zeros_(module.bias)
+
+
+class ConditionalDetrEncoder(ConditionalDetrPreTrainedModel):
+ """
+ Transformer encoder that processes a flattened feature map from a vision backbone, composed of a stack of
+ [`ConditionalDetrEncoderLayer`] modules.
+
+ Args:
+ config (`ConditionalDetrConfig`): Model configuration object.
+ """
+
+ _can_record_outputs = {"hidden_states": ConditionalDetrEncoderLayer, "attentions": ConditionalDetrSelfAttention}
+
+ def __init__(self, config: ConditionalDetrConfig):
+ super().__init__(config)
+
+ self.dropout = config.dropout
+ self.layers = nn.ModuleList([ConditionalDetrEncoderLayer(config) for _ in range(config.encoder_layers)])
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @merge_with_config_defaults
+ @capture_outputs
+ def forward(
+ self,
+ inputs_embeds=None,
+ attention_mask=None,
+ spatial_position_embeddings=None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> BaseModelOutput:
+ r"""
+ Args:
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
+ Flattened feature map (output of the backbone + projection layer) that is passed to the encoder.
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Mask to avoid performing attention on padding pixel features. Mask values selected in `[0, 1]`:
+
+ - 1 for pixel features that are real (i.e. **not masked**),
+ - 0 for pixel features that are padding (i.e. **masked**).
+
+ [What are attention masks?](../glossary#attention-mask)
+ spatial_position_embeddings (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
+ Spatial position embeddings (2D positional encodings) that are added to the queries and keys in each self-attention layer.
+ """
+ hidden_states = inputs_embeds
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
+
+ attention_mask = create_bidirectional_mask(
+ config=self.config,
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ )
+
+ for encoder_layer in self.layers:
+ # we add spatial_position_embeddings as extra input to the encoder_layer
+ hidden_states = encoder_layer(
+ hidden_states, attention_mask, spatial_position_embeddings=spatial_position_embeddings, **kwargs
+ )
+
+ return BaseModelOutput(last_hidden_state=hidden_states)
+
+
+def encode_sinusoidal_position_embedding(
+ pos_tensor: torch.Tensor,
+ num_pos_feats: int = 128,
+ temperature: int = 10000,
+) -> torch.Tensor:
+ """Sinusoidal position embeddings from normalized anchor coordinates.
+
+ Each coordinate in `pos_tensor` is independently encoded with ``num_pos_feats``
+ interleaved sin/cos components; per-coordinate embeddings are concatenated.
+ Handles 2-D ``(x, y)`` and N-D ``(x, y, w, h)`` inputs. For 2-D+ inputs the
+ x and y embeddings are swapped to follow the DETR ``[pos_y, pos_x, ...]`` convention.
+
+ Args:
+ pos_tensor: Normalized coordinates in ``[0, 1]``, shape ``(..., n_coords)``.
+ num_pos_feats: Embedding dimension per coordinate.
+ temperature: Base for the frequency decay.
+
+ Returns:
+ Tensor of shape ``(..., n_coords * num_pos_feats)``, same dtype as input.
+ """
+ scale = 2 * math.pi
+ dim_t = torch.arange(num_pos_feats, dtype=torch.float32, device=pos_tensor.device)
+ dim_t = temperature ** (2 * torch.div(dim_t, 2, rounding_mode="floor") / num_pos_feats)
+
+ coords = pos_tensor.unbind(-1) # list of (...,) tensors
+ embeddings = [coord[..., None] * scale / dim_t for coord in coords] # each (..., num_pos_feats)
+ embeddings = [
+ torch.stack((e[..., 0::2].sin(), e[..., 1::2].cos()), dim=-1).flatten(-2) for e in embeddings
+ ] # each (..., num_pos_feats)
+
+ if len(embeddings) >= 2:
+ embeddings[0], embeddings[1] = embeddings[1], embeddings[0]
+
+ return torch.cat(embeddings, dim=-1).to(pos_tensor.dtype)
+
+
+class ConditionalDetrDecoder(ConditionalDetrPreTrainedModel):
+ """
+ Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`ConditionalDetrDecoderLayer`].
+
+ The decoder updates the query embeddings through multiple self-attention and cross-attention layers.
+
+ Some small tweaks for Conditional DETR:
+
+ - object_queries and query_position_embeddings are added to the forward pass.
+ - if self.config.auxiliary_loss is set to True, also returns a stack of activations from all decoding layers.
+
+ Args:
+ config: ConditionalDetrConfig
+ """
+
+ _can_record_outputs = {
+ "hidden_states": ConditionalDetrDecoderLayer,
+ "attentions": OutputRecorder(ConditionalDetrDecoderSelfAttention, layer_name="self_attn", index=1),
+ "cross_attentions": OutputRecorder(ConditionalDetrDecoderCrossAttention, layer_name="encoder_attn", index=1),
+ }
+
+ def __init__(self, config: ConditionalDetrConfig):
+ super().__init__(config)
+ self.hidden_size = config.d_model
+
+ self.dropout = config.dropout
+ self.layerdrop = config.decoder_layerdrop
+
+ self.layers = nn.ModuleList([ConditionalDetrDecoderLayer(config) for _ in range(config.decoder_layers)])
+ # in Conditional DETR, the decoder uses layernorm after the last decoder layer output
+ self.layernorm = nn.LayerNorm(config.d_model)
+
+ # query_scale is the FFN applied on f to generate transformation T
+ self.query_scale = ConditionalDetrMLPPredictionHead(self.hidden_size, self.hidden_size, self.hidden_size, 2)
+ self.ref_point_head = ConditionalDetrMLPPredictionHead(self.hidden_size, self.hidden_size, 2, 2)
+ for layer_id in range(config.decoder_layers - 1):
+ # Set q_pos_proj to None for layers after the first (only first layer uses query position embeddings)
+ self.layers[layer_id + 1].encoder_attn.q_pos_proj = None
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @merge_with_config_defaults
+ @capture_outputs
+ def forward(
+ self,
+ inputs_embeds=None,
+ attention_mask=None,
+ encoder_hidden_states=None,
+ encoder_attention_mask=None,
+ spatial_position_embeddings=None,
+ object_queries_position_embeddings=None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> ConditionalDetrDecoderOutput:
+ r"""
+ Args:
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
+ The query embeddings that are passed into the decoder.
+
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Mask to avoid performing attention on certain queries. Mask values selected in `[0, 1]`:
+
+ - 1 for queries that are **not masked**,
+ - 0 for queries that are **masked**.
+
+ [What are attention masks?](../glossary#attention-mask)
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
+ of the decoder.
+ encoder_attention_mask (`torch.LongTensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):
+ Mask to avoid performing cross-attention on padding pixel_values of the encoder. Mask values selected
+ in `[0, 1]`:
+
+ - 1 for pixels that are real (i.e. **not masked**),
+ - 0 for pixels that are padding (i.e. **masked**).
+
+ spatial_position_embeddings (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
+ Spatial position embeddings that are added to the queries and keys in each cross-attention layer.
+ object_queries_position_embeddings (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_size)`):
+ , *optional*): Position embeddings that are added to the queries and keys in each self-attention layer.
+ """
+ if inputs_embeds is not None:
+ hidden_states = inputs_embeds
+
+ # expand encoder attention mask
+ if encoder_hidden_states is not None and encoder_attention_mask is not None:
+ # [batch_size, seq_len] -> [batch_size, 1, target_seq_len, source_seq_len]
+ encoder_attention_mask = create_bidirectional_mask(
+ self.config,
+ inputs_embeds,
+ encoder_attention_mask,
+ )
+
+ # optional intermediate hidden states
+ intermediate = () if self.config.auxiliary_loss else None
+
+ reference_points_before_sigmoid = self.ref_point_head(
+ object_queries_position_embeddings
+ ) # [num_queries, batch_size, 2]
+ reference_points = reference_points_before_sigmoid.sigmoid().transpose(0, 1)
+ obj_center = reference_points[..., :2].transpose(0, 1)
+ # get sine embedding for the query vector
+ query_sine_embed_before_transformation = encode_sinusoidal_position_embedding(
+ obj_center, num_pos_feats=self.config.d_model // 2
+ )
+
+ for idx, decoder_layer in enumerate(self.layers):
+ if self.training:
+ dropout_probability = torch.rand([])
+ if dropout_probability < self.layerdrop:
+ continue
+ if idx == 0:
+ pos_transformation = 1
+ else:
+ pos_transformation = self.query_scale(hidden_states)
+ # apply transformation
+ query_sine_embed = query_sine_embed_before_transformation * pos_transformation
+
+ hidden_states = decoder_layer(
+ hidden_states,
+ None,
+ spatial_position_embeddings,
+ object_queries_position_embeddings,
+ query_sine_embed,
+ encoder_hidden_states, # as a positional argument for gradient checkpointing
+ encoder_attention_mask=encoder_attention_mask,
+ is_first=(idx == 0),
+ **kwargs,
+ )
+
+ if self.config.auxiliary_loss:
+ hidden_states = self.layernorm(hidden_states)
+ intermediate += (hidden_states,)
+
+ # finally, apply layernorm
+ hidden_states = self.layernorm(hidden_states)
+
+ # stack intermediate decoder activations
+ if self.config.auxiliary_loss:
+ intermediate = torch.stack(intermediate)
+
+ return ConditionalDetrDecoderOutput(
+ last_hidden_state=hidden_states,
+ intermediate_hidden_states=intermediate,
+ reference_points=reference_points,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ The bare CONDITIONAL_DETR Model (consisting of a backbone and encoder-decoder Transformer) outputting raw hidden-states without
+ any specific head on top.
+ """
+)
+class ConditionalDetrModel(ConditionalDetrPreTrainedModel):
+ def __init__(self, config: ConditionalDetrConfig):
+ super().__init__(config)
+
+ self.backbone = ConditionalDetrConvEncoder(config)
+
+ if config.position_embedding_type == "sine":
+ self.position_embedding = ConditionalDetrSinePositionEmbedding(config.d_model // 2, normalize=True)
+ elif config.position_embedding_type == "learned":
+ self.position_embedding = ConditionalDetrLearnedPositionEmbedding(config.d_model // 2)
+ else:
+ raise ValueError(f"Not supported {config.position_embedding_type}")
+ self.query_position_embeddings = nn.Embedding(config.num_queries, config.d_model)
+ self.input_projection = nn.Conv2d(self.backbone.intermediate_channel_sizes[-1], config.d_model, kernel_size=1)
+
+ self.encoder = ConditionalDetrEncoder(config)
+ self.decoder = ConditionalDetrDecoder(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def freeze_backbone(self):
+ for _, param in self.backbone.model.named_parameters():
+ param.requires_grad_(False)
+
+ def unfreeze_backbone(self):
+ for _, param in self.backbone.model.named_parameters():
+ param.requires_grad_(True)
+
+ @auto_docstring
+ @can_return_tuple
+ def forward(
+ self,
+ pixel_values: torch.FloatTensor,
+ pixel_mask: torch.LongTensor | None = None,
+ decoder_attention_mask: torch.LongTensor | None = None,
+ encoder_outputs: torch.FloatTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ decoder_inputs_embeds: torch.FloatTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> ConditionalDetrModelOutput:
+ r"""
+ decoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, num_queries)`, *optional*):
+ Not used by default. Can be used to mask object queries.
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
+ Optionally, instead of passing the flattened feature map (output of the backbone + projection layer), you
+ can choose to directly pass a flattened representation of an image.
+ decoder_inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_size)`, *optional*):
+ Optionally, instead of initializing the queries with a tensor of zeros, you can choose to directly pass an
+ embedded representation.
+
+ Examples:
+
+ ```python
+ >>> from transformers import AutoImageProcessor, AutoModel
+ >>> from PIL import Image
+ >>> import httpx
+ >>> from io import BytesIO
+
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
+ >>> with httpx.stream("GET", url) as response:
+ ... image = Image.open(BytesIO(response.read()))
+
+ >>> image_processor = AutoImageProcessor.from_pretrained("microsoft/conditional-detr-resnet-50")
+ >>> model = AutoModel.from_pretrained("microsoft/conditional-detr-resnet-50")
+
+ >>> # prepare image for the model
+ >>> inputs = image_processor(images=image, return_tensors="pt")
+
+ >>> # forward pass
+ >>> outputs = model(**inputs)
+
+ >>> # the last hidden states are the final query embeddings of the Transformer decoder
+ >>> # these are of shape (batch_size, num_queries, hidden_size)
+ >>> last_hidden_states = outputs.last_hidden_state
+ >>> list(last_hidden_states.shape)
+ [1, 300, 256]
+ ```"""
+ batch_size, num_channels, height, width = pixel_values.shape
+ device = pixel_values.device
+
+ if pixel_mask is None:
+ pixel_mask = torch.ones(((batch_size, height, width)), device=device)
+
+ # First, sent pixel_values + pixel_mask through Backbone to obtain the features
+ # pixel_values should be of shape (batch_size, num_channels, height, width)
+ # pixel_mask should be of shape (batch_size, height, width)
+ features = self.backbone(pixel_values, pixel_mask)
+
+ # get final feature map and downsampled mask
+ feature_map, mask = features[-1]
+
+ if mask is None:
+ raise ValueError("Backbone does not return downsampled pixel mask")
+
+ # Second, apply 1x1 convolution to reduce the channel dimension to d_model (256 by default)
+ projected_feature_map = self.input_projection(feature_map)
+
+ # Generate position embeddings
+ spatial_position_embeddings = (
+ self.position_embedding(shape=feature_map.shape, device=device, dtype=pixel_values.dtype, mask=mask)
+ .flatten(2)
+ .transpose(1, 2)
+ )
+
+ # Third, flatten the feature map of shape NxCxHxW to NxCxHW, and permute it to NxHWxC
+ # In other words, turn their shape into (batch_size, sequence_length, hidden_size)
+ flattened_features = projected_feature_map.flatten(2).transpose(1, 2)
+
+ flattened_mask = mask.flatten(1)
+
+ # Fourth, sent flattened_features + flattened_mask + spatial_position_embeddings through encoder
+ # flattened_features is a Tensor of shape (batch_size, height*width, hidden_size)
+ # flattened_mask is a Tensor of shape (batch_size, height*width)
+ if encoder_outputs is None:
+ encoder_outputs = self.encoder(
+ inputs_embeds=flattened_features,
+ attention_mask=flattened_mask,
+ spatial_position_embeddings=spatial_position_embeddings,
+ **kwargs,
+ )
+ # If the user passed a tuple for encoder_outputs, we wrap it in a BaseModelOutput
+ elif not isinstance(encoder_outputs, BaseModelOutput):
+ encoder_outputs = BaseModelOutput(
+ last_hidden_state=encoder_outputs[0],
+ hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
+ attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
+ )
+
+ # Fifth, sent query embeddings through the decoder (which is conditioned on the encoder output)
+ object_queries_position_embeddings = self.query_position_embeddings.weight.unsqueeze(0).repeat(
+ batch_size, 1, 1
+ )
+ queries = torch.zeros_like(object_queries_position_embeddings)
+
+ # decoder outputs consists of (dec_features, dec_hidden, dec_attn)
+ decoder_outputs = self.decoder(
+ inputs_embeds=queries,
+ attention_mask=None,
+ spatial_position_embeddings=spatial_position_embeddings,
+ object_queries_position_embeddings=object_queries_position_embeddings,
+ encoder_hidden_states=encoder_outputs.last_hidden_state,
+ encoder_attention_mask=flattened_mask,
+ **kwargs,
+ )
+
+ return ConditionalDetrModelOutput(
+ last_hidden_state=decoder_outputs.last_hidden_state,
+ decoder_hidden_states=decoder_outputs.hidden_states,
+ decoder_attentions=decoder_outputs.attentions,
+ cross_attentions=decoder_outputs.cross_attentions,
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
+ encoder_hidden_states=encoder_outputs.hidden_states,
+ encoder_attentions=encoder_outputs.attentions,
+ intermediate_hidden_states=decoder_outputs.intermediate_hidden_states,
+ reference_points=decoder_outputs.reference_points,
+ )
+
+
+def inverse_sigmoid(x, eps=1e-5):
+ x = x.clamp(min=0, max=1)
+ x1 = x.clamp(min=eps)
+ x2 = (1 - x).clamp(min=eps)
+ return torch.log(x1 / x2)
+
+
+@auto_docstring(
+ custom_intro="""
+ CONDITIONAL_DETR Model (consisting of a backbone and encoder-decoder Transformer) with object detection heads on top, for tasks
+ such as COCO detection.
+ """
+)
+class ConditionalDetrForObjectDetection(ConditionalDetrPreTrainedModel):
+ def __init__(self, config: ConditionalDetrConfig):
+ super().__init__(config)
+
+ # CONDITIONAL_DETR encoder-decoder model
+ self.model = ConditionalDetrModel(config)
+ self.class_labels_classifier = nn.Linear(config.d_model, config.num_labels)
+ self.bbox_predictor = ConditionalDetrMLPPredictionHead(
+ input_dim=config.d_model, hidden_dim=config.d_model, output_dim=4, num_layers=3
+ )
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ @can_return_tuple
+ def forward(
+ self,
+ pixel_values: torch.FloatTensor,
+ pixel_mask: torch.LongTensor | None = None,
+ decoder_attention_mask: torch.LongTensor | None = None,
+ encoder_outputs: torch.FloatTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ decoder_inputs_embeds: torch.FloatTensor | None = None,
+ labels: list[dict] | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> ConditionalDetrObjectDetectionOutput:
+ r"""
+ decoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, num_queries)`, *optional*):
+ Not used by default. Can be used to mask object queries.
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
+ Optionally, instead of passing the flattened feature map (output of the backbone + projection layer), you
+ can choose to directly pass a flattened representation of an image.
+ decoder_inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_size)`, *optional*):
+ Optionally, instead of initializing the queries with a tensor of zeros, you can choose to directly pass an
+ embedded representation.
+ labels (`list[Dict]` of len `(batch_size,)`, *optional*):
+ Labels for computing the bipartite matching loss. List of dicts, each dictionary containing at least the
+ following 2 keys: 'class_labels' and 'boxes' (the class labels and bounding boxes of an image in the batch
+ respectively). The class labels themselves should be a `torch.LongTensor` of len `(number of bounding boxes
+ in the image,)` and the boxes a `torch.FloatTensor` of shape `(number of bounding boxes in the image, 4)`.
+
+ Examples:
+
+ ```python
+ >>> from transformers import AutoImageProcessor, AutoModelForObjectDetection
+ >>> from PIL import Image
+ >>> import httpx
+ >>> from io import BytesIO
+
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
+ >>> with httpx.stream("GET", url) as response:
+ ... image = Image.open(BytesIO(response.read()))
+
+ >>> image_processor = AutoImageProcessor.from_pretrained("microsoft/conditional-detr-resnet-50")
+ >>> model = AutoModelForObjectDetection.from_pretrained("microsoft/conditional-detr-resnet-50")
+
+ >>> inputs = image_processor(images=image, return_tensors="pt")
+
+ >>> outputs = model(**inputs)
+
+ >>> # convert outputs (bounding boxes and class logits) to Pascal VOC format (xmin, ymin, xmax, ymax)
+ >>> target_sizes = torch.tensor([image.size[::-1]])
+ >>> results = image_processor.post_process_object_detection(outputs, threshold=0.5, target_sizes=target_sizes)[
+ ... 0
+ ... ]
+ >>> for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
+ ... box = [round(i, 2) for i in box.tolist()]
+ ... print(
+ ... f"Detected {model.config.id2label[label.item()]} with confidence "
+ ... f"{round(score.item(), 3)} at location {box}"
+ ... )
+ Detected remote with confidence 0.833 at location [38.31, 72.1, 177.63, 118.45]
+ Detected cat with confidence 0.831 at location [9.2, 51.38, 321.13, 469.0]
+ Detected cat with confidence 0.804 at location [340.3, 16.85, 642.93, 370.95]
+ Detected remote with confidence 0.683 at location [334.48, 73.49, 366.37, 190.01]
+ Detected couch with confidence 0.535 at location [0.52, 1.19, 640.35, 475.1]
+ ```"""
+ # First, sent images through CONDITIONAL_DETR base model to obtain encoder + decoder outputs
+ outputs = self.model(
+ pixel_values,
+ pixel_mask=pixel_mask,
+ decoder_attention_mask=decoder_attention_mask,
+ encoder_outputs=encoder_outputs,
+ inputs_embeds=inputs_embeds,
+ decoder_inputs_embeds=decoder_inputs_embeds,
+ **kwargs,
+ )
+
+ sequence_output = outputs[0]
+
+ # class logits + predicted bounding boxes
+ logits = self.class_labels_classifier(sequence_output)
+
+ reference = outputs.reference_points
+ reference_before_sigmoid = inverse_sigmoid(reference).transpose(0, 1)
+
+ hs = sequence_output
+ tmp = self.bbox_predictor(hs)
+ tmp[..., :2] += reference_before_sigmoid
+ pred_boxes = tmp.sigmoid()
+ # pred_boxes = self.bbox_predictor(sequence_output).sigmoid()
+
+ loss, loss_dict, auxiliary_outputs = None, None, None
+ if labels is not None:
+ outputs_class, outputs_coord = None, None
+ if self.config.auxiliary_loss:
+ outputs_coords = []
+ intermediate = outputs.intermediate_hidden_states
+ outputs_class = self.class_labels_classifier(intermediate)
+ for lvl in range(intermediate.shape[0]):
+ tmp = self.bbox_predictor(intermediate[lvl])
+ tmp[..., :2] += reference_before_sigmoid
+ outputs_coord = tmp.sigmoid()
+ outputs_coords.append(outputs_coord)
+ outputs_coord = torch.stack(outputs_coords)
+ loss, loss_dict, auxiliary_outputs = self.loss_function(
+ logits, labels, self.device, pred_boxes, self.config, outputs_class, outputs_coord
+ )
+
+ return ConditionalDetrObjectDetectionOutput(
+ loss=loss,
+ loss_dict=loss_dict,
+ logits=logits,
+ pred_boxes=pred_boxes,
+ auxiliary_outputs=auxiliary_outputs,
+ last_hidden_state=outputs.last_hidden_state,
+ decoder_hidden_states=outputs.decoder_hidden_states,
+ decoder_attentions=outputs.decoder_attentions,
+ cross_attentions=outputs.cross_attentions,
+ encoder_last_hidden_state=outputs.encoder_last_hidden_state,
+ encoder_hidden_states=outputs.encoder_hidden_states,
+ encoder_attentions=outputs.encoder_attentions,
+ )
+
+ # taken from https://github.com/Atten4Vis/conditionalDETR/blob/master/models/conditional_detr.py
+ def _set_aux_loss(self, outputs_class, outputs_coord):
+ return [{"logits": a, "pred_boxes": b} for a, b in zip(outputs_class[:-1], outputs_coord[:-1])]
+
+
+@auto_docstring(
+ custom_intro="""
+ CONDITIONAL_DETR Model (consisting of a backbone and encoder-decoder Transformer) with a segmentation head on top, for tasks
+ such as COCO panoptic.
+ """
+)
+class ConditionalDetrForSegmentation(ConditionalDetrPreTrainedModel):
+ def __init__(self, config: ConditionalDetrConfig):
+ super().__init__(config)
+
+ # object detection model
+ self.conditional_detr = ConditionalDetrForObjectDetection(config)
+
+ # segmentation head
+ hidden_size, number_of_heads = config.d_model, config.encoder_attention_heads
+ intermediate_channel_sizes = self.conditional_detr.model.backbone.intermediate_channel_sizes
+
+ self.mask_head = ConditionalDetrMaskHeadSmallConv(
+ input_channels=hidden_size + number_of_heads,
+ fpn_channels=intermediate_channel_sizes[::-1][-3:],
+ hidden_size=hidden_size,
+ activation_function=config.activation_function,
+ )
+
+ self.bbox_attention = ConditionalDetrMHAttentionMap(hidden_size, number_of_heads, dropout=0.0)
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ @can_return_tuple
+ def forward(
+ self,
+ pixel_values: torch.FloatTensor,
+ pixel_mask: torch.LongTensor | None = None,
+ decoder_attention_mask: torch.FloatTensor | None = None,
+ encoder_outputs: torch.FloatTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ decoder_inputs_embeds: torch.FloatTensor | None = None,
+ labels: list[dict] | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.FloatTensor] | ConditionalDetrSegmentationOutput:
+ r"""
+ decoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, num_queries)`, *optional*):
+ Mask to avoid performing attention on certain object queries in the decoder. Mask values selected in `[0, 1]`:
+
+ - 1 for queries that are **not masked**,
+ - 0 for queries that are **masked**.
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
+ Kept for backward compatibility, but cannot be used for segmentation, as segmentation requires
+ multi-scale features from the backbone that are not available when bypassing it with inputs_embeds.
+ decoder_inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_size)`, *optional*):
+ Optionally, instead of initializing the queries with a tensor of zeros, you can choose to directly pass an
+ embedded representation. Useful for tasks that require custom query initialization.
+ labels (`list[Dict]` of len `(batch_size,)`, *optional*):
+ Labels for computing the bipartite matching loss, DICE/F-1 loss and Focal loss. List of dicts, each
+ dictionary containing at least the following 3 keys: 'class_labels', 'boxes' and 'masks' (the class labels,
+ bounding boxes and segmentation masks of an image in the batch respectively). The class labels themselves
+ should be a `torch.LongTensor` of len `(number of bounding boxes in the image,)`, the boxes a
+ `torch.FloatTensor` of shape `(number of bounding boxes in the image, 4)` and the masks a
+ `torch.FloatTensor` of shape `(number of bounding boxes in the image, height, width)`.
+
+ Examples:
+
+ ```python
+ >>> import io
+ >>> import httpx
+ >>> from io import BytesIO
+ >>> from PIL import Image
+ >>> import torch
+ >>> import numpy
+
+ >>> from transformers import AutoImageProcessor, ConditionalDetrForSegmentation
+ >>> from transformers.image_transforms import rgb_to_id
+
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
+ >>> with httpx.stream("GET", url) as response:
+ ... image = Image.open(BytesIO(response.read()))
+
+ >>> image_processor = AutoImageProcessor.from_pretrained("facebook/conditional_detr-resnet-50-panoptic")
+ >>> model = ConditionalDetrForSegmentation.from_pretrained("facebook/conditional_detr-resnet-50-panoptic")
+
+ >>> # prepare image for the model
+ >>> inputs = image_processor(images=image, return_tensors="pt")
+
+ >>> # forward pass
+ >>> outputs = model(**inputs)
+
+ >>> # Use the `post_process_panoptic_segmentation` method of the `image_processor` to retrieve post-processed panoptic segmentation maps
+ >>> # Segmentation results are returned as a list of dictionaries
+ >>> result = image_processor.post_process_panoptic_segmentation(outputs, target_sizes=[(300, 500)])
+
+ >>> # A tensor of shape (height, width) where each value denotes a segment id, filled with -1 if no segment is found
+ >>> panoptic_seg = result[0]["segmentation"]
+ >>> panoptic_seg.shape
+ torch.Size([300, 500])
+ >>> # Get prediction score and segment_id to class_id mapping of each segment
+ >>> panoptic_segments_info = result[0]["segments_info"]
+ >>> len(panoptic_segments_info)
+ 5
+ ```"""
+
+ batch_size, num_channels, height, width = pixel_values.shape
+ device = pixel_values.device
+
+ if pixel_mask is None:
+ pixel_mask = torch.ones((batch_size, height, width), device=device)
+
+ vision_features = self.conditional_detr.model.backbone(pixel_values, pixel_mask)
+ feature_map, mask = vision_features[-1]
+
+ # Apply 1x1 conv to map (batch_size, C, H, W) -> (batch_size, hidden_size, H, W), then flatten to (batch_size, HW, hidden_size)
+ projected_feature_map = self.conditional_detr.model.input_projection(feature_map)
+ flattened_features = projected_feature_map.flatten(2).transpose(1, 2)
+ spatial_position_embeddings = (
+ self.conditional_detr.model.position_embedding(
+ shape=feature_map.shape, device=device, dtype=pixel_values.dtype, mask=mask
+ )
+ .flatten(2)
+ .transpose(1, 2)
+ )
+ flattened_mask = mask.flatten(1)
+
+ if encoder_outputs is None:
+ encoder_outputs = self.conditional_detr.model.encoder(
+ inputs_embeds=flattened_features,
+ attention_mask=flattened_mask,
+ spatial_position_embeddings=spatial_position_embeddings,
+ **kwargs,
+ )
+
+ object_queries_position_embeddings = self.conditional_detr.model.query_position_embeddings.weight.unsqueeze(
+ 0
+ ).repeat(batch_size, 1, 1)
+
+ # Use decoder_inputs_embeds as queries if provided, otherwise initialize with zeros
+ if decoder_inputs_embeds is not None:
+ queries = decoder_inputs_embeds
+ else:
+ queries = torch.zeros_like(object_queries_position_embeddings)
+
+ decoder_outputs = self.conditional_detr.model.decoder(
+ inputs_embeds=queries,
+ attention_mask=decoder_attention_mask,
+ spatial_position_embeddings=spatial_position_embeddings,
+ object_queries_position_embeddings=object_queries_position_embeddings,
+ encoder_hidden_states=encoder_outputs.last_hidden_state,
+ encoder_attention_mask=flattened_mask,
+ **kwargs,
+ )
+
+ sequence_output = decoder_outputs[0]
+
+ logits = self.conditional_detr.class_labels_classifier(sequence_output)
+ pred_boxes = self.conditional_detr.bbox_predictor(sequence_output).sigmoid()
+
+ height, width = feature_map.shape[-2:]
+ memory = encoder_outputs.last_hidden_state.transpose(1, 2).view(batch_size, self.config.d_model, height, width)
+ attention_mask = flattened_mask.view(batch_size, height, width)
+
+ if attention_mask is not None:
+ min_dtype = torch.finfo(memory.dtype).min
+ attention_mask = torch.where(
+ attention_mask.unsqueeze(1).unsqueeze(1),
+ torch.tensor(0.0, device=memory.device, dtype=memory.dtype),
+ min_dtype,
+ )
+
+ bbox_mask = self.bbox_attention(sequence_output, memory, attention_mask=attention_mask)
+
+ seg_masks = self.mask_head(
+ features=projected_feature_map,
+ attention_masks=bbox_mask,
+ fpn_features=[vision_features[2][0], vision_features[1][0], vision_features[0][0]],
+ )
+
+ pred_masks = seg_masks.view(
+ batch_size, self.conditional_detr.config.num_queries, seg_masks.shape[-2], seg_masks.shape[-1]
+ )
+
+ loss, loss_dict, auxiliary_outputs = None, None, None
+ if labels is not None:
+ outputs_class, outputs_coord = None, None
+ if self.config.auxiliary_loss:
+ intermediate = decoder_outputs.intermediate_hidden_states
+ outputs_class = self.conditional_detr.class_labels_classifier(intermediate)
+ outputs_coord = self.conditional_detr.bbox_predictor(intermediate).sigmoid()
+ loss, loss_dict, auxiliary_outputs = self.loss_function(
+ logits, labels, device, pred_boxes, pred_masks, self.config, outputs_class, outputs_coord
+ )
+
+ return ConditionalDetrSegmentationOutput(
+ loss=loss,
+ loss_dict=loss_dict,
+ logits=logits,
+ pred_boxes=pred_boxes,
+ pred_masks=pred_masks,
+ auxiliary_outputs=auxiliary_outputs,
+ last_hidden_state=decoder_outputs.last_hidden_state,
+ decoder_hidden_states=decoder_outputs.hidden_states,
+ decoder_attentions=decoder_outputs.attentions,
+ cross_attentions=decoder_outputs.cross_attentions,
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
+ encoder_hidden_states=encoder_outputs.hidden_states,
+ encoder_attentions=encoder_outputs.attentions,
+ )
+
+
+__all__ = [
+ "ConditionalDetrForObjectDetection",
+ "ConditionalDetrForSegmentation",
+ "ConditionalDetrModel",
+ "ConditionalDetrPreTrainedModel",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/conditional_detr/modular_conditional_detr.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/conditional_detr/modular_conditional_detr.py
new file mode 100644
index 0000000000000000000000000000000000000000..25fbe16c3e6dbdffa3b9777843268496d8dcd644
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/conditional_detr/modular_conditional_detr.py
@@ -0,0 +1,1122 @@
+# Copyright 2022 Microsoft Research Asia and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import math
+from collections.abc import Callable
+
+import torch
+from torch import nn
+
+from ...image_transforms import (
+ center_to_corners_format,
+)
+from ...masking_utils import create_bidirectional_mask
+from ...modeling_outputs import (
+ BaseModelOutput,
+)
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS
+from ...processing_utils import Unpack
+from ...utils import (
+ TensorType,
+ TransformersKwargs,
+ auto_docstring,
+ logging,
+ requires_backends,
+)
+from ...utils.generic import can_return_tuple, merge_with_config_defaults
+from ...utils.import_utils import requires
+from ...utils.output_capturing import OutputRecorder, capture_outputs
+from ..deformable_detr.modeling_deformable_detr import inverse_sigmoid
+from ..detr.image_processing_detr import DetrImageProcessor
+from ..detr.image_processing_pil_detr import DetrImageProcessorPil
+from ..detr.modeling_detr import (
+ DetrConvEncoder,
+ DetrDecoderLayer,
+ DetrDecoderOutput,
+ DetrEncoder,
+ DetrEncoderLayer,
+ DetrForObjectDetection,
+ DetrForSegmentation,
+ DetrLearnedPositionEmbedding,
+ DetrMLP,
+ DetrMLPPredictionHead,
+ DetrModel,
+ DetrModelOutput,
+ DetrObjectDetectionOutput,
+ DetrPreTrainedModel,
+ DetrSegmentationOutput,
+ DetrSelfAttention,
+ DetrSinePositionEmbedding,
+ eager_attention_forward,
+)
+from .configuration_conditional_detr import ConditionalDetrConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+def encode_sinusoidal_position_embedding(
+ pos_tensor: torch.Tensor,
+ num_pos_feats: int = 128,
+ temperature: int = 10000,
+) -> torch.Tensor:
+ """Sinusoidal position embeddings from normalized anchor coordinates.
+
+ Each coordinate in `pos_tensor` is independently encoded with ``num_pos_feats``
+ interleaved sin/cos components; per-coordinate embeddings are concatenated.
+ Handles 2-D ``(x, y)`` and N-D ``(x, y, w, h)`` inputs. For 2-D+ inputs the
+ x and y embeddings are swapped to follow the DETR ``[pos_y, pos_x, ...]`` convention.
+
+ Args:
+ pos_tensor: Normalized coordinates in ``[0, 1]``, shape ``(..., n_coords)``.
+ num_pos_feats: Embedding dimension per coordinate.
+ temperature: Base for the frequency decay.
+
+ Returns:
+ Tensor of shape ``(..., n_coords * num_pos_feats)``, same dtype as input.
+ """
+ scale = 2 * math.pi
+ dim_t = torch.arange(num_pos_feats, dtype=torch.float32, device=pos_tensor.device)
+ dim_t = temperature ** (2 * torch.div(dim_t, 2, rounding_mode="floor") / num_pos_feats)
+
+ coords = pos_tensor.unbind(-1) # list of (...,) tensors
+ embeddings = [coord[..., None] * scale / dim_t for coord in coords] # each (..., num_pos_feats)
+ embeddings = [
+ torch.stack((e[..., 0::2].sin(), e[..., 1::2].cos()), dim=-1).flatten(-2) for e in embeddings
+ ] # each (..., num_pos_feats)
+
+ if len(embeddings) >= 2:
+ embeddings[0], embeddings[1] = embeddings[1], embeddings[0]
+
+ return torch.cat(embeddings, dim=-1).to(pos_tensor.dtype)
+
+
+class ConditionalDetrImageProcessor(DetrImageProcessor):
+ def post_process_object_detection(
+ self, outputs, threshold: float = 0.5, target_sizes: TensorType | list[tuple] = None, top_k: int = 100
+ ):
+ """
+ Converts the raw output of [`ConditionalDetrForObjectDetection`] into final bounding boxes in (top_left_x,
+ top_left_y, bottom_right_x, bottom_right_y) format. Only supports PyTorch.
+
+ Args:
+ outputs ([`ConditionalDetrObjectDetectionOutput`]):
+ Raw outputs of the model.
+ threshold (`float`, *optional*):
+ Score threshold to keep object detection predictions.
+ target_sizes (`torch.Tensor` or `list[tuple[int, int]]`, *optional*):
+ Tensor of shape `(batch_size, 2)` or list of tuples (`tuple[int, int]`) containing the target size
+ (height, width) of each image in the batch. If left to None, predictions will not be resized.
+ top_k (`int`, *optional*, defaults to 100):
+ Keep only top k bounding boxes before filtering by thresholding.
+
+ Returns:
+ `list[Dict]`: A list of dictionaries, each dictionary containing the scores, labels and boxes for an image
+ in the batch as predicted by the model.
+ """
+ out_logits, out_bbox = outputs.logits, outputs.pred_boxes
+
+ if target_sizes is not None:
+ if len(out_logits) != len(target_sizes):
+ raise ValueError(
+ "Make sure that you pass in as many target sizes as the batch dimension of the logits"
+ )
+
+ prob = out_logits.sigmoid()
+ prob = prob.view(out_logits.shape[0], -1)
+ k_value = min(top_k, prob.size(1))
+ topk_values, topk_indexes = torch.topk(prob, k_value, dim=1)
+ scores = topk_values
+ topk_boxes = torch.div(topk_indexes, out_logits.shape[2], rounding_mode="floor")
+ labels = topk_indexes % out_logits.shape[2]
+ boxes = center_to_corners_format(out_bbox)
+ boxes = torch.gather(boxes, 1, topk_boxes.unsqueeze(-1).repeat(1, 1, 4))
+
+ # and from relative [0, 1] to absolute [0, height] coordinates
+ if target_sizes is not None:
+ if isinstance(target_sizes, list):
+ img_h = torch.Tensor([i[0] for i in target_sizes])
+ img_w = torch.Tensor([i[1] for i in target_sizes])
+ else:
+ img_h, img_w = target_sizes.unbind(1)
+ scale_fct = torch.stack([img_w, img_h, img_w, img_h], dim=1).to(boxes.device)
+ boxes = boxes * scale_fct[:, None, :]
+
+ results = []
+ for s, l, b in zip(scores, labels, boxes):
+ score = s[s > threshold]
+ label = l[s > threshold]
+ box = b[s > threshold]
+ results.append({"scores": score, "labels": label, "boxes": box})
+
+ return results
+
+ def post_process_semantic_segmentation(self, outputs, target_sizes: list[tuple[int, int]] | None = None):
+ """
+ Converts the output of [`ConditionalDetrForSegmentation`] into semantic segmentation maps. Only supports PyTorch.
+
+ Args:
+ outputs ([`ConditionalDetrForSegmentation`]):
+ Raw outputs of the model.
+ target_sizes (`list[tuple[int, int]]`, *optional*):
+ A list of tuples (`tuple[int, int]`) containing the target size (height, width) of each image in the
+ batch. If unset, predictions will not be resized.
+ Returns:
+ `list[torch.Tensor]`:
+ A list of length `batch_size`, where each item is a semantic segmentation map of shape (height, width)
+ corresponding to the target_sizes entry (if `target_sizes` is specified). Each entry of each
+ `torch.Tensor` correspond to a semantic class id.
+ """
+ class_queries_logits = outputs.logits # [batch_size, num_queries, num_classes]
+ masks_queries_logits = outputs.pred_masks # [batch_size, num_queries, height, width]
+
+ # Conditional DETR does not have a null class, so we use all classes
+ masks_classes = class_queries_logits.softmax(dim=-1)
+ masks_probs = masks_queries_logits.sigmoid() # [batch_size, num_queries, height, width]
+
+ # Semantic segmentation logits of shape (batch_size, num_classes, height, width)
+ segmentation = torch.einsum("bqc, bqhw -> bchw", masks_classes, masks_probs)
+ batch_size = class_queries_logits.shape[0]
+
+ # Resize logits and compute semantic segmentation maps
+ if target_sizes is not None:
+ if batch_size != len(target_sizes):
+ raise ValueError(
+ "Make sure that you pass in as many target sizes as the batch dimension of the logits"
+ )
+
+ semantic_segmentation = []
+ for idx in range(batch_size):
+ resized_logits = nn.functional.interpolate(
+ segmentation[idx].unsqueeze(dim=0), size=target_sizes[idx], mode="bilinear", align_corners=False
+ )
+ semantic_map = resized_logits[0].argmax(dim=0)
+ semantic_segmentation.append(semantic_map)
+ else:
+ semantic_segmentation = segmentation.argmax(dim=1)
+ semantic_segmentation = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0])]
+
+ return semantic_segmentation
+
+
+class ConditionalDetrImageProcessorPil(DetrImageProcessorPil):
+ @requires(backends=("torch",))
+ def post_process_object_detection(
+ self, outputs, threshold: float = 0.5, target_sizes: TensorType | list[tuple] = None, top_k: int = 100
+ ):
+ """
+ Converts the raw output of [`ConditionalDetrForObjectDetection`] into final bounding boxes in (top_left_x,
+ top_left_y, bottom_right_x, bottom_right_y) format. Only supports PyTorch.
+
+ Args:
+ outputs ([`ConditionalDetrObjectDetectionOutput`]):
+ Raw outputs of the model.
+ threshold (`float`, *optional*):
+ Score threshold to keep object detection predictions.
+ target_sizes (`torch.Tensor` or `list[tuple[int, int]]`, *optional*):
+ Tensor of shape `(batch_size, 2)` or list of tuples (`tuple[int, int]`) containing the target size
+ (height, width) of each image in the batch. If left to None, predictions will not be resized.
+ top_k (`int`, *optional*, defaults to 100):
+ Keep only top k bounding boxes before filtering by thresholding.
+
+ Returns:
+ `list[Dict]`: A list of dictionaries, each dictionary containing the scores, labels and boxes for an image
+ in the batch as predicted by the model.
+ """
+ requires_backends(self, ["torch"])
+ out_logits, out_bbox = outputs.logits, outputs.pred_boxes
+
+ if target_sizes is not None:
+ if len(out_logits) != len(target_sizes):
+ raise ValueError(
+ "Make sure that you pass in as many target sizes as the batch dimension of the logits"
+ )
+
+ prob = out_logits.sigmoid()
+ prob = prob.view(out_logits.shape[0], -1)
+ k_value = min(top_k, prob.size(1))
+ topk_values, topk_indexes = torch.topk(prob, k_value, dim=1)
+ scores = topk_values
+ topk_boxes = torch.div(topk_indexes, out_logits.shape[2], rounding_mode="floor")
+ labels = topk_indexes % out_logits.shape[2]
+ boxes = center_to_corners_format(out_bbox)
+ boxes = torch.gather(boxes, 1, topk_boxes.unsqueeze(-1).repeat(1, 1, 4))
+
+ # and from relative [0, 1] to absolute [0, height] coordinates
+ if target_sizes is not None:
+ if isinstance(target_sizes, list):
+ img_h = torch.Tensor([i[0] for i in target_sizes])
+ img_w = torch.Tensor([i[1] for i in target_sizes])
+ else:
+ img_h, img_w = target_sizes.unbind(1)
+ scale_fct = torch.stack([img_w, img_h, img_w, img_h], dim=1).to(boxes.device)
+ boxes = boxes * scale_fct[:, None, :]
+
+ results = []
+ for s, l, b in zip(scores, labels, boxes):
+ score = s[s > threshold]
+ label = l[s > threshold]
+ box = b[s > threshold]
+ results.append({"scores": score, "labels": label, "boxes": box})
+
+ return results
+
+ @requires(backends=("torch",))
+ def post_process_semantic_segmentation(self, outputs, target_sizes: list[tuple[int, int]] | None = None):
+ """
+ Converts the output of [`ConditionalDetrForSegmentation`] into semantic segmentation maps. Only supports PyTorch.
+
+ Args:
+ outputs ([`ConditionalDetrForSegmentation`]):
+ Raw outputs of the model.
+ target_sizes (`list[tuple[int, int]]`, *optional*):
+ A list of tuples (`tuple[int, int]`) containing the target size (height, width) of each image in the
+ batch. If unset, predictions will not be resized.
+ Returns:
+ `list[torch.Tensor]`:
+ A list of length `batch_size`, where each item is a semantic segmentation map of shape (height, width)
+ corresponding to the target_sizes entry (if `target_sizes` is specified). Each entry of each
+ `torch.Tensor` correspond to a semantic class id.
+ """
+ requires_backends(self, ["torch"])
+ class_queries_logits = outputs.logits # [batch_size, num_queries, num_classes]
+ masks_queries_logits = outputs.pred_masks # [batch_size, num_queries, height, width]
+
+ # Conditional DETR does not have a null class, so we use all classes
+ masks_classes = class_queries_logits.softmax(dim=-1)
+ masks_probs = masks_queries_logits.sigmoid() # [batch_size, num_queries, height, width]
+
+ # Semantic segmentation logits of shape (batch_size, num_classes, height, width)
+ segmentation = torch.einsum("bqc, bqhw -> bchw", masks_classes, masks_probs)
+ batch_size = class_queries_logits.shape[0]
+
+ # Resize logits and compute semantic segmentation maps
+ if target_sizes is not None:
+ if batch_size != len(target_sizes):
+ raise ValueError(
+ "Make sure that you pass in as many target sizes as the batch dimension of the logits"
+ )
+
+ semantic_segmentation = []
+ for idx in range(batch_size):
+ resized_logits = nn.functional.interpolate(
+ segmentation[idx].unsqueeze(dim=0), size=target_sizes[idx], mode="bilinear", align_corners=False
+ )
+ semantic_map = resized_logits[0].argmax(dim=0)
+ semantic_segmentation.append(semantic_map)
+ else:
+ semantic_segmentation = segmentation.argmax(dim=1)
+ semantic_segmentation = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0])]
+
+ return semantic_segmentation
+
+
+class ConditionalDetrDecoderOutput(DetrDecoderOutput):
+ r"""
+ cross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` and `config.add_cross_attention=True` is passed or when `config.output_attentions=True`):
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
+ sequence_length)`. Attentions weights of the decoder's cross-attention layer, after the attention softmax,
+ used to compute the weighted average in the cross-attention heads.
+ intermediate_hidden_states (`torch.FloatTensor` of shape `(config.decoder_layers, batch_size, num_queries, hidden_size)`, *optional*, returned when `config.auxiliary_loss=True`):
+ Intermediate decoder activations, i.e. the output of each decoder layer, each of them gone through a
+ layernorm.
+ reference_points (`torch.FloatTensor` of shape `(config.decoder_layers, batch_size, num_queries, 2 (anchor points))`):
+ Reference points (reference points of each layer of the decoder).
+ """
+
+ reference_points: tuple[torch.FloatTensor] | None = None
+
+
+class ConditionalDetrModelOutput(DetrModelOutput):
+ r"""
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
+ Sequence of hidden-states at the output of the last layer of the decoder of the model.
+ intermediate_hidden_states (`torch.FloatTensor` of shape `(config.decoder_layers, batch_size, sequence_length, hidden_size)`, *optional*, returned when `config.auxiliary_loss=True`):
+ Intermediate decoder activations, i.e. the output of each decoder layer, each of them gone through a
+ layernorm.
+ reference_points (`torch.FloatTensor` of shape `(config.decoder_layers, batch_size, num_queries, 2 (anchor points))`):
+ Reference points (reference points of each layer of the decoder).
+ """
+
+ reference_points: tuple[torch.FloatTensor] | None = None
+
+
+class ConditionalDetrObjectDetectionOutput(DetrObjectDetectionOutput):
+ pass
+
+
+class ConditionalDetrSegmentationOutput(DetrSegmentationOutput):
+ pass
+
+
+class ConditionalDetrConvEncoder(DetrConvEncoder):
+ pass
+
+
+class ConditionalDetrSinePositionEmbedding(DetrSinePositionEmbedding):
+ pass
+
+
+class ConditionalDetrLearnedPositionEmbedding(DetrLearnedPositionEmbedding):
+ pass
+
+
+class ConditionalDetrSelfAttention(DetrSelfAttention):
+ pass
+
+
+class ConditionalDetrDecoderSelfAttention(nn.Module):
+ """
+ Multi-headed self-attention for Conditional DETR decoder layers.
+
+ This attention module handles separate content and position projections, which are then combined
+ before applying standard self-attention. Position embeddings are added to both queries and keys.
+ """
+
+ def __init__(
+ self,
+ config: ConditionalDetrConfig,
+ hidden_size: int,
+ num_attention_heads: int,
+ dropout: float | int = 0.0,
+ ):
+ super().__init__()
+ self.config = config
+ self.hidden_size = hidden_size
+ self.head_dim = hidden_size // num_attention_heads
+ self.scaling = self.head_dim**-0.5
+ self.attention_dropout = dropout
+ self.is_causal = False
+
+ # Content and position projections
+ self.q_content_proj = nn.Linear(hidden_size, hidden_size)
+ self.q_pos_proj = nn.Linear(hidden_size, hidden_size)
+ self.k_content_proj = nn.Linear(hidden_size, hidden_size)
+ self.k_pos_proj = nn.Linear(hidden_size, hidden_size)
+ self.v_proj = nn.Linear(hidden_size, hidden_size)
+ self.o_proj = nn.Linear(hidden_size, hidden_size)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ query_position_embeddings: torch.Tensor,
+ attention_mask: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor, torch.Tensor]:
+ """
+ Args:
+ hidden_states (`torch.Tensor` of shape `(batch_size, num_queries, hidden_size)`):
+ Input hidden states from the decoder layer.
+ query_position_embeddings (`torch.Tensor` of shape `(batch_size, num_queries, hidden_size)`):
+ Position embeddings for queries and keys. Required (unlike standard attention). Processed through
+ separate position projections (`q_pos_proj`, `k_pos_proj`) and added to content projections.
+ attention_mask (`torch.Tensor` of shape `(batch_size, 1, num_queries, num_queries)`, *optional*):
+ Attention mask to avoid attending to padding tokens.
+ """
+ input_shape = hidden_states.shape[:-1]
+ hidden_shape = (*input_shape, -1, self.head_dim)
+
+ query_states = (
+ (self.q_content_proj(hidden_states) + self.q_pos_proj(query_position_embeddings))
+ .view(hidden_shape)
+ .transpose(1, 2)
+ )
+ key_states = (
+ (self.k_content_proj(hidden_states) + self.k_pos_proj(query_position_embeddings))
+ .view(hidden_shape)
+ .transpose(1, 2)
+ )
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_states,
+ key_states,
+ value_states,
+ attention_mask,
+ dropout=0.0 if not self.training else self.attention_dropout,
+ scaling=self.scaling,
+ **kwargs,
+ )
+
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ attn_output = self.o_proj(attn_output)
+ return attn_output, attn_weights
+
+
+class ConditionalDetrDecoderCrossAttention(nn.Module):
+ """
+ Multi-headed cross-attention for Conditional DETR decoder layers.
+
+ This attention module handles the special cross-attention logic in Conditional DETR:
+ - Separate content and position projections for queries and keys
+ - Concatenation of query sine embeddings with queries (doubling query dimension)
+ - Concatenation of key position embeddings with keys (doubling key dimension)
+ - Output dimension remains hidden_size despite doubled input dimensions
+ """
+
+ def __init__(
+ self,
+ config: ConditionalDetrConfig,
+ hidden_size: int,
+ num_attention_heads: int,
+ dropout: float | int = 0.0,
+ ):
+ super().__init__()
+ self.config = config
+ self.hidden_size = hidden_size
+ self.num_attention_heads = num_attention_heads
+ self.head_dim = hidden_size // num_attention_heads
+ self.attention_dropout = dropout
+ self.is_causal = False
+
+ # Content and position projections
+ self.q_content_proj = nn.Linear(hidden_size, hidden_size)
+ self.q_pos_proj = nn.Linear(hidden_size, hidden_size)
+ self.k_content_proj = nn.Linear(hidden_size, hidden_size)
+ self.k_pos_proj = nn.Linear(hidden_size, hidden_size)
+ self.v_proj = nn.Linear(hidden_size, hidden_size)
+ self.q_pos_sine_proj = nn.Linear(hidden_size, hidden_size)
+
+ # Output projection: input is hidden_size * 2 (from concatenated q/k), output is hidden_size
+ self.o_proj = nn.Linear(hidden_size, hidden_size)
+
+ # Compute scaling for expanded head_dim (q and k have doubled dimensions after concatenation)
+ # This matches the original Conditional DETR implementation where embed_dim * 2 is used
+ expanded_head_dim = (hidden_size * 2) // num_attention_heads
+ self.scaling = expanded_head_dim**-0.5
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: torch.Tensor,
+ query_sine_embed: torch.Tensor,
+ encoder_position_embeddings: torch.Tensor,
+ query_position_embeddings: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor, torch.Tensor]:
+ """
+ Args:
+ hidden_states (`torch.Tensor` of shape `(batch_size, num_queries, hidden_size)`):
+ Decoder hidden states (queries).
+ encoder_hidden_states (`torch.Tensor` of shape `(batch_size, encoder_seq_len, hidden_size)`):
+ Encoder output hidden states (keys and values).
+ query_sine_embed (`torch.Tensor` of shape `(batch_size, num_queries, hidden_size)`):
+ Sine position embeddings for queries. **Concatenated** (not added) with query content,
+ doubling the query dimension.
+ encoder_position_embeddings (`torch.Tensor` of shape `(batch_size, encoder_seq_len, hidden_size)`):
+ Position embeddings for keys. **Concatenated** (not added) with key content, doubling the key dimension.
+ query_position_embeddings (`torch.Tensor` of shape `(batch_size, num_queries, hidden_size)`, *optional*):
+ Additional position embeddings. When provided (first layer only), **added** to query content
+ before concatenation with `query_sine_embed`. Also causes `encoder_position_embeddings` to be
+ added to key content before concatenation.
+ attention_mask (`torch.Tensor` of shape `(batch_size, 1, num_queries, encoder_seq_len)`, *optional*):
+ Attention mask to avoid attending to padding tokens.
+ """
+ query_input_shape = hidden_states.shape[:-1]
+ kv_input_shape = encoder_hidden_states.shape[:-1]
+ query_hidden_shape = (*query_input_shape, self.num_attention_heads, self.head_dim)
+ kv_hidden_shape = (*kv_input_shape, self.num_attention_heads, self.head_dim)
+
+ # Apply content and position projections
+ query_input = self.q_content_proj(hidden_states)
+ key_input = self.k_content_proj(encoder_hidden_states)
+ value_states = self.v_proj(encoder_hidden_states)
+ key_pos = self.k_pos_proj(encoder_position_embeddings)
+
+ # Combine content and position embeddings
+ if query_position_embeddings is not None:
+ query_input = query_input + self.q_pos_proj(query_position_embeddings)
+ key_input = key_input + key_pos
+
+ # Reshape and concatenate position embeddings (doubling head_dim)
+ query_input = query_input.view(query_hidden_shape)
+ key_input = key_input.view(kv_hidden_shape)
+ query_sine_embed = self.q_pos_sine_proj(query_sine_embed).view(query_hidden_shape)
+ key_pos = key_pos.view(kv_hidden_shape)
+
+ query_states = torch.cat([query_input, query_sine_embed], dim=-1).view(*query_input_shape, -1)
+ key_states = torch.cat([key_input, key_pos], dim=-1).view(*kv_input_shape, -1)
+
+ # Reshape for attention computation
+ expanded_head_dim = query_states.shape[-1] // self.num_attention_heads
+ query_states = query_states.view(*query_input_shape, self.num_attention_heads, expanded_head_dim).transpose(
+ 1, 2
+ )
+ key_states = key_states.view(*kv_input_shape, self.num_attention_heads, expanded_head_dim).transpose(1, 2)
+ value_states = value_states.view(kv_hidden_shape).transpose(1, 2)
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_states,
+ key_states,
+ value_states,
+ attention_mask,
+ dropout=0.0 if not self.training else self.attention_dropout,
+ scaling=self.scaling,
+ **kwargs,
+ )
+
+ attn_output = attn_output.reshape(*query_input_shape, -1).contiguous()
+ attn_output = self.o_proj(attn_output)
+ return attn_output, attn_weights
+
+
+class ConditionalDetrMLP(DetrMLP):
+ pass
+
+
+class ConditionalDetrEncoderLayer(DetrEncoderLayer):
+ pass
+
+
+class ConditionalDetrDecoderLayer(DetrDecoderLayer):
+ def __init__(self, config: ConditionalDetrConfig):
+ super().__init__()
+ self.self_attn = ConditionalDetrDecoderSelfAttention(
+ config=config,
+ hidden_size=self.hidden_size,
+ num_attention_heads=config.decoder_attention_heads,
+ dropout=config.attention_dropout,
+ )
+ self.encoder_attn = ConditionalDetrDecoderCrossAttention(
+ config=config,
+ hidden_size=self.hidden_size,
+ num_attention_heads=config.decoder_attention_heads,
+ dropout=config.attention_dropout,
+ )
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor | None = None,
+ spatial_position_embeddings: torch.Tensor | None = None,
+ query_position_embeddings: torch.Tensor | None = None,
+ query_sine_embed: torch.Tensor | None = None,
+ encoder_hidden_states: torch.Tensor | None = None,
+ encoder_attention_mask: torch.Tensor | None = None,
+ is_first: bool | None = False,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.Tensor:
+ """
+ Args:
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(seq_len, batch, embed_dim)`
+ attention_mask (`torch.FloatTensor`): attention mask of size
+ `(batch, 1, target_len, source_len)` where padding elements are indicated by very large negative
+ values.
+ spatial_position_embeddings (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
+ Spatial position embeddings (2D positional encodings) that are added to the queries and keys in each self-attention layer.
+ query_position_embeddings (`torch.FloatTensor`, *optional*):
+ object_queries that are added to the queries and keys
+ in the self-attention layer.
+ encoder_hidden_states (`torch.FloatTensor`):
+ cross attention input to the layer of shape `(seq_len, batch, embed_dim)`
+ encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size
+ `(batch, 1, target_len, source_len)` where padding elements are indicated by very large negative
+ values.
+ output_attentions (`bool`, *optional*):
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
+ returned tensors for more detail.
+ """
+ residual = hidden_states
+
+ hidden_states, _ = self.self_attn(
+ hidden_states=hidden_states,
+ query_position_embeddings=query_position_embeddings,
+ attention_mask=attention_mask,
+ **kwargs,
+ )
+
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
+ hidden_states = residual + hidden_states
+ hidden_states = self.self_attn_layer_norm(hidden_states)
+
+ if encoder_hidden_states is not None:
+ residual = hidden_states
+
+ hidden_states, _ = self.encoder_attn(
+ hidden_states=hidden_states,
+ encoder_hidden_states=encoder_hidden_states,
+ attention_mask=encoder_attention_mask,
+ query_sine_embed=query_sine_embed,
+ encoder_position_embeddings=spatial_position_embeddings,
+ # Only pass query_position_embeddings for the first layer
+ query_position_embeddings=query_position_embeddings if is_first else None,
+ **kwargs,
+ )
+
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
+ hidden_states = residual + hidden_states
+ hidden_states = self.encoder_attn_layer_norm(hidden_states)
+
+ # Fully Connected
+ residual = hidden_states
+ hidden_states = self.mlp(hidden_states)
+ hidden_states = residual + hidden_states
+ hidden_states = self.final_layer_norm(hidden_states)
+
+ return hidden_states
+
+
+class ConditionalDetrMLPPredictionHead(DetrMLPPredictionHead):
+ pass
+
+
+class ConditionalDetrPreTrainedModel(DetrPreTrainedModel):
+ _keys_to_ignore_on_load_unexpected = [
+ r"detr\.model\.backbone\.model\.layer\d+\.0\.downsample\.1\.num_batches_tracked"
+ ]
+
+
+class ConditionalDetrEncoder(DetrEncoder):
+ pass
+
+
+class ConditionalDetrDecoder(ConditionalDetrPreTrainedModel):
+ """
+ Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`ConditionalDetrDecoderLayer`].
+
+ The decoder updates the query embeddings through multiple self-attention and cross-attention layers.
+
+ Some small tweaks for Conditional DETR:
+
+ - object_queries and query_position_embeddings are added to the forward pass.
+ - if self.config.auxiliary_loss is set to True, also returns a stack of activations from all decoding layers.
+
+ Args:
+ config: ConditionalDetrConfig
+ """
+
+ _can_record_outputs = {
+ "hidden_states": ConditionalDetrDecoderLayer,
+ "attentions": OutputRecorder(ConditionalDetrDecoderSelfAttention, layer_name="self_attn", index=1),
+ "cross_attentions": OutputRecorder(ConditionalDetrDecoderCrossAttention, layer_name="encoder_attn", index=1),
+ }
+
+ def __init__(self, config: ConditionalDetrConfig):
+ super().__init__(config)
+ self.hidden_size = config.d_model
+
+ self.dropout = config.dropout
+ self.layerdrop = config.decoder_layerdrop
+
+ self.layers = nn.ModuleList([ConditionalDetrDecoderLayer(config) for _ in range(config.decoder_layers)])
+ # in Conditional DETR, the decoder uses layernorm after the last decoder layer output
+ self.layernorm = nn.LayerNorm(config.d_model)
+
+ # query_scale is the FFN applied on f to generate transformation T
+ self.query_scale = ConditionalDetrMLPPredictionHead(self.hidden_size, self.hidden_size, self.hidden_size, 2)
+ self.ref_point_head = ConditionalDetrMLPPredictionHead(self.hidden_size, self.hidden_size, 2, 2)
+ for layer_id in range(config.decoder_layers - 1):
+ # Set q_pos_proj to None for layers after the first (only first layer uses query position embeddings)
+ self.layers[layer_id + 1].encoder_attn.q_pos_proj = None
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @merge_with_config_defaults
+ @capture_outputs
+ def forward(
+ self,
+ inputs_embeds=None,
+ attention_mask=None,
+ encoder_hidden_states=None,
+ encoder_attention_mask=None,
+ spatial_position_embeddings=None,
+ object_queries_position_embeddings=None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> ConditionalDetrDecoderOutput:
+ r"""
+ Args:
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
+ The query embeddings that are passed into the decoder.
+
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Mask to avoid performing attention on certain queries. Mask values selected in `[0, 1]`:
+
+ - 1 for queries that are **not masked**,
+ - 0 for queries that are **masked**.
+
+ [What are attention masks?](../glossary#attention-mask)
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
+ of the decoder.
+ encoder_attention_mask (`torch.LongTensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):
+ Mask to avoid performing cross-attention on padding pixel_values of the encoder. Mask values selected
+ in `[0, 1]`:
+
+ - 1 for pixels that are real (i.e. **not masked**),
+ - 0 for pixels that are padding (i.e. **masked**).
+
+ spatial_position_embeddings (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
+ Spatial position embeddings that are added to the queries and keys in each cross-attention layer.
+ object_queries_position_embeddings (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_size)`):
+ , *optional*): Position embeddings that are added to the queries and keys in each self-attention layer.
+ """
+ if inputs_embeds is not None:
+ hidden_states = inputs_embeds
+
+ # expand encoder attention mask
+ if encoder_hidden_states is not None and encoder_attention_mask is not None:
+ # [batch_size, seq_len] -> [batch_size, 1, target_seq_len, source_seq_len]
+ encoder_attention_mask = create_bidirectional_mask(
+ self.config,
+ inputs_embeds,
+ encoder_attention_mask,
+ )
+
+ # optional intermediate hidden states
+ intermediate = () if self.config.auxiliary_loss else None
+
+ reference_points_before_sigmoid = self.ref_point_head(
+ object_queries_position_embeddings
+ ) # [num_queries, batch_size, 2]
+ reference_points = reference_points_before_sigmoid.sigmoid().transpose(0, 1)
+ obj_center = reference_points[..., :2].transpose(0, 1)
+ # get sine embedding for the query vector
+ query_sine_embed_before_transformation = encode_sinusoidal_position_embedding(
+ obj_center, num_pos_feats=self.config.d_model // 2
+ )
+
+ for idx, decoder_layer in enumerate(self.layers):
+ if self.training:
+ dropout_probability = torch.rand([])
+ if dropout_probability < self.layerdrop:
+ continue
+ if idx == 0:
+ pos_transformation = 1
+ else:
+ pos_transformation = self.query_scale(hidden_states)
+ # apply transformation
+ query_sine_embed = query_sine_embed_before_transformation * pos_transformation
+
+ hidden_states = decoder_layer(
+ hidden_states,
+ None,
+ spatial_position_embeddings,
+ object_queries_position_embeddings,
+ query_sine_embed,
+ encoder_hidden_states, # as a positional argument for gradient checkpointing
+ encoder_attention_mask=encoder_attention_mask,
+ is_first=(idx == 0),
+ **kwargs,
+ )
+
+ if self.config.auxiliary_loss:
+ hidden_states = self.layernorm(hidden_states)
+ intermediate += (hidden_states,)
+
+ # finally, apply layernorm
+ hidden_states = self.layernorm(hidden_states)
+
+ # stack intermediate decoder activations
+ if self.config.auxiliary_loss:
+ intermediate = torch.stack(intermediate)
+
+ return ConditionalDetrDecoderOutput(
+ last_hidden_state=hidden_states,
+ intermediate_hidden_states=intermediate,
+ reference_points=reference_points,
+ )
+
+
+class ConditionalDetrModel(DetrModel):
+ def __init__(self, config: ConditionalDetrConfig):
+ super().__init__(config)
+ self.query_position_embeddings = nn.Embedding(config.num_queries, config.d_model)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ @can_return_tuple
+ def forward(
+ self,
+ pixel_values: torch.FloatTensor,
+ pixel_mask: torch.LongTensor | None = None,
+ decoder_attention_mask: torch.LongTensor | None = None,
+ encoder_outputs: torch.FloatTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ decoder_inputs_embeds: torch.FloatTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> ConditionalDetrModelOutput:
+ r"""
+ decoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, num_queries)`, *optional*):
+ Not used by default. Can be used to mask object queries.
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
+ Optionally, instead of passing the flattened feature map (output of the backbone + projection layer), you
+ can choose to directly pass a flattened representation of an image.
+ decoder_inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_size)`, *optional*):
+ Optionally, instead of initializing the queries with a tensor of zeros, you can choose to directly pass an
+ embedded representation.
+
+ Examples:
+
+ ```python
+ >>> from transformers import AutoImageProcessor, AutoModel
+ >>> from PIL import Image
+ >>> import httpx
+ >>> from io import BytesIO
+
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
+ >>> with httpx.stream("GET", url) as response:
+ ... image = Image.open(BytesIO(response.read()))
+
+ >>> image_processor = AutoImageProcessor.from_pretrained("microsoft/conditional-detr-resnet-50")
+ >>> model = AutoModel.from_pretrained("microsoft/conditional-detr-resnet-50")
+
+ >>> # prepare image for the model
+ >>> inputs = image_processor(images=image, return_tensors="pt")
+
+ >>> # forward pass
+ >>> outputs = model(**inputs)
+
+ >>> # the last hidden states are the final query embeddings of the Transformer decoder
+ >>> # these are of shape (batch_size, num_queries, hidden_size)
+ >>> last_hidden_states = outputs.last_hidden_state
+ >>> list(last_hidden_states.shape)
+ [1, 300, 256]
+ ```"""
+ batch_size, num_channels, height, width = pixel_values.shape
+ device = pixel_values.device
+
+ if pixel_mask is None:
+ pixel_mask = torch.ones(((batch_size, height, width)), device=device)
+
+ # First, sent pixel_values + pixel_mask through Backbone to obtain the features
+ # pixel_values should be of shape (batch_size, num_channels, height, width)
+ # pixel_mask should be of shape (batch_size, height, width)
+ features = self.backbone(pixel_values, pixel_mask)
+
+ # get final feature map and downsampled mask
+ feature_map, mask = features[-1]
+
+ if mask is None:
+ raise ValueError("Backbone does not return downsampled pixel mask")
+
+ # Second, apply 1x1 convolution to reduce the channel dimension to d_model (256 by default)
+ projected_feature_map = self.input_projection(feature_map)
+
+ # Generate position embeddings
+ spatial_position_embeddings = (
+ self.position_embedding(shape=feature_map.shape, device=device, dtype=pixel_values.dtype, mask=mask)
+ .flatten(2)
+ .transpose(1, 2)
+ )
+
+ # Third, flatten the feature map of shape NxCxHxW to NxCxHW, and permute it to NxHWxC
+ # In other words, turn their shape into (batch_size, sequence_length, hidden_size)
+ flattened_features = projected_feature_map.flatten(2).transpose(1, 2)
+
+ flattened_mask = mask.flatten(1)
+
+ # Fourth, sent flattened_features + flattened_mask + spatial_position_embeddings through encoder
+ # flattened_features is a Tensor of shape (batch_size, height*width, hidden_size)
+ # flattened_mask is a Tensor of shape (batch_size, height*width)
+ if encoder_outputs is None:
+ encoder_outputs = self.encoder(
+ inputs_embeds=flattened_features,
+ attention_mask=flattened_mask,
+ spatial_position_embeddings=spatial_position_embeddings,
+ **kwargs,
+ )
+ # If the user passed a tuple for encoder_outputs, we wrap it in a BaseModelOutput
+ elif not isinstance(encoder_outputs, BaseModelOutput):
+ encoder_outputs = BaseModelOutput(
+ last_hidden_state=encoder_outputs[0],
+ hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
+ attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
+ )
+
+ # Fifth, sent query embeddings through the decoder (which is conditioned on the encoder output)
+ object_queries_position_embeddings = self.query_position_embeddings.weight.unsqueeze(0).repeat(
+ batch_size, 1, 1
+ )
+ queries = torch.zeros_like(object_queries_position_embeddings)
+
+ # decoder outputs consists of (dec_features, dec_hidden, dec_attn)
+ decoder_outputs = self.decoder(
+ inputs_embeds=queries,
+ attention_mask=None,
+ spatial_position_embeddings=spatial_position_embeddings,
+ object_queries_position_embeddings=object_queries_position_embeddings,
+ encoder_hidden_states=encoder_outputs.last_hidden_state,
+ encoder_attention_mask=flattened_mask,
+ **kwargs,
+ )
+
+ return ConditionalDetrModelOutput(
+ last_hidden_state=decoder_outputs.last_hidden_state,
+ decoder_hidden_states=decoder_outputs.hidden_states,
+ decoder_attentions=decoder_outputs.attentions,
+ cross_attentions=decoder_outputs.cross_attentions,
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
+ encoder_hidden_states=encoder_outputs.hidden_states,
+ encoder_attentions=encoder_outputs.attentions,
+ intermediate_hidden_states=decoder_outputs.intermediate_hidden_states,
+ reference_points=decoder_outputs.reference_points,
+ )
+
+
+class ConditionalDetrForObjectDetection(DetrForObjectDetection):
+ def __init__(self, config: ConditionalDetrConfig):
+ super().__init__(config)
+ self.class_labels_classifier = nn.Linear(config.d_model, config.num_labels)
+
+ # taken from https://github.com/Atten4Vis/conditionalDETR/blob/master/models/conditional_detr.py
+ def _set_aux_loss(self, outputs_class, outputs_coord):
+ return [{"logits": a, "pred_boxes": b} for a, b in zip(outputs_class[:-1], outputs_coord[:-1])]
+
+ @auto_docstring
+ @can_return_tuple
+ def forward(
+ self,
+ pixel_values: torch.FloatTensor,
+ pixel_mask: torch.LongTensor | None = None,
+ decoder_attention_mask: torch.LongTensor | None = None,
+ encoder_outputs: torch.FloatTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ decoder_inputs_embeds: torch.FloatTensor | None = None,
+ labels: list[dict] | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> ConditionalDetrObjectDetectionOutput:
+ r"""
+ decoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, num_queries)`, *optional*):
+ Not used by default. Can be used to mask object queries.
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
+ Optionally, instead of passing the flattened feature map (output of the backbone + projection layer), you
+ can choose to directly pass a flattened representation of an image.
+ decoder_inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_size)`, *optional*):
+ Optionally, instead of initializing the queries with a tensor of zeros, you can choose to directly pass an
+ embedded representation.
+ labels (`list[Dict]` of len `(batch_size,)`, *optional*):
+ Labels for computing the bipartite matching loss. List of dicts, each dictionary containing at least the
+ following 2 keys: 'class_labels' and 'boxes' (the class labels and bounding boxes of an image in the batch
+ respectively). The class labels themselves should be a `torch.LongTensor` of len `(number of bounding boxes
+ in the image,)` and the boxes a `torch.FloatTensor` of shape `(number of bounding boxes in the image, 4)`.
+
+ Examples:
+
+ ```python
+ >>> from transformers import AutoImageProcessor, AutoModelForObjectDetection
+ >>> from PIL import Image
+ >>> import httpx
+ >>> from io import BytesIO
+
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
+ >>> with httpx.stream("GET", url) as response:
+ ... image = Image.open(BytesIO(response.read()))
+
+ >>> image_processor = AutoImageProcessor.from_pretrained("microsoft/conditional-detr-resnet-50")
+ >>> model = AutoModelForObjectDetection.from_pretrained("microsoft/conditional-detr-resnet-50")
+
+ >>> inputs = image_processor(images=image, return_tensors="pt")
+
+ >>> outputs = model(**inputs)
+
+ >>> # convert outputs (bounding boxes and class logits) to Pascal VOC format (xmin, ymin, xmax, ymax)
+ >>> target_sizes = torch.tensor([image.size[::-1]])
+ >>> results = image_processor.post_process_object_detection(outputs, threshold=0.5, target_sizes=target_sizes)[
+ ... 0
+ ... ]
+ >>> for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
+ ... box = [round(i, 2) for i in box.tolist()]
+ ... print(
+ ... f"Detected {model.config.id2label[label.item()]} with confidence "
+ ... f"{round(score.item(), 3)} at location {box}"
+ ... )
+ Detected remote with confidence 0.833 at location [38.31, 72.1, 177.63, 118.45]
+ Detected cat with confidence 0.831 at location [9.2, 51.38, 321.13, 469.0]
+ Detected cat with confidence 0.804 at location [340.3, 16.85, 642.93, 370.95]
+ Detected remote with confidence 0.683 at location [334.48, 73.49, 366.37, 190.01]
+ Detected couch with confidence 0.535 at location [0.52, 1.19, 640.35, 475.1]
+ ```"""
+ # First, sent images through CONDITIONAL_DETR base model to obtain encoder + decoder outputs
+ outputs = self.model(
+ pixel_values,
+ pixel_mask=pixel_mask,
+ decoder_attention_mask=decoder_attention_mask,
+ encoder_outputs=encoder_outputs,
+ inputs_embeds=inputs_embeds,
+ decoder_inputs_embeds=decoder_inputs_embeds,
+ **kwargs,
+ )
+
+ sequence_output = outputs[0]
+
+ # class logits + predicted bounding boxes
+ logits = self.class_labels_classifier(sequence_output)
+
+ reference = outputs.reference_points
+ reference_before_sigmoid = inverse_sigmoid(reference).transpose(0, 1)
+
+ hs = sequence_output
+ tmp = self.bbox_predictor(hs)
+ tmp[..., :2] += reference_before_sigmoid
+ pred_boxes = tmp.sigmoid()
+ # pred_boxes = self.bbox_predictor(sequence_output).sigmoid()
+
+ loss, loss_dict, auxiliary_outputs = None, None, None
+ if labels is not None:
+ outputs_class, outputs_coord = None, None
+ if self.config.auxiliary_loss:
+ outputs_coords = []
+ intermediate = outputs.intermediate_hidden_states
+ outputs_class = self.class_labels_classifier(intermediate)
+ for lvl in range(intermediate.shape[0]):
+ tmp = self.bbox_predictor(intermediate[lvl])
+ tmp[..., :2] += reference_before_sigmoid
+ outputs_coord = tmp.sigmoid()
+ outputs_coords.append(outputs_coord)
+ outputs_coord = torch.stack(outputs_coords)
+ loss, loss_dict, auxiliary_outputs = self.loss_function(
+ logits, labels, self.device, pred_boxes, self.config, outputs_class, outputs_coord
+ )
+
+ return ConditionalDetrObjectDetectionOutput(
+ loss=loss,
+ loss_dict=loss_dict,
+ logits=logits,
+ pred_boxes=pred_boxes,
+ auxiliary_outputs=auxiliary_outputs,
+ last_hidden_state=outputs.last_hidden_state,
+ decoder_hidden_states=outputs.decoder_hidden_states,
+ decoder_attentions=outputs.decoder_attentions,
+ cross_attentions=outputs.cross_attentions,
+ encoder_last_hidden_state=outputs.encoder_last_hidden_state,
+ encoder_hidden_states=outputs.encoder_hidden_states,
+ encoder_attentions=outputs.encoder_attentions,
+ )
+
+
+class ConditionalDetrForSegmentation(DetrForSegmentation):
+ pass
+
+
+__all__ = [
+ "ConditionalDetrImageProcessor",
+ "ConditionalDetrImageProcessorPil",
+ "ConditionalDetrForObjectDetection",
+ "ConditionalDetrForSegmentation",
+ "ConditionalDetrModel",
+ "ConditionalDetrPreTrainedModel",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cpm/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cpm/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..16c8e646ab1b0d1f2b178515aeb825c2c293fbce
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cpm/__init__.py
@@ -0,0 +1,26 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .tokenization_cpm import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cpm/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cpm/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..53ff2fcbde99e88572e4a27515cb5ed1a4915005
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cpm/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cpm/__pycache__/tokenization_cpm.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cpm/__pycache__/tokenization_cpm.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e167709649e1292ba3a4224dd05e62893e2b9306
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cpm/__pycache__/tokenization_cpm.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cpm/__pycache__/tokenization_cpm_fast.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cpm/__pycache__/tokenization_cpm_fast.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cbe73dece9da5877083084af57cd3ee224fabf27
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cpm/__pycache__/tokenization_cpm_fast.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cpm/tokenization_cpm.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cpm/tokenization_cpm.py
new file mode 100644
index 0000000000000000000000000000000000000000..c1df4f75f9e2d1b853494fd4275061301cecb406
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cpm/tokenization_cpm.py
@@ -0,0 +1,336 @@
+# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Tokenization classes."""
+
+import os
+import unicodedata
+from shutil import copyfile
+from typing import Any
+
+import sentencepiece as spm
+
+from ...tokenization_python import AddedToken, PreTrainedTokenizer
+from ...utils import SPIECE_UNDERLINE, logging
+from ...utils.import_utils import requires
+
+
+logger = logging.get_logger(__name__)
+
+VOCAB_FILES_NAMES = {"vocab_file": "spiece.model"}
+
+
+@requires(backends=("sentencepiece",))
+class CpmTokenizer(PreTrainedTokenizer):
+ """Runs pre-tokenization with Jieba-RS segmentation tool. It is used in CPM models."""
+
+ vocab_files_names = VOCAB_FILES_NAMES
+
+ def __init__(
+ self,
+ vocab_file,
+ do_lower_case=False,
+ remove_space=True,
+ keep_accents=False,
+ bos_token="",
+ eos_token="",
+ unk_token="",
+ sep_token="",
+ pad_token="",
+ cls_token="",
+ mask_token="",
+ additional_special_tokens=["", ""],
+ sp_model_kwargs: dict[str, Any] | None = None,
+ **kwargs,
+ ) -> None:
+ """
+ Construct a CPM tokenizer. Based on [Jieba-RS](https://pypi.org/project/rjieba/) and
+ [SentencePiece](https://github.com/google/sentencepiece).
+
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should
+ refer to this superclass for more information regarding those methods.
+
+ Args:
+ vocab_file (`str`):
+ [SentencePiece](https://github.com/google/sentencepiece) file (generally has a .spm extension) that
+ contains the vocabulary necessary to instantiate a tokenizer.
+ do_lower_case (`bool`, *optional*, defaults to `True`):
+ Whether to lowercase the input when tokenizing.
+ remove_space (`bool`, *optional*, defaults to `True`):
+ Whether to strip the text when tokenizing (removing excess spaces before and after the string).
+ keep_accents (`bool`, *optional*, defaults to `False`):
+ Whether to keep accents when tokenizing.
+ bos_token (`str`, *optional*, defaults to `""`):
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier
+ token.
+
+
+
+ When building a sequence using special tokens, this is not the token that is used for the beginning of
+ sequence. The token used is the `cls_token`.
+
+
+
+ eos_token (`str`, *optional*, defaults to `""`):
+ The end of sequence token.
+
+
+
+ When building a sequence using special tokens, this is not the token that is used for the end of
+ sequence. The token used is the `sep_token`.
+
+
+
+ unk_token (`str`, *optional*, defaults to `""`):
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be
+ this token instead.
+ sep_token (`str`, *optional*, defaults to `""`):
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences
+ for sequence classification or for a text and a question for question answering. It is also used as the
+ last token of a sequence built with special tokens.
+ pad_token (`str`, *optional*, defaults to `""`):
+ The token used for padding, for example when batching sequences of different lengths.
+ cls_token (`str`, *optional*, defaults to `""`):
+ The classifier token which is used when doing sequence classification (classification of the whole
+ sequence instead of per-token classification). It is the first token of the sequence when built with
+ special tokens.
+ mask_token (`str`, *optional*, defaults to `""`):
+ The token used for masking values. This is the token used when training this model with masked language
+ modeling. This is the token which the model will try to predict.
+ additional_special_tokens (`list[str]`, *optional*, defaults to `["", ""]`):
+ Additional special tokens used by the tokenizer.
+
+ Attributes:
+ sp_model (`SentencePieceProcessor`):
+ The *SentencePiece* processor that is used for every conversion (string, tokens and IDs).
+ """
+ # Mask token behave like a normal word, i.e. include the space before it
+ mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token
+
+ self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
+
+ self.do_lower_case = do_lower_case
+ self.remove_space = remove_space
+ self.keep_accents = keep_accents
+ self.vocab_file = vocab_file
+
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
+ self.sp_model.Load(vocab_file)
+
+ try:
+ import rjieba
+ except ModuleNotFoundError as error:
+ raise error.__class__(
+ "You need to install rjieba to use CpmTokenizer or CpmTokenizerFast. "
+ "See https://pypi.org/project/rjieba/ for installation."
+ )
+ self.jieba = rjieba
+ self.translator = str.maketrans(" \n", "\u2582\u2583")
+
+ super().__init__(
+ do_lower_case=do_lower_case,
+ remove_space=remove_space,
+ keep_accents=keep_accents,
+ bos_token=bos_token,
+ eos_token=eos_token,
+ unk_token=unk_token,
+ sep_token=sep_token,
+ pad_token=pad_token,
+ cls_token=cls_token,
+ mask_token=mask_token,
+ additional_special_tokens=additional_special_tokens,
+ sp_model_kwargs=self.sp_model_kwargs,
+ **kwargs,
+ )
+
+ self._pad_token_type_id = 3
+
+ @property
+ def vocab_size(self):
+ return len(self.sp_model)
+
+ def get_vocab(self):
+ vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
+ vocab.update(self.added_tokens_encoder)
+ return vocab
+
+ def __getstate__(self):
+ state = self.__dict__.copy()
+ state["sp_model"] = None
+ return state
+
+ def __setstate__(self, d):
+ self.__dict__ = d
+
+ # for backward compatibility
+ if not hasattr(self, "sp_model_kwargs"):
+ self.sp_model_kwargs = {}
+
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
+ self.sp_model.Load(self.vocab_file)
+
+ def preprocess_text(self, inputs):
+ if self.remove_space:
+ outputs = " ".join(inputs.strip().split())
+ else:
+ outputs = inputs
+ outputs = outputs.replace("``", '"').replace("''", '"')
+
+ if not self.keep_accents:
+ outputs = unicodedata.normalize("NFKD", outputs)
+ outputs = "".join([c for c in outputs if not unicodedata.combining(c)])
+ if self.do_lower_case:
+ outputs = outputs.lower()
+
+ return outputs
+
+ def _tokenize(self, text: str) -> list[str]:
+ """Tokenize a string."""
+ text = self.preprocess_text(text)
+ pieces = self.sp_model.encode(text, out_type=str)
+ new_pieces = []
+ for piece in pieces:
+ if len(piece) > 1 and piece[-1] == "," and piece[-2].isdigit():
+ cur_pieces = self.sp_model.EncodeAsPieces(piece[:-1].replace(SPIECE_UNDERLINE, ""))
+ if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE:
+ if len(cur_pieces[0]) == 1:
+ cur_pieces = cur_pieces[1:]
+ else:
+ cur_pieces[0] = cur_pieces[0][1:]
+ cur_pieces.append(piece[-1])
+ new_pieces.extend(cur_pieces)
+ else:
+ new_pieces.append(piece)
+
+ return new_pieces
+
+ def _convert_token_to_id(self, token):
+ """Converts a token (str) in an id using the vocab."""
+ return self.sp_model.PieceToId(token)
+
+ def _convert_id_to_token(self, index):
+ """Converts an index (integer) in a token (str) using the vocab."""
+ return self.sp_model.IdToPiece(index)
+
+ def convert_tokens_to_string(self, tokens):
+ """Converts a sequence of tokens (strings for sub-words) in a single string."""
+ out_string = "".join(tokens).replace(SPIECE_UNDERLINE, " ").strip()
+ return out_string
+
+ def build_inputs_with_special_tokens(
+ self, token_ids_0: list[int], token_ids_1: list[int] | None = None
+ ) -> list[int]:
+ """
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
+ adding special tokens. An XLNet sequence has the following format:
+
+ - single sequence: `X `
+ - pair of sequences: `A B `
+
+ Args:
+ token_ids_0 (`list[int]`):
+ List of IDs to which the special tokens will be added.
+ token_ids_1 (`list[int]`, *optional*):
+ Optional second list of IDs for sequence pairs.
+
+ Returns:
+ `list[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
+ """
+ sep = [self.sep_token_id]
+ cls = [self.cls_token_id]
+ if token_ids_1 is None:
+ return token_ids_0 + sep + cls
+ return token_ids_0 + sep + token_ids_1 + sep + cls
+
+ def get_special_tokens_mask(
+ self, token_ids_0: list[int], token_ids_1: list[int] | None = None, already_has_special_tokens: bool = False
+ ) -> list[int]:
+ """
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
+ special tokens using the tokenizer `prepare_for_model` method.
+
+ Args:
+ token_ids_0 (`list[int]`):
+ List of IDs.
+ token_ids_1 (`list[int]`, *optional*):
+ Optional second list of IDs for sequence pairs.
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
+ Whether or not the token list is already formatted with special tokens for the model.
+
+ Returns:
+ `list[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
+ """
+
+ if already_has_special_tokens:
+ return super().get_special_tokens_mask(
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
+ )
+
+ if token_ids_1 is not None:
+ return ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1, 1]
+ return ([0] * len(token_ids_0)) + [1, 1]
+
+ def create_token_type_ids_from_sequences(
+ self, token_ids_0: list[int], token_ids_1: list[int] | None = None
+ ) -> list[int]:
+ """
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. An XLNet
+ sequence pair mask has the following format:
+
+ ```
+ 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
+ | first sequence | second sequence |
+ ```
+
+ If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
+
+ Args:
+ token_ids_0 (`list[int]`):
+ List of IDs.
+ token_ids_1 (`list[int]`, *optional*):
+ Optional second list of IDs for sequence pairs.
+
+ Returns:
+ `list[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
+ """
+ sep = [self.sep_token_id]
+ cls_segment_id = [2]
+
+ if token_ids_1 is None:
+ return len(token_ids_0 + sep) * [0] + cls_segment_id
+ return len(token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1] + cls_segment_id
+
+ def save_vocabulary(self, save_directory: str, filename_prefix: str | None = None) -> tuple[str]:
+ if not os.path.isdir(save_directory):
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
+ return
+ out_vocab_file = os.path.join(
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
+ )
+
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
+ copyfile(self.vocab_file, out_vocab_file)
+ elif not os.path.isfile(self.vocab_file):
+ with open(out_vocab_file, "wb") as fi:
+ content_spiece_model = self.sp_model.serialized_model_proto()
+ fi.write(content_spiece_model)
+
+ return (out_vocab_file,)
+
+ def _decode(self, *args, **kwargs):
+ text = super()._decode(*args, **kwargs)
+ text = text.replace(" ", "").replace("\u2582", " ").replace("\u2583", "\n")
+ return text
+
+
+__all__ = ["CpmTokenizer"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cpm/tokenization_cpm_fast.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cpm/tokenization_cpm_fast.py
new file mode 100644
index 0000000000000000000000000000000000000000..edbab867e8dab25dc5fdcc52c9a90ef40d9bf966
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cpm/tokenization_cpm_fast.py
@@ -0,0 +1,232 @@
+# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Tokenization classes."""
+
+import os
+from shutil import copyfile
+
+from ...tokenization_utils_tokenizers import AddedToken, PreTrainedTokenizerFast
+from ...utils import logging
+
+
+logger = logging.get_logger(__name__)
+
+VOCAB_FILES_NAMES = {"vocab_file": "spiece.model", "tokenizer_file": "tokenizer.json"}
+
+
+class CpmTokenizerFast(PreTrainedTokenizerFast):
+ """Runs pre-tokenization with Jieba-RS segmentation tool. It is used in CPM models."""
+
+ def __init__(
+ self,
+ vocab_file=None,
+ tokenizer_file=None,
+ do_lower_case=False,
+ remove_space=True,
+ keep_accents=False,
+ bos_token="",
+ eos_token="",
+ unk_token="",
+ sep_token="",
+ pad_token="",
+ cls_token="",
+ mask_token="",
+ additional_special_tokens=["", ""],
+ **kwargs,
+ ):
+ """
+ Construct a CPM tokenizer. Based on [Jieba-RS](https://pypi.org/project/rjieba/) and
+ [SentencePiece](https://github.com/google/sentencepiece).
+
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should
+ refer to this superclass for more information regarding those methods.
+
+ Args:
+ vocab_file (`str`):
+ [SentencePiece](https://github.com/google/sentencepiece) file (generally has a .spm extension) that
+ contains the vocabulary necessary to instantiate a tokenizer.
+ do_lower_case (`bool`, *optional*, defaults to `True`):
+ Whether to lowercase the input when tokenizing.
+ remove_space (`bool`, *optional*, defaults to `True`):
+ Whether to strip the text when tokenizing (removing excess spaces before and after the string).
+ keep_accents (`bool`, *optional*, defaults to `False`):
+ Whether to keep accents when tokenizing.
+ bos_token (`str`, *optional*, defaults to `""`):
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier
+ token.
+
+
+
+ When building a sequence using special tokens, this is not the token that is used for the beginning of
+ sequence. The token used is the `cls_token`.
+
+
+
+ eos_token (`str`, *optional*, defaults to `""`):
+ The end of sequence token.
+
+
+
+ When building a sequence using special tokens, this is not the token that is used for the end of
+ sequence. The token used is the `sep_token`.
+
+
+
+ unk_token (`str`, *optional*, defaults to `""`):
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be
+ this token instead.
+ sep_token (`str`, *optional*, defaults to `""`):
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences
+ for sequence classification or for a text and a question for question answering. It is also used as the
+ last token of a sequence built with special tokens.
+ pad_token (`str`, *optional*, defaults to `""`):
+ The token used for padding, for example when batching sequences of different lengths.
+ cls_token (`str`, *optional*, defaults to `""`):
+ The classifier token which is used when doing sequence classification (classification of the whole
+ sequence instead of per-token classification). It is the first token of the sequence when built with
+ special tokens.
+ mask_token (`str`, *optional*, defaults to `""`):
+ The token used for masking values. This is the token used when training this model with masked language
+ modeling. This is the token which the model will try to predict.
+ additional_special_tokens (`list[str]`, *optional*, defaults to `["", ""]`):
+ Additional special tokens used by the tokenizer.
+
+ Attributes:
+ sp_model (`SentencePieceProcessor`):
+ The *SentencePiece* processor that is used for every conversion (string, tokens and IDs).
+ """
+ # Mask token behave like a normal word, i.e. include the space before it
+ mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token
+
+ super().__init__(
+ vocab_file=vocab_file,
+ tokenizer_file=tokenizer_file,
+ do_lower_case=do_lower_case,
+ remove_space=remove_space,
+ keep_accents=keep_accents,
+ bos_token=bos_token,
+ eos_token=eos_token,
+ unk_token=unk_token,
+ sep_token=sep_token,
+ pad_token=pad_token,
+ cls_token=cls_token,
+ mask_token=mask_token,
+ additional_special_tokens=additional_special_tokens,
+ **kwargs,
+ )
+
+ self._pad_token_type_id = 3
+ self.do_lower_case = do_lower_case
+ self.remove_space = remove_space
+ self.keep_accents = keep_accents
+ self.vocab_file = vocab_file
+
+ try:
+ import rjieba
+ except ModuleNotFoundError as error:
+ raise error.__class__(
+ "You need to install rjieba to use CpmTokenizer or CpmTokenizerFast. "
+ "See https://pypi.org/project/rjieba/ for installation."
+ )
+ self.jieba = rjieba
+ self.translator = str.maketrans(" \n", "\u2582\u2583")
+
+ def build_inputs_with_special_tokens(
+ self, token_ids_0: list[int], token_ids_1: list[int] | None = None
+ ) -> list[int]:
+ """
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
+ adding special tokens. An XLNet sequence has the following format:
+
+ - single sequence: `X `
+ - pair of sequences: `A B `
+
+ Args:
+ token_ids_0 (`list[int]`):
+ List of IDs to which the special tokens will be added.
+ token_ids_1 (`list[int]`, *optional*):
+ Optional second list of IDs for sequence pairs.
+
+ Returns:
+ `list[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
+ """
+ sep = [self.sep_token_id]
+ cls = [self.cls_token_id]
+ if token_ids_1 is None:
+ return token_ids_0 + sep + cls
+ return token_ids_0 + sep + token_ids_1 + sep + cls
+
+ def create_token_type_ids_from_sequences(
+ self, token_ids_0: list[int], token_ids_1: list[int] | None = None
+ ) -> list[int]:
+ """
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. An XLNet
+ sequence pair mask has the following format:
+
+ ```
+ 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
+ | first sequence | second sequence |
+ ```
+
+ If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
+
+ Args:
+ token_ids_0 (`list[int]`):
+ List of IDs.
+ token_ids_1 (`list[int]`, *optional*):
+ Optional second list of IDs for sequence pairs.
+
+ Returns:
+ `list[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
+ """
+ sep = [self.sep_token_id]
+ cls_segment_id = [2]
+
+ if token_ids_1 is None:
+ return len(token_ids_0 + sep) * [0] + cls_segment_id
+ return len(token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1] + cls_segment_id
+
+ def save_vocabulary(self, save_directory: str, filename_prefix: str | None = None) -> tuple[str]:
+ if not self.can_save_slow_tokenizer:
+ raise ValueError(
+ "Your fast tokenizer does not have the necessary information to save the vocabulary for a slow "
+ "tokenizer."
+ )
+
+ if not os.path.isdir(save_directory):
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
+ return
+ out_vocab_file = os.path.join(
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
+ )
+
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file):
+ copyfile(self.vocab_file, out_vocab_file)
+
+ return (out_vocab_file,)
+
+ def _batch_encode_plus(self, batch_text_or_text_pairs, *args, **kwargs):
+ batch_text_or_text_pairs = [
+ " ".join([x.translate(self.translator) for x in self.jieba.cut(text, False)])
+ for text in batch_text_or_text_pairs
+ ]
+ return super()._batch_encode_plus(batch_text_or_text_pairs, *args, **kwargs)
+
+ def _decode(self, *args, **kwargs):
+ text = super()._decode(*args, **kwargs)
+ text = text.replace(" ", "").replace("\u2582", " ").replace("\u2583", "\n")
+ return text
+
+
+__all__ = ["CpmTokenizerFast"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cpmant/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cpmant/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d92eea75693e728f4c1e9afc199d40751ef6af7a
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cpmant/__init__.py
@@ -0,0 +1,28 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_cpmant import *
+ from .modeling_cpmant import *
+ from .tokenization_cpmant import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cpmant/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cpmant/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0c2860cf958b12e634fca80d68b853290f71cd5a
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cpmant/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cpmant/__pycache__/configuration_cpmant.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cpmant/__pycache__/configuration_cpmant.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..eafaf2d8f2f8bd0d9a124e334b2225737d3dbf6e
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cpmant/__pycache__/configuration_cpmant.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cpmant/__pycache__/modeling_cpmant.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cpmant/__pycache__/modeling_cpmant.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..77f4a383f7fae5ccdf549a000b39ae72bbfe8a26
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cpmant/__pycache__/modeling_cpmant.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cpmant/__pycache__/tokenization_cpmant.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cpmant/__pycache__/tokenization_cpmant.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..922d08928fa3b086ab59dfca6f24d8a27d9644c8
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cpmant/__pycache__/tokenization_cpmant.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cpmant/configuration_cpmant.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cpmant/configuration_cpmant.py
new file mode 100644
index 0000000000000000000000000000000000000000..9f0479982e2d0af47630c507f85d709d4743db35
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cpmant/configuration_cpmant.py
@@ -0,0 +1,73 @@
+# Copyright 2022 The OpenBMB Team and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""CPMAnt model configuration"""
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring
+
+
+@auto_docstring(checkpoint="openbmb/cpm-ant-10b")
+@strict
+class CpmAntConfig(PreTrainedConfig):
+ r"""
+ position_bias_num_buckets (`int`, *optional*, defaults to 512):
+ The number of position_bias buckets.
+ position_bias_max_distance (`int`, *optional*, defaults to 2048):
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
+ just in case (e.g., 512 or 1024 or 2048).
+ prompt_types (`int`, *optional*, defaults to 32):
+ The type of prompt.
+ prompt_length (`int`, *optional*, defaults to 32):
+ The length of prompt.
+ segment_types (`int`, *optional*, defaults to 32):
+ The type of segment.
+
+ Example:
+
+ ```python
+ >>> from transformers import CpmAntModel, CpmAntConfig
+
+ >>> # Initializing a CPMAnt cpm-ant-10b style configuration
+ >>> configuration = CpmAntConfig()
+
+ >>> # Initializing a model from the cpm-ant-10b style configuration
+ >>> model = CpmAntModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "cpmant"
+
+ vocab_size: int = 30720
+ hidden_size: int = 4096
+ num_attention_heads: int = 32
+ dim_head: int = 128
+ dim_ff: int = 10240
+ num_hidden_layers: int = 48
+ dropout_p: float | int = 0.0
+ position_bias_num_buckets: int = 512
+ position_bias_max_distance: int = 2048
+ eps: float = 1e-6
+ init_std: float = 1.0
+ prompt_types: int = 32
+ prompt_length: int = 32
+ segment_types: int = 32
+ use_cache: bool = True
+ tie_word_embeddings: bool = True
+
+
+__all__ = ["CpmAntConfig"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cpmant/modeling_cpmant.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cpmant/modeling_cpmant.py
new file mode 100644
index 0000000000000000000000000000000000000000..832dc7f7d096a11d9e9a86f8cc3f565cbba343e2
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cpmant/modeling_cpmant.py
@@ -0,0 +1,779 @@
+# Copyright 2022 The OpenBMB Team and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch CPMAnt"""
+
+import math
+
+import torch
+import torch.nn.functional as F
+from torch import nn
+from torch.nn import CrossEntropyLoss
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...cache_utils import Cache, DynamicCache
+from ...generation import GenerationMixin
+from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
+from ...modeling_utils import PreTrainedModel
+from ...utils import auto_docstring, logging
+from .configuration_cpmant import CpmAntConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+class CpmAntLayerNorm(nn.Module):
+ """
+ We use Root Mean Square (RMS) Layer Normalization, please see https://huggingface.co/papers/1910.07467 for details."
+ """
+
+ def __init__(self, config: CpmAntConfig):
+ super().__init__()
+
+ self.eps = config.eps
+ self.dim_norm = config.hidden_size
+ self.weight = nn.Parameter(torch.empty(config.hidden_size))
+
+ def forward(self, hidden_states: torch.Tensor):
+ """
+ Args:
+ hidden_states (`torch.Tensor` of shape `(batch, seq_len, dim_in)`)
+ """
+ if hidden_states.size(-1) != self.dim_norm:
+ raise AssertionError("hidden_states.size(-1) != self.dim_norm")
+ old_dtype = hidden_states.dtype
+ variance = hidden_states.to(torch.float32).pow(2).mean(dim=-1, keepdim=True)
+ hidden_states = (hidden_states * torch.rsqrt(variance + self.eps)).to(old_dtype) * self.weight
+ return hidden_states
+
+
+class CpmAntAttention(nn.Module):
+ def __init__(self, config: CpmAntConfig, layer_idx=None):
+ super().__init__()
+ self.dim_model = config.hidden_size
+ self.num_heads = config.num_attention_heads
+ self.dim_head = config.dim_head
+ self.layer_idx = layer_idx
+
+ self.project_q = nn.Linear(self.dim_model, self.num_heads * self.dim_head, bias=False)
+ self.project_k = nn.Linear(self.dim_model, self.num_heads * self.dim_head, bias=False)
+ self.project_v = nn.Linear(self.dim_model, self.num_heads * self.dim_head, bias=False)
+
+ self.attention_out = nn.Linear(self.num_heads * self.dim_head, self.dim_model, bias=False)
+
+ self.softmax = torch.nn.Softmax(dim=-1)
+
+ if config.dropout_p is not None:
+ self.dropout = torch.nn.Dropout(p=config.dropout_p)
+ else:
+ self.dropout = None
+
+ def forward(
+ self,
+ hidden_q: torch.Tensor,
+ hidden_kv: torch.Tensor,
+ attention_mask: torch.BoolTensor,
+ position_bias: torch.Tensor,
+ output_attentions: bool | None = False,
+ past_key_values: Cache | None = None,
+ use_cache: bool | None = None,
+ **kwargs,
+ ):
+ """
+ Args:
+ hidden_q (`torch.Tensor`):
+ Input of transformer block(self-attention block). It can be the raw embedding of a batch of sequences.
+ hidden_kv (`torch.Tensor` of shape `(batch, len_k, dim_model)`)):
+ Tensor *key_value* and *query* of shape `(batch, len_k, dim_model)`
+ attention_mask (`torch.Tensor` of shape `(batch, len_seq, len_seq)`):
+ Avoid invalid areas to participate in the calculation of self-attention.
+ position_bias (`torch.Tensor` of shape `(batch, len_seq, len_seq)`):
+ Provide positional information to self-attention block.
+ output_attentions (`bool`, *optional*):
+ Whether or not to return the attentions tensors of all attention layers.
+ past_key_values (`Cache`, *optional*):
+ Cached past key and value projection states.
+ use_cache (`bool`, *optional*):
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
+ (see `past_key_values`).
+ """
+ batch_size = hidden_q.size(0)
+ len_q = hidden_q.size(1)
+ len_k = hidden_kv.size(1)
+
+ query = self.project_q(hidden_q)
+ key = self.project_k(hidden_kv)
+ value = self.project_v(hidden_kv)
+
+ query = query.view(batch_size, len_q, self.num_heads, self.dim_head).permute(0, 2, 1, 3)
+ key = key.view(batch_size, len_k, self.num_heads, self.dim_head).permute(0, 2, 1, 3)
+ value = value.view(batch_size, len_k, self.num_heads, self.dim_head).permute(0, 2, 1, 3)
+
+ if past_key_values is not None:
+ key, value = past_key_values.update(key, value, self.layer_idx)
+ len_k = key.size(-2)
+
+ # (batch_size, num_heads, len_q, dim_head) @ (batch_size, num_heads, dim_head, len_k) -> (batch_size, num_heads, len_q, len_k)
+ score = torch.matmul(query, key.transpose(-1, -2)) / math.sqrt(self.dim_head)
+ score = score + position_bias
+
+ score = torch.masked_fill(
+ score,
+ attention_mask.view(batch_size, 1, len_q, len_k) == torch.tensor(False),
+ torch.scalar_tensor(float("-inf"), device=score.device, dtype=score.dtype),
+ )
+ score = self.softmax(score)
+
+ score = torch.masked_fill(
+ score,
+ attention_mask.view(batch_size, 1, len_q, len_k) == torch.tensor(False),
+ torch.scalar_tensor(0, device=score.device, dtype=score.dtype),
+ )
+ if output_attentions:
+ attn_weights = score
+ else:
+ attn_weights = None
+
+ if self.dropout is not None:
+ score = self.dropout(score)
+
+ # (batch_size, num_heads, len_q, len_k) @ (batch_size, num_heads, len_k, dim_head) -> (batch_size, num_heads, len_q, dim_head)
+ score = torch.matmul(score, value)
+
+ score = score.view(batch_size, self.num_heads, len_q, self.dim_head).permute(0, 2, 1, 3)
+ score = score.contiguous().view(batch_size, len_q, self.num_heads * self.dim_head)
+
+ score = self.attention_out(score)
+
+ return score, attn_weights
+
+
+class CpmAntSelfAttentionBlock(nn.Module):
+ def __init__(self, config: CpmAntConfig, layer_idx=None):
+ super().__init__()
+ self.layernorm_before_attention = CpmAntLayerNorm(config)
+ self.self_attention = CpmAntAttention(config, layer_idx=layer_idx)
+ if config.dropout_p:
+ self.dropout = torch.nn.Dropout(config.dropout_p)
+ else:
+ self.dropout = None
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor,
+ position_bias: torch.Tensor | None = None,
+ output_attentions: bool | None = False,
+ past_key_values: Cache | None = None,
+ use_cache: bool | None = None,
+ **kwargs,
+ ):
+ """
+ Args:
+ hidden_states (`torch.Tensor` of shape `(batch, len_seq, dim_model)`):
+ Input of transformer block(self-attention block). It can be the raw embedding of a batch of sequences.
+ attention_mask (`torch.Tensor` of shape `(batch, len_seq, len_seq)`):
+ Avoid invalid areas to participate in the calculation of self-attention.
+ position_bias (`torch.Tensor` of shape `(batch, len_seq, len_seq)`):
+ Provide positional information to self-attention block.
+ output_attentions (`bool`, *optional*):
+ Whether or not to return the attentions tensors of all attention layers.
+ past_key_values (`Cache`, *optional*):
+ Cached past key and value projection states.
+ use_cache (`bool`, *optional*):
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
+ (see `past_key_values`).
+ """
+ outputs = self.layernorm_before_attention(hidden_states)
+ outputs, attn_weights = self.self_attention(
+ outputs,
+ outputs,
+ attention_mask,
+ position_bias,
+ output_attentions,
+ past_key_values,
+ use_cache,
+ )
+
+ if self.dropout is not None:
+ outputs = self.dropout(outputs)
+ hidden_states = hidden_states + outputs
+
+ return hidden_states, attn_weights
+
+
+class CpmAntDenseGatedACT(nn.Module):
+ def __init__(self, config: CpmAntConfig):
+ super().__init__()
+ self.w_0 = nn.Linear(config.hidden_size, config.dim_ff, bias=False)
+ self.w_1 = nn.Linear(config.hidden_size, config.dim_ff, bias=False)
+ self.act = torch.nn.GELU()
+
+ def forward(self, hidden_states: torch.Tensor):
+ """Transform an input tensor from one feature space to another via a nonlinear operation
+
+ Args:
+ hidden_states (`torch.Tensor` of shape `(batch, seq_len, dim_in)`)
+ """
+ gate_score = self.act(self.w_0(hidden_states))
+ hidden_states = self.w_1(hidden_states)
+
+ hidden_states = gate_score * hidden_states
+ return hidden_states
+
+
+class CpmAntFeedForward(nn.Module):
+ def __init__(self, config: CpmAntConfig):
+ super().__init__()
+ self.w_in = CpmAntDenseGatedACT(config)
+ if config.dropout_p is not None:
+ self.dropout = torch.nn.Dropout(config.dropout_p)
+ else:
+ self.dropout = None
+
+ self.w_out = nn.Linear(config.dim_ff, config.hidden_size, bias=False)
+
+ def forward(self, hidden_states: torch.Tensor):
+ """
+ Args:
+ hidden_states (`torch.Tensor` of shape `(batch, seq_len, dim_in)`)
+ """
+ hidden_states = self.w_in(hidden_states)
+
+ if self.dropout is not None:
+ hidden_states = self.dropout(hidden_states)
+
+ hidden_states = self.w_out(hidden_states)
+
+ return hidden_states
+
+
+class CpmAntFFNBlock(nn.Module):
+ def __init__(self, config: CpmAntConfig):
+ super().__init__()
+ self.layernorm_before_ffn = CpmAntLayerNorm(config)
+ self.ffn = CpmAntFeedForward(config)
+ if config.dropout_p:
+ self.dropout = torch.nn.Dropout(config.dropout_p)
+ else:
+ self.dropout = None
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ ):
+ """
+ Args:
+ hidden_states (`torch.Tensor` of shape `(batch, len_seq, dim_model)`):
+ Hidden states before feed forward layer.
+ """
+ ln_outputs = self.layernorm_before_ffn(hidden_states)
+ outputs = self.ffn(ln_outputs)
+ if self.dropout is not None:
+ outputs = self.dropout(outputs)
+ hidden_states = hidden_states + outputs
+ return hidden_states
+
+
+class CpmAntTransformerBlock(nn.Module):
+ def __init__(self, config: CpmAntConfig, layer_idx=None):
+ super().__init__()
+ self.self_att = CpmAntSelfAttentionBlock(config, layer_idx=layer_idx)
+ self.ffn = CpmAntFFNBlock(config)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor,
+ position_bias: torch.Tensor | None = None,
+ output_attentions: bool | None = False,
+ past_key_values: Cache | None = None,
+ use_cache: bool | None = None,
+ **kwargs,
+ ):
+ """
+ Args:
+ hidden_states (`torch.Tensor`):
+ Input to the layer of shape `(batch, seq_len, dim_model)`
+ attention_mask (`torch.Tensor`):
+ Avoid invalid areas to participate in the calculation of shape `(batch, seq_len, seq_len)`
+ position_bias (`torch.Tensor`):
+ Provides position information to attention mechanism of shape `(num_heads, seq_len, seq_len)`
+ output_attentions (`bool`, *optional*):
+ Whether or not to return the attentions tensors of all attention layers.
+ past_key_values (`Cache`, *optional*):
+ Cached past key and value projection states
+ use_cache (`bool`, *optional*):
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
+ (see `past_key_values`).
+ """
+ hidden_states, attn_weights = self.self_att(
+ hidden_states,
+ attention_mask=attention_mask,
+ position_bias=position_bias,
+ output_attentions=output_attentions,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ )
+
+ hidden_states = self.ffn(hidden_states)
+ return hidden_states, attn_weights
+
+
+class CpmAntEncoder(nn.Module):
+ def __init__(self, config: CpmAntConfig):
+ super().__init__()
+ self.num_layers = config.num_hidden_layers
+ self.layers = nn.ModuleList([CpmAntTransformerBlock(config, layer_idx=i) for i in range(self.num_layers)])
+
+ self.output_layernorm = CpmAntLayerNorm(config)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor,
+ position_bias: torch.Tensor,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ past_key_values: Cache | None = None,
+ use_cache: bool | None = None,
+ **kwargs,
+ ):
+ """
+ Args:
+ hidden_states (`torch.Tensor`):
+ Input to the layer of shape `(batch, seq_len, dim_model)`
+ attention_mask (`torch.Tensor`):
+ Avoid invalid areas to participate in the calculation of shape `(batch, seq_len, seq_len)`
+ position_bias (`torch.Tensor`):
+ Provides position information to attention mechanism of shape `(num_heads, seq_len, seq_len)`
+ output_attentions (`bool`, *optional*):
+ Whether or not to return the attentions tensors of all attention layers.
+ output_hidden_states (`bool`, *optional*):
+ Whether or not to return the hidden states of all layers.
+ past_key_values (`Cache`, *optional*):
+ Cached past key and value projection states
+ use_cache (`bool`, *optional*):
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
+ (see `past_key_values`).
+ """
+ all_hidden_states = () if output_hidden_states else None
+ all_self_attns = () if output_attentions else None
+
+ for i, layer in enumerate(self.layers):
+ if output_hidden_states:
+ all_hidden_states += (hidden_states,)
+ layer_outputs = layer(
+ hidden_states,
+ attention_mask,
+ position_bias,
+ output_attentions=output_attentions,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ )
+ hidden_states, attn_weights = layer_outputs
+ if output_attentions:
+ all_self_attns += (attn_weights,)
+
+ hidden_states = self.output_layernorm(hidden_states)
+
+ if output_hidden_states:
+ all_hidden_states += (hidden_states,)
+
+ return hidden_states, all_hidden_states, all_self_attns
+
+
+# Copied from transformers.models.bert.modeling_bert.BertIntermediate with Bert->CPMAnt
+class CpmAntIntermediate(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
+ if isinstance(config.hidden_act, str):
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
+ else:
+ self.intermediate_act_fn = config.hidden_act
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.intermediate_act_fn(hidden_states)
+ return hidden_states
+
+
+class CpmAntSegmentPositionEmbedding(nn.Module):
+ def __init__(self, config: CpmAntConfig):
+ super().__init__()
+
+ self.num_heads = config.num_attention_heads
+ self.num_buckets = config.position_bias_num_buckets
+ self.max_distance = config.position_bias_max_distance
+ self.num_segments = config.segment_types
+
+ self.relative_attention_bias = nn.Parameter(
+ torch.empty(
+ config.segment_types * config.segment_types + config.position_bias_num_buckets,
+ config.num_attention_heads,
+ )
+ )
+
+ def forward(
+ self,
+ key_pos: torch.Tensor,
+ query_pos: torch.Tensor,
+ key_segment: torch.Tensor,
+ query_segment: torch.Tensor,
+ ):
+ with torch.no_grad():
+ batch = key_pos.size(0)
+ keylen = key_pos.size(1)
+ querylen = query_pos.size(1)
+
+ if key_pos.size(0) != query_pos.size(0):
+ raise AssertionError(
+ f"key_pos.size(0) should be equal to query_pos.size(0), but got {key_pos.size(0)} and {query_pos.size(0)}!"
+ )
+ if keylen != key_segment.size(1) or querylen != query_segment.size(1):
+ raise AssertionError(
+ f"keylen should be equal to key_segment.size(1), but got {keylen} and {key_segment.size(1)}!"
+ )
+ if querylen != query_segment.size(1):
+ raise AssertionError(
+ f"querylen should be equal to query_segment.size(1), but got {querylen} and {query_segment.size(1)}!"
+ )
+
+ key_pos = key_pos.view(batch, -1, keylen)
+ query_pos = query_pos.view(batch, querylen, -1)
+ key_segment = key_segment.view(batch, -1, keylen)
+ query_segment = query_segment.view(batch, querylen, -1)
+
+ relative_position_bucket = self._segment_relative_position_bucket(query_segment, key_segment)
+ relative_position_bucket = relative_position_bucket + self.num_buckets
+
+ # (batch, len_q, len_k)
+ absolute_position_bucket = self._position_bucket(
+ torch.arange(keylen, dtype=torch.int32, device=relative_position_bucket.device)[None, :]
+ - torch.arange(querylen, dtype=torch.int32, device=relative_position_bucket.device)[:, None],
+ num_buckets=self.num_buckets,
+ max_distance=self.max_distance,
+ )
+ relative_position_bucket = torch.where(
+ (key_segment == query_segment),
+ absolute_position_bucket[None, :, :],
+ relative_position_bucket,
+ )
+
+ # (batch, len_q, len_k, num_heads)
+ embeds = F.embedding(relative_position_bucket, self.relative_attention_bias)
+ # (batch, num_heads, len_q, len_k)
+ embeds = embeds.permute(0, 3, 1, 2).contiguous()
+ return embeds
+
+ def _segment_relative_position_bucket(self, query_segment, key_segment):
+ return query_segment * self.num_segments + key_segment
+
+ def _position_bucket(self, relative_position, num_buckets=32, max_distance=128):
+ relative_buckets = 0
+ # always bidirectional in CPMAnt
+ num_buckets //= 2
+ relative_buckets = (relative_position > 0).to(torch.int32) * num_buckets
+ relative_position = torch.abs(relative_position)
+ max_exact = num_buckets // 2
+ is_small = relative_position < max_exact
+ relative_position_if_large = max_exact + (
+ torch.log(relative_position.float() / max_exact)
+ / math.log(max_distance / max_exact)
+ * (num_buckets - max_exact)
+ ).to(torch.int32)
+ relative_position_if_large = torch.min(
+ relative_position_if_large,
+ torch.full_like(relative_position_if_large, num_buckets - 1),
+ )
+ relative_buckets += torch.where(is_small, relative_position.to(torch.int32), relative_position_if_large)
+ return relative_buckets
+
+
+# Copied from transformers.models.bert.modeling_bert.BertOutput with Bert->CPMAnt
+class CpmAntOutput(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
+ return hidden_states
+
+
+@auto_docstring
+class CpmAntPreTrainedModel(PreTrainedModel):
+ config: CpmAntConfig
+ base_model_prefix = "cpmant"
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ """Initialize the weights"""
+ super()._init_weights(module)
+ if isinstance(module, CpmAntLayerNorm):
+ init.ones_(module.weight)
+ elif isinstance(module, CpmAntSegmentPositionEmbedding):
+ init.normal_(module.relative_attention_bias, mean=0.0, std=self.config.init_std)
+
+
+@auto_docstring
+class CpmAntModel(CpmAntPreTrainedModel):
+ def __init__(self, config: CpmAntConfig):
+ super().__init__(config)
+ self.encoder = CpmAntEncoder(config)
+ self.segment_embedding = nn.Embedding(config.segment_types, config.hidden_size)
+ self.input_embedding = nn.Embedding(
+ config.vocab_size + config.prompt_types * config.prompt_length, config.hidden_size
+ )
+ self.position_bias = CpmAntSegmentPositionEmbedding(config)
+ self.prompt_length = config.prompt_length
+ self.vocab_size = config.vocab_size
+
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.input_embedding
+
+ def set_input_embeddings(self, embeddings, **kwargs):
+ self.input_embedding = embeddings
+
+ def _prepare_attention_mask(self, input_ids, span, context, length):
+ batch = input_ids.size(0)
+ seqlen = input_ids.size(1)
+ device = input_ids.device
+ directional_mask_2d = torch.arange(seqlen, device=device) <= torch.arange(seqlen, device=device).view(-1, 1)
+ attention_mask = context[:, None, :] | (
+ context[:, :, None].logical_not() & directional_mask_2d.view(1, seqlen, seqlen)
+ )
+ attention_mask = attention_mask & (span[:, None, :] == span[:, :, None])
+ # mask for left padding
+ mask_1d = (
+ torch.tensor(list(range(seqlen - self.prompt_length))[::-1], device=device)[None, :].repeat(batch, 1)
+ < length[:, None]
+ )
+ mask_1d = torch.cat((torch.ones(batch, self.prompt_length, device=device).bool(), mask_1d), dim=1)
+ attention_mask = mask_1d.view(batch, seqlen, 1) & mask_1d.view(batch, 1, seqlen) & attention_mask
+ return attention_mask
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ past_key_values: Cache | None = None,
+ use_cache: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple[torch.Tensor] | BaseModelOutputWithPast:
+ r"""
+ input_ids (`torch.Tensor` of shape `(batch_size, seq_len)`):
+ Indices of input sequence tokens in the vocabulary.
+
+ Indices can be obtained using [`CPMAntTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input-ids)
+ """
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
+
+ # add prompts ahead
+ if input_ids.dtype != torch.int32:
+ input_ids = input_ids.to(torch.int32)
+ dtype, device = input_ids.dtype, input_ids.device
+ segment = torch.where(input_ids != 0, 2, 0).to(dtype=dtype, device=device)
+ length = (segment != 0).sum(-1).to(dtype=dtype, device=device)
+ input_ids = torch.cat(
+ (
+ torch.arange(
+ self.prompt_length * 2 + self.vocab_size,
+ self.prompt_length * 3 + self.vocab_size,
+ dtype=dtype,
+ device=device,
+ ).repeat(input_ids.size(0), 1),
+ input_ids,
+ ),
+ dim=1,
+ )
+ batch, seq_length = input_ids.size()
+ segment = torch.cat((torch.zeros(batch, self.prompt_length, dtype=dtype, device=device), segment), dim=1)
+ context = torch.full((batch, seq_length), 1, dtype=dtype, device=device)
+ position = torch.arange(seq_length, dtype=dtype, device=device).repeat(batch, 1)
+ span = torch.full((batch, seq_length), 0, dtype=dtype, device=device)
+
+ if use_cache and past_key_values is None:
+ past_key_values = DynamicCache(config=self.config)
+
+ past_length = past_key_values.get_seq_length() if past_key_values is not None else 0
+ input_ids = input_ids.contiguous()
+ hidden_states = self.input_embedding(input_ids)
+ segment_states = self.segment_embedding(segment)
+ if past_length != 0:
+ segment_states = segment_states[:, -1:, :]
+
+ hidden_states = hidden_states + segment_states
+
+ attention_mask = self._prepare_attention_mask(input_ids, span, context, length)
+ position_bias = self.position_bias(position, position, segment, segment)
+
+ attention_mask = attention_mask[:, past_length:, :]
+ position_bias = position_bias[:, :, past_length:, :]
+ hidden_states = hidden_states[:, past_length:, :]
+
+ hidden_states, all_hidden_states, all_attentions = self.encoder(
+ hidden_states,
+ attention_mask,
+ position_bias,
+ output_attentions,
+ output_hidden_states,
+ past_key_values,
+ use_cache,
+ )
+
+ if past_length == 0:
+ hidden_states = hidden_states[:, self.prompt_length :, :]
+ # drop the prompt
+ if all_attentions is not None:
+ new_attentions = ()
+ for attention in all_attentions:
+ new_attentions += (attention[:, :, self.prompt_length :, self.prompt_length :],)
+ all_attentions = new_attentions
+ if all_hidden_states is not None:
+ new_hidden_states = ()
+ for hidden_state in all_hidden_states:
+ new_hidden_states += (hidden_state[:, self.prompt_length :, :],)
+ all_hidden_states = new_hidden_states
+
+ if not return_dict:
+ return tuple(
+ v for v in [hidden_states, past_key_values, all_hidden_states, all_attentions] if v is not None
+ )
+
+ return BaseModelOutputWithPast(
+ last_hidden_state=hidden_states,
+ past_key_values=past_key_values,
+ hidden_states=all_hidden_states,
+ attentions=all_attentions,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ The CPMAnt Model with a language modeling head on top (linear layer with weights tied to the input embeddings).
+ """
+)
+class CpmAntForCausalLM(CpmAntPreTrainedModel, GenerationMixin):
+ _tied_weights_keys = {"lm_head.weight": "cpmant.input_embedding.weight"}
+
+ def __init__(self, config: CpmAntConfig):
+ super().__init__(config)
+ self.cpmant = CpmAntModel(config)
+
+ # lm_head.weight is tied to cpmant.input_embedding.weight
+ self.lm_head = nn.Linear(
+ config.hidden_size, config.vocab_size + config.prompt_types * config.prompt_length, bias=False
+ )
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ past_key_values: Cache | None = None,
+ use_cache: bool | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ labels: torch.Tensor | None = None,
+ return_dict: bool | None = None,
+ attention_mask: torch.Tensor | None = None, # dummy parameter for text-generation pipeline
+ logits_to_keep: int | torch.Tensor = 0,
+ **kwargs,
+ ) -> tuple | CausalLMOutputWithPast:
+ r"""
+ input_ids (`torch.Tensor` of shape `(batch_size, seq_len)`):
+ Indices of input sequence tokens in the vocabulary.
+
+ Indices can be obtained using [`CPMAntTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input-ids)
+ labels (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss.
+
+ Example:
+
+ Text Generation with CpmAntForCausalLM.
+ ```python
+ >>> from transformers import CPMAntTokenizer, CpmAntForCausalLM
+
+ >>> texts = "今天天气不错,"
+ >>> model = CpmAntForCausalLM.from_pretrained("openbmb/cpm-ant-10b")
+ >>> tokenizer = CPMAntTokenizer.from_pretrained("openbmb/cpm-ant-10b")
+ >>> input_ids = tokenizer(texts, return_tensors="pt")
+ >>> outputs = model.generate(**input_ids)
+ >>> output_texts = tokenizer.batch_decode(outputs)
+ >>> print(output_texts)
+ ['今天天气不错,阳光明媚,我和妈妈一起去超市买东西。\n在超市里,我看到了一个很好玩的玩具,它的名字叫“机器人”。它有一个圆圆的脑袋,两只圆圆的眼睛,还有一个圆圆的']
+ ```
+ """
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ model_output = self.cpmant(
+ input_ids,
+ output_attentions,
+ output_hidden_states,
+ past_key_values,
+ use_cache,
+ return_dict,
+ )
+ hidden_states = model_output.last_hidden_state if return_dict else model_output[0]
+ # Only compute necessary logits
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
+
+ loss = None
+ if labels is not None:
+ loss_func = CrossEntropyLoss()
+ loss = loss_func(logits.view(-1, logits.size(-1)), labels.view(-1))
+
+ if not return_dict:
+ output = (logits,) + model_output[1:]
+ return ((loss,) + output) if loss is not None else output
+
+ return CausalLMOutputWithPast(
+ loss=loss,
+ logits=logits,
+ past_key_values=model_output.past_key_values,
+ hidden_states=model_output.hidden_states,
+ attentions=model_output.attentions,
+ )
+
+ def get_input_embeddings(self):
+ return self.cpmant.input_embedding
+
+ def set_input_embeddings(self, embeddings):
+ self.cpmant.input_embedding = embeddings
+
+
+__all__ = ["CpmAntForCausalLM", "CpmAntModel", "CpmAntPreTrainedModel"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cpmant/tokenization_cpmant.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cpmant/tokenization_cpmant.py
new file mode 100644
index 0000000000000000000000000000000000000000..4404a53fcee67a9006082988ec50eadc4229f2e9
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cpmant/tokenization_cpmant.py
@@ -0,0 +1,232 @@
+# Copyright 2022 The OpenBMB Team and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Tokenization classes for CPMAnt."""
+
+import collections
+import os
+
+from transformers.utils import is_rjieba_available, requires_backends
+
+
+if is_rjieba_available():
+ import rjieba
+
+from ...tokenization_python import PreTrainedTokenizer
+from ...utils import logging
+
+
+logger = logging.get_logger(__name__)
+
+VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt"}
+
+
+def load_vocab(vocab_file):
+ """Loads a vocabulary file into a dictionary."""
+ vocab = collections.OrderedDict()
+ with open(vocab_file, "r", encoding="utf-8") as reader:
+ tokens = reader.readlines()
+ for index, token in enumerate(tokens):
+ token = token.rstrip("\n")
+ vocab[token] = index
+ return vocab
+
+
+class WordpieceTokenizer:
+ def __init__(self, vocab, unk_token="", max_input_chars_per_word=200):
+ self.vocab = vocab
+ self.unk_token = unk_token
+ self.max_input_chars_per_word = max_input_chars_per_word
+
+ def tokenize(self, token):
+ chars = list(token)
+ if len(chars) > self.max_input_chars_per_word:
+ return [self.unk_token]
+
+ start = 0
+ sub_tokens = []
+ while start < len(chars):
+ end = len(chars)
+ cur_substr = None
+ while start < end:
+ substr = "".join(chars[start:end])
+ if substr in self.vocab:
+ cur_substr = substr
+ break
+ end -= 1
+ if cur_substr is None:
+ sub_tokens.append(self.unk_token)
+ start += 1
+ else:
+ sub_tokens.append(cur_substr)
+ start = end
+
+ return sub_tokens
+
+
+class CpmAntTokenizer(PreTrainedTokenizer):
+ """
+ Construct a CPMAnt tokenizer. Based on byte-level Byte-Pair-Encoding.
+
+ Args:
+ vocab_file (`str`):
+ Path to the vocabulary file.
+ bod_token (`str`, *optional*, defaults to `""`):
+ The beginning of document token.
+ eod_token (`str`, *optional*, defaults to `""`):
+ The end of document token.
+ bos_token (`str`, *optional*, defaults to `""`):
+ The beginning of sequence token.
+ eos_token (`str`, *optional*, defaults to `""`):
+ The end of sequence token.
+ pad_token (`str`, *optional*, defaults to `""`):
+ The token used for padding.
+ unk_token (`str`, *optional*, defaults to `""`):
+ The unknown token.
+ line_token (`str`, *optional*, defaults to `""`):
+ The line token.
+ space_token (`str`, *optional*, defaults to `""`):
+ The space token.
+ """
+
+ vocab_files_names = VOCAB_FILES_NAMES
+ model_input_names = ["input_ids", "attention_mask"]
+ add_prefix_space = False
+
+ def __init__(
+ self,
+ vocab_file,
+ bod_token="",
+ eod_token="",
+ bos_token="",
+ eos_token="",
+ pad_token="",
+ unk_token="",
+ line_token="",
+ space_token="",
+ padding_side="left",
+ **kwargs,
+ ):
+ requires_backends(self, ["rjieba"])
+ self.bod_token = bod_token
+ self.eod_token = eod_token
+ self.encoder = load_vocab(vocab_file)
+ self.encoder[" "] = self.encoder[space_token]
+ self.encoder["\n"] = self.encoder[line_token]
+
+ del self.encoder[space_token]
+ del self.encoder[line_token]
+
+ self.encoder = collections.OrderedDict(sorted(self.encoder.items(), key=lambda x: x[1]))
+ self.decoder = {v: k for k, v in self.encoder.items()}
+
+ self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.encoder, unk_token=unk_token)
+
+ super().__init__(
+ bod_token=bod_token,
+ eod_token=eod_token,
+ bos_token=bos_token,
+ eos_token=eos_token,
+ pad_token=pad_token,
+ unk_token=unk_token,
+ line_token=line_token,
+ space_token=space_token,
+ padding_side=padding_side,
+ token_type_ids_pattern="all_zeros",
+ token_type_ids_include_special_tokens=True,
+ special_tokens_pattern="bos",
+ **kwargs,
+ )
+ for special_token in [space_token, line_token]:
+ token_id = self.added_tokens_encoder.pop(special_token, None)
+ if token_id is not None:
+ self._added_tokens_decoder.pop(token_id, None)
+ self._update_total_vocab_size()
+
+ @property
+ def bod_token_id(self):
+ return self.encoder[self.bod_token]
+
+ @property
+ def eod_token_id(self):
+ return self.encoder[self.eod_token]
+
+ @property
+ def newline_id(self):
+ return self.encoder["\n"]
+
+ @property
+ def vocab_size(self) -> int:
+ return len(self.encoder)
+
+ def get_vocab(self):
+ return dict(self.encoder, **self.added_tokens_encoder)
+
+ def _tokenize(self, text):
+ """Tokenize a string."""
+ output_tokens = []
+ for x in rjieba.cut(text, False):
+ output_tokens.extend(self.wordpiece_tokenizer.tokenize(x))
+ return output_tokens
+
+ def _decode(self, token_ids, **kwargs):
+ """Decode ids into a string."""
+ token_ids = [i for i in token_ids if i >= 0]
+ token_ids = [
+ x for x in token_ids if x != self.pad_token_id and x != self.eos_token_id and x != self.bos_token_id
+ ]
+ return super()._decode(token_ids, **kwargs)
+
+ def check(self, token):
+ return token in self.encoder
+
+ def convert_tokens_to_string(self, tokens: list[str]) -> str:
+ return "".join(tokens)
+
+ def _convert_token_to_id(self, token):
+ """Converts a token (str) in an id using the vocab."""
+ return self.encoder.get(token, self.encoder.get(self.unk_token))
+
+ def _convert_id_to_token(self, index):
+ """Converts an index (integer) in a token (str) using the vocab."""
+ return self.decoder.get(index, self.unk_token)
+
+ def save_vocabulary(self, save_directory: str, filename_prefix: str | None = None) -> tuple[str]:
+ if os.path.isdir(save_directory):
+ vocab_file = os.path.join(
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
+ )
+ else:
+ vocab_file = (filename_prefix + "-" if filename_prefix else "") + save_directory
+ index = 0
+ if " " in self.encoder:
+ self.encoder[""] = self.encoder[" "]
+ del self.encoder[" "]
+ if "\n" in self.encoder:
+ self.encoder[""] = self.encoder["\n"]
+ del self.encoder["\n"]
+ self.encoder = collections.OrderedDict(sorted(self.encoder.items(), key=lambda x: x[1]))
+ with open(vocab_file, "w", encoding="utf-8") as writer:
+ for token, token_index in self.encoder.items():
+ if index != token_index:
+ logger.warning(
+ f"Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive."
+ " Please check that the vocabulary is not corrupted!"
+ )
+ index = token_index
+ writer.write(token + "\n")
+ index += 1
+ return (vocab_file,)
+
+
+__all__ = ["CpmAntTokenizer"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cvt/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cvt/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5d3b6d6015df040ff138a55254562e31df7a1394
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cvt/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cvt/__pycache__/configuration_cvt.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cvt/__pycache__/configuration_cvt.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..81311ece489a6ed2ea53faaa0205bff9ad0ccc5f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cvt/__pycache__/configuration_cvt.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cvt/__pycache__/modeling_cvt.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cvt/__pycache__/modeling_cvt.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..48d83307d2e99618d5d192234cab6dea51c3aaaf
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cvt/__pycache__/modeling_cvt.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cwm/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cwm/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..61d8efb9a3b257fa4a7d28f1798adc43c99dadc9
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cwm/__init__.py
@@ -0,0 +1,28 @@
+# Copyright 2025 the HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_cwm import *
+ from .modeling_cwm import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cwm/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cwm/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e466cd663e51112cd72972efdcd5554a01c84676
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cwm/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cwm/__pycache__/configuration_cwm.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cwm/__pycache__/configuration_cwm.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..eecd5f5697da13664eceeef9229fa4c31448cdc2
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cwm/__pycache__/configuration_cwm.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cwm/__pycache__/modeling_cwm.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cwm/__pycache__/modeling_cwm.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b0e4324a0ba4e05b89323fd70920e753f30c8399
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cwm/__pycache__/modeling_cwm.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cwm/__pycache__/modular_cwm.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cwm/__pycache__/modular_cwm.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b872692c9ed8982522987437c78c319e81adfeec
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cwm/__pycache__/modular_cwm.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cwm/configuration_cwm.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cwm/configuration_cwm.py
new file mode 100644
index 0000000000000000000000000000000000000000..ecc3743da19de42e220ffad171cf5bc0abf48027
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cwm/configuration_cwm.py
@@ -0,0 +1,125 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/cwm/modular_cwm.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_cwm.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2025
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring
+
+
+@auto_docstring(checkpoint="facebook/cwm")
+@strict
+class CwmConfig(PreTrainedConfig):
+ r"""
+ ```python
+ >>> from transformers import CwmModel, CwmConfig
+
+ >>> # Initializing a Cwm cwm-7b style configuration
+ >>> configuration = CwmConfig()
+
+ >>> # Initializing a model from the cwm-7b style configuration
+ >>> model = CwmModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "cwm"
+ keys_to_ignore_at_inference = ["past_key_values"]
+ # Default tensor parallel plan for base model `CwmModel`
+ base_model_tp_plan = {
+ "layers.*.self_attn.q_proj": "colwise",
+ "layers.*.self_attn.k_proj": "colwise",
+ "layers.*.self_attn.v_proj": "colwise",
+ "layers.*.self_attn.o_proj": "rowwise",
+ "layers.*.mlp.gate_proj": "colwise",
+ "layers.*.mlp.up_proj": "colwise",
+ "layers.*.mlp.down_proj": "rowwise",
+ }
+ base_model_pp_plan = {
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
+ "norm": (["hidden_states"], ["hidden_states"]),
+ }
+
+ vocab_size: int = 128256
+ hidden_size: int = 6144
+ intermediate_size: int = 21504
+ num_hidden_layers: int = 64
+ num_attention_heads: int = 48
+ num_key_value_heads: int = 8
+ hidden_act: str = "silu"
+ max_position_embeddings: int = 131072
+ initializer_range: float = 0.02
+ rms_norm_eps: float = 1e-5
+ use_cache: bool = True
+ pad_token_id: int | None = None
+ bos_token_id: int = 128000
+ eos_token_id: int | list[int] | None = None
+ pretraining_tp: int = 1
+ tie_word_embeddings: bool = False
+ rope_parameters: dict | None = None
+ attention_dropout: float | int = 0.0
+ mlp_bias: bool = False
+ head_dim: int = 128
+ default_theta = 1_000_000.0
+ sliding_window: int = 8192
+ layer_types: list[str] | None = None # ["full_attention"|"sliding_attention"] per layer
+
+ def __post_init__(self, **kwargs):
+ if self.rope_parameters is None:
+ self.rope_parameters = {
+ "rope_theta": 1_000_000.0,
+ "factor": 16.0,
+ "high_freq_factor": 4.0,
+ "low_freq_factor": 1.0,
+ "original_max_position_embeddings": 8192,
+ "rope_type": "llama3",
+ }
+
+ if self.layer_types is None:
+ # Default pattern: every 4th layer uses full attention, others use sliding attention
+ window_pattern = 4
+ self.layer_types = [
+ ("full_attention" if (i % window_pattern == 0) else "sliding_attention")
+ for i in range(self.num_hidden_layers)
+ ]
+
+ self.sliding_window = int(self.sliding_window) if self.sliding_window else None
+ self.layer_types = list(self.layer_types)
+ self.eos_token_id = self.eos_token_id if self.eos_token_id is not None else [128001, 128008, 128009]
+ if self.head_dim is None:
+ self.head_dim = self.hidden_size // self.num_attention_heads
+ if self.num_key_value_heads is None:
+ self.num_key_value_heads = self.num_attention_heads
+
+ super().__post_init__(**kwargs)
+
+ def validate_architecture(self):
+ """Part of `@strict`-powered validation. Validates the architecture of the config."""
+ if self.hidden_size % self.num_attention_heads != 0:
+ raise ValueError(
+ f"The hidden size ({self.hidden_size}) is not a multiple of the number of attention "
+ f"heads ({self.num_attention_heads})."
+ )
+
+
+__all__ = ["CwmConfig"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cwm/modeling_cwm.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cwm/modeling_cwm.py
new file mode 100644
index 0000000000000000000000000000000000000000..3e0eb0504be0df9b0e6a705acdfd2d1f1e079991
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cwm/modeling_cwm.py
@@ -0,0 +1,500 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/cwm/modular_cwm.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_cwm.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2025
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+from collections.abc import Callable
+from typing import Optional
+
+import torch
+from torch import nn
+
+from ...activations import ACT2FN
+from ...cache_utils import Cache, DynamicCache
+from ...generation import GenerationMixin
+from ...integrations import use_kernel_forward_from_hub, use_kernel_func_from_hub, use_kernelized_func
+from ...masking_utils import create_causal_mask, create_sliding_window_causal_mask
+from ...modeling_flash_attention_utils import FlashAttentionKwargs
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
+from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import TransformersKwargs, auto_docstring, can_return_tuple
+from ...utils.generic import maybe_autocast, merge_with_config_defaults
+from ...utils.output_capturing import capture_outputs
+from .configuration_cwm import CwmConfig
+
+
+class CwmRotaryEmbedding(nn.Module):
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
+
+ def __init__(self, config: CwmConfig, device=None):
+ super().__init__()
+ self.max_seq_len_cached = config.max_position_embeddings
+ self.original_max_seq_len = config.max_position_embeddings
+
+ self.config = config
+
+ self.rope_type = self.config.rope_parameters["rope_type"]
+ rope_init_fn: Callable = self.compute_default_rope_parameters
+ if self.rope_type != "default":
+ rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
+ inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
+
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
+ self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
+
+ @staticmethod
+ def compute_default_rope_parameters(
+ config: CwmConfig | None = None,
+ device: Optional["torch.device"] = None,
+ seq_len: int | None = None,
+ ) -> tuple["torch.Tensor", float]:
+ """
+ Computes the inverse frequencies according to the original RoPE implementation
+ Args:
+ config ([`~transformers.PreTrainedConfig`]):
+ The model configuration.
+ device (`torch.device`):
+ The device to use for initialization of the inverse frequencies.
+ seq_len (`int`, *optional*):
+ The current sequence length. Unused for this type of RoPE.
+ Returns:
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
+ """
+ base = config.rope_parameters["rope_theta"]
+ dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
+
+ attention_factor = 1.0 # Unused in this type of RoPE
+
+ # Compute the inverse frequencies
+ inv_freq = 1.0 / (
+ base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
+ )
+ return inv_freq, attention_factor
+
+ @torch.no_grad()
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
+ def forward(self, x, position_ids):
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
+ position_ids_expanded = position_ids[:, None, :].float()
+
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
+ with maybe_autocast(device_type=device_type, enabled=False): # Force float32
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
+ emb = torch.cat((freqs, freqs), dim=-1)
+ cos = emb.cos() * self.attention_scaling
+ sin = emb.sin() * self.attention_scaling
+
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
+
+
+def rotate_half(x):
+ """Rotates half the hidden dims of the input."""
+ x1 = x[..., : x.shape[-1] // 2]
+ x2 = x[..., x.shape[-1] // 2 :]
+ return torch.cat((-x2, x1), dim=-1)
+
+
+@use_kernel_func_from_hub("rotary_pos_emb")
+def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
+ """Applies Rotary Position Embedding to the query and key tensors.
+
+ Args:
+ q (`torch.Tensor`): The query tensor.
+ k (`torch.Tensor`): The key tensor.
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
+ Returns:
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
+ """
+ cos = cos.unsqueeze(unsqueeze_dim)
+ sin = sin.unsqueeze(unsqueeze_dim)
+ q_embed = (q * cos) + (rotate_half(q) * sin)
+ k_embed = (k * cos) + (rotate_half(k) * sin)
+ return q_embed, k_embed
+
+
+def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
+ """
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
+ """
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
+ if n_rep == 1:
+ return hidden_states
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
+
+
+def eager_attention_forward(
+ module: nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: torch.Tensor | None,
+ scaling: float,
+ dropout: float = 0.0,
+ **kwargs: Unpack[TransformersKwargs],
+):
+ key_states = repeat_kv(key, module.num_key_value_groups)
+ value_states = repeat_kv(value, module.num_key_value_groups)
+
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
+ if attention_mask is not None:
+ attn_weights = attn_weights + attention_mask
+
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
+ attn_output = torch.matmul(attn_weights, value_states)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+
+ return attn_output, attn_weights
+
+
+@use_kernelized_func(apply_rotary_pos_emb)
+class CwmAttention(nn.Module):
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
+
+ def __init__(self, config: CwmConfig, layer_idx: int):
+ super().__init__()
+ self.layer_type = config.layer_types[layer_idx] if hasattr(config, "layer_types") else None
+ self.config = config
+ self.layer_idx = layer_idx
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
+ self.scaling = self.head_dim**-0.5
+ self.attention_dropout = config.attention_dropout
+ self.is_causal = True
+ self.q_proj = torch.nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=False)
+ self.k_proj = torch.nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=False)
+ self.v_proj = torch.nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=False)
+ self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
+ self.sliding_window = config.sliding_window if self.layer_type == "sliding_attention" else None
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
+ attention_mask: torch.Tensor | None,
+ past_key_values: Cache | None = None,
+ **kwargs: Unpack[FlashAttentionKwargs],
+ ) -> tuple[torch.Tensor, torch.Tensor | None]:
+ input_shape = hidden_states.shape[:-1]
+ hidden_shape = (*input_shape, -1, self.head_dim)
+
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+
+ cos, sin = position_embeddings
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
+
+ if past_key_values is not None:
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_states,
+ key_states,
+ value_states,
+ attention_mask,
+ dropout=0.0 if not self.training else self.attention_dropout,
+ scaling=self.scaling,
+ sliding_window=self.sliding_window, # main diff with Llama
+ **kwargs,
+ )
+
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ attn_output = self.o_proj(attn_output)
+ return attn_output, attn_weights
+
+
+@use_kernel_forward_from_hub("RMSNorm")
+class CwmRMSNorm(nn.Module):
+ def __init__(self, hidden_size, eps: float = 1e-6) -> None:
+ """
+ CwmRMSNorm is equivalent to T5LayerNorm
+ """
+ super().__init__()
+ self.weight = nn.Parameter(torch.ones(hidden_size))
+ self.variance_epsilon = eps
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ input_dtype = hidden_states.dtype
+ hidden_states = hidden_states.to(torch.float32)
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
+ return self.weight * hidden_states.to(input_dtype)
+
+ def extra_repr(self):
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
+
+
+class CwmMLP(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.hidden_size = config.hidden_size
+ self.intermediate_size = config.intermediate_size
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
+ self.act_fn = ACT2FN[config.hidden_act]
+
+ def forward(self, x):
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
+ return down_proj
+
+
+class CwmDecoderLayer(GradientCheckpointingLayer):
+ def __init__(self, config: CwmConfig, layer_idx: int):
+ super().__init__()
+ self.hidden_size = config.hidden_size
+ self.self_attn = CwmAttention(config=config, layer_idx=layer_idx)
+
+ self.mlp = CwmMLP(config)
+ self.input_layernorm = CwmRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.post_attention_layernorm = CwmRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ use_cache: bool | None = False,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.Tensor:
+ residual = hidden_states
+ hidden_states = self.input_layernorm(hidden_states)
+ # Self Attention
+ hidden_states, _ = self.self_attn(
+ hidden_states=hidden_states,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ position_embeddings=position_embeddings,
+ **kwargs,
+ )
+ hidden_states = residual + hidden_states
+
+ # Fully Connected
+ residual = hidden_states
+ hidden_states = self.post_attention_layernorm(hidden_states)
+ hidden_states = self.mlp(hidden_states)
+ hidden_states = residual + hidden_states
+ return hidden_states
+
+
+@auto_docstring
+class CwmPreTrainedModel(PreTrainedModel):
+ config: CwmConfig
+ base_model_prefix = "model"
+ supports_gradient_checkpointing = True
+ _no_split_modules = ["CwmDecoderLayer"]
+ _skip_keys_device_placement = ["past_key_values"]
+ _supports_flash_attn = True
+ _supports_sdpa = True
+ _supports_flex_attn = True
+
+ _can_compile_fullgraph = True
+ _supports_attention_backend = True
+ _can_record_outputs = {
+ "hidden_states": CwmDecoderLayer,
+ "attentions": CwmAttention,
+ }
+
+
+class CwmModelOutputWithPast(BaseModelOutputWithPast):
+ pass
+
+
+@auto_docstring
+class CwmModel(CwmPreTrainedModel):
+ config_class = CwmConfig
+
+ def __init__(self, config: CwmConfig):
+ super().__init__(config)
+ self.padding_idx = config.pad_token_id
+ self.vocab_size = config.vocab_size
+
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
+ self.layers = torch.nn.ModuleList(
+ [CwmDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
+ )
+ self.norm = CwmRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.rotary_emb = CwmRotaryEmbedding(config=config)
+ self.gradient_checkpointing = False
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @merge_with_config_defaults
+ @capture_outputs
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ use_cache: bool | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> CwmModelOutputWithPast:
+ if (input_ids is None) ^ (inputs_embeds is not None):
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
+
+ if inputs_embeds is None:
+ inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)
+
+ if use_cache and past_key_values is None:
+ past_key_values = DynamicCache(config=self.config)
+
+ if position_ids is None:
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
+ position_ids = position_ids.unsqueeze(0)
+
+ if not isinstance(causal_mask_mapping := attention_mask, dict):
+ mask_kwargs = {
+ "config": self.config,
+ "inputs_embeds": inputs_embeds,
+ "attention_mask": attention_mask,
+ "past_key_values": past_key_values,
+ "position_ids": position_ids,
+ }
+ sliding_mask_kwargs = mask_kwargs.copy()
+
+ causal_mask_mapping = {
+ "full_attention": create_causal_mask(**mask_kwargs),
+ "sliding_attention": create_sliding_window_causal_mask(**sliding_mask_kwargs),
+ }
+
+ hidden_states = inputs_embeds
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
+
+ for i, decoder_layer in enumerate(self.layers[: self.config.num_hidden_layers]):
+ hidden_states = decoder_layer(
+ hidden_states,
+ attention_mask=causal_mask_mapping[self.config.layer_types[i]],
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ position_embeddings=position_embeddings,
+ **kwargs,
+ )
+
+ hidden_states = self.norm(hidden_states)
+ return CwmModelOutputWithPast(
+ last_hidden_state=hidden_states,
+ past_key_values=past_key_values,
+ )
+
+
+@auto_docstring
+class CwmForCausalLM(CwmPreTrainedModel, GenerationMixin):
+ _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
+ _tp_plan = {"lm_head": "colwise_gather_output"}
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
+
+ def __init__(self, config):
+ super().__init__(config)
+ self.model = CwmModel(config)
+ self.vocab_size = config.vocab_size
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ use_cache: bool | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> CausalLMOutputWithPast:
+ r"""
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, CwmForCausalLM
+
+ >>> model = CwmForCausalLM.from_pretrained("meta-cwm/Cwm-2-7b-hf")
+ >>> tokenizer = AutoTokenizer.from_pretrained("meta-cwm/Cwm-2-7b-hf")
+
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
+
+ >>> # Generate
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
+ ```"""
+ outputs: BaseModelOutputWithPast = self.model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ **kwargs,
+ )
+
+ hidden_states = outputs.last_hidden_state
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
+
+ return CausalLMOutputWithPast(
+ loss=loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+__all__ = ["CwmPreTrainedModel", "CwmModel", "CwmForCausalLM"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cwm/modular_cwm.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cwm/modular_cwm.py
new file mode 100644
index 0000000000000000000000000000000000000000..c9571a9b91ea14718d8522942d2cec0c8ebc1449
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/cwm/modular_cwm.py
@@ -0,0 +1,196 @@
+# Copyright 2025
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+import torch
+from huggingface_hub.dataclasses import strict
+
+from ...cache_utils import Cache, DynamicCache
+from ...masking_utils import create_causal_mask, create_sliding_window_causal_mask
+from ...modeling_outputs import BaseModelOutputWithPast
+from ...processing_utils import Unpack
+from ...utils import TransformersKwargs, auto_docstring, logging
+from ..llama.configuration_llama import LlamaConfig
+from ..llama.modeling_llama import (
+ LlamaDecoderLayer,
+ LlamaForCausalLM,
+ LlamaModel,
+ LlamaPreTrainedModel,
+)
+from ..qwen2.modeling_qwen2 import Qwen2Attention, Qwen2RotaryEmbedding
+
+
+logger = logging.get_logger(__name__)
+
+
+@auto_docstring(checkpoint="facebook/cwm")
+@strict
+class CwmConfig(LlamaConfig):
+ model_type = "cwm"
+ default_theta = 1_000_000.0
+
+ vocab_size: int = 128256
+ hidden_size: int = 6144
+ intermediate_size: int = 21504
+ num_hidden_layers: int = 64
+ num_attention_heads: int = 48
+ num_key_value_heads: int = 8
+ head_dim: int = 128
+ hidden_act: str = "silu"
+ max_position_embeddings: int = 131072
+ initializer_range: float = 0.02
+ rms_norm_eps: float = 1e-5
+ use_cache: bool = True
+ pad_token_id: int | None = None
+ eos_token_id: int | list[int] | None = None
+ bos_token_id: int = 128000
+ tie_word_embeddings: bool = False
+ attention_dropout: float | int = 0.0
+ pretraining_tp: int = 1
+ mlp_bias: bool = False
+ rope_parameters: dict | None = None
+ sliding_window: int = 8192
+ layer_types: list[str] | None = None # ["full_attention"|"sliding_attention"] per layer
+
+ attention_bias = AttributeError()
+
+ def __post_init__(self, **kwargs):
+ if self.rope_parameters is None:
+ self.rope_parameters = {
+ "rope_theta": 1_000_000.0,
+ "factor": 16.0,
+ "high_freq_factor": 4.0,
+ "low_freq_factor": 1.0,
+ "original_max_position_embeddings": 8192,
+ "rope_type": "llama3",
+ }
+
+ if self.layer_types is None:
+ # Default pattern: every 4th layer uses full attention, others use sliding attention
+ window_pattern = 4
+ self.layer_types = [
+ ("full_attention" if (i % window_pattern == 0) else "sliding_attention")
+ for i in range(self.num_hidden_layers)
+ ]
+
+ self.sliding_window = int(self.sliding_window) if self.sliding_window else None
+ self.layer_types = list(self.layer_types)
+ self.eos_token_id = self.eos_token_id if self.eos_token_id is not None else [128001, 128008, 128009]
+ super().__post_init__(**kwargs)
+
+
+class CwmRotaryEmbedding(Qwen2RotaryEmbedding):
+ pass
+
+
+class CwmAttention(Qwen2Attention):
+ def __init__(self, config: CwmConfig, layer_idx: int):
+ super().__init__(config=config, layer_idx=layer_idx)
+ self.q_proj = torch.nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=False)
+ self.k_proj = torch.nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=False)
+ self.v_proj = torch.nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=False)
+
+
+class CwmDecoderLayer(LlamaDecoderLayer):
+ def __init__(self, config: CwmConfig, layer_idx: int):
+ super().__init__(config=config, layer_idx=layer_idx)
+ self.self_attn = CwmAttention(config=config, layer_idx=layer_idx)
+
+
+class CwmPreTrainedModel(LlamaPreTrainedModel):
+ pass
+
+
+class CwmModelOutputWithPast(BaseModelOutputWithPast):
+ pass
+
+
+class CwmModel(LlamaModel):
+ config_class = CwmConfig
+
+ def __init__(self, config: CwmConfig):
+ super().__init__(config)
+ self.layers = torch.nn.ModuleList(
+ [CwmDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
+ )
+
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ use_cache: bool | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> CwmModelOutputWithPast:
+ if (input_ids is None) ^ (inputs_embeds is not None):
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
+
+ if inputs_embeds is None:
+ inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)
+
+ if use_cache and past_key_values is None:
+ past_key_values = DynamicCache(config=self.config)
+
+ if position_ids is None:
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
+ position_ids = position_ids.unsqueeze(0)
+
+ if not isinstance(causal_mask_mapping := attention_mask, dict):
+ mask_kwargs = {
+ "config": self.config,
+ "inputs_embeds": inputs_embeds,
+ "attention_mask": attention_mask,
+ "past_key_values": past_key_values,
+ "position_ids": position_ids,
+ }
+ sliding_mask_kwargs = mask_kwargs.copy()
+
+ causal_mask_mapping = {
+ "full_attention": create_causal_mask(**mask_kwargs),
+ "sliding_attention": create_sliding_window_causal_mask(**sliding_mask_kwargs),
+ }
+
+ hidden_states = inputs_embeds
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
+
+ for i, decoder_layer in enumerate(self.layers[: self.config.num_hidden_layers]):
+ hidden_states = decoder_layer(
+ hidden_states,
+ attention_mask=causal_mask_mapping[self.config.layer_types[i]],
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ position_embeddings=position_embeddings,
+ **kwargs,
+ )
+
+ hidden_states = self.norm(hidden_states)
+ return CwmModelOutputWithPast(
+ last_hidden_state=hidden_states,
+ past_key_values=past_key_values,
+ )
+
+
+class CwmForCausalLM(LlamaForCausalLM):
+ pass
+
+
+__all__ = [
+ "CwmConfig",
+ "CwmPreTrainedModel",
+ "CwmModel",
+ "CwmForCausalLM",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/d_fine/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/d_fine/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9fe1546788993c2f48f76583f474271b75301ae8
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/d_fine/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/d_fine/__pycache__/configuration_d_fine.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/d_fine/__pycache__/configuration_d_fine.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9afd8e9a5b2e0a8148d19ffcb6fa7a26c3ff8df1
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/d_fine/__pycache__/configuration_d_fine.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/d_fine/__pycache__/modular_d_fine.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/d_fine/__pycache__/modular_d_fine.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..80d8599939e7dfa3414a82c5a7b3f6279e489225
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/d_fine/__pycache__/modular_d_fine.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dab_detr/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dab_detr/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e63020e79e12aa296e6495fe9d39c9acb275c5ac
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dab_detr/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dab_detr/__pycache__/configuration_dab_detr.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dab_detr/__pycache__/configuration_dab_detr.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..633025a121fe2d2de26893f5d20d3a9c0a769669
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dab_detr/__pycache__/configuration_dab_detr.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dab_detr/__pycache__/modeling_dab_detr.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dab_detr/__pycache__/modeling_dab_detr.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..56e7fa4a614425071d03b0cdb5b0d0337e785e27
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dab_detr/__pycache__/modeling_dab_detr.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/data2vec/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/data2vec/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..4fcf78dd606f56c7b0def6d4ff1a3fb8f49a8fa0
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/data2vec/__init__.py
@@ -0,0 +1,31 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_data2vec_audio import *
+ from .configuration_data2vec_text import *
+ from .configuration_data2vec_vision import *
+ from .modeling_data2vec_audio import *
+ from .modeling_data2vec_text import *
+ from .modeling_data2vec_vision import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/data2vec/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/data2vec/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b93f0e80e143e5c6041dcbef41d456a31a39166a
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/data2vec/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/data2vec/__pycache__/configuration_data2vec_audio.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/data2vec/__pycache__/configuration_data2vec_audio.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..37ecf93d5c7c0201ea3f9ed6cb43998f67f5ceb7
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/data2vec/__pycache__/configuration_data2vec_audio.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/data2vec/__pycache__/configuration_data2vec_text.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/data2vec/__pycache__/configuration_data2vec_text.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..afeb5647f8305159064a283d8fb63a6b02ec1c12
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/data2vec/__pycache__/configuration_data2vec_text.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/data2vec/__pycache__/configuration_data2vec_vision.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/data2vec/__pycache__/configuration_data2vec_vision.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c18b9b2fe918d796f6708c317bf9225f9387e029
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/data2vec/__pycache__/configuration_data2vec_vision.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/data2vec/__pycache__/modeling_data2vec_audio.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/data2vec/__pycache__/modeling_data2vec_audio.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a2982e78f807325df32a36147f8fb052b9a0ff06
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/data2vec/__pycache__/modeling_data2vec_audio.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/data2vec/__pycache__/modeling_data2vec_text.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/data2vec/__pycache__/modeling_data2vec_text.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..44046474e0cf07d81755877bec0b968cc8de7bc1
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/data2vec/__pycache__/modeling_data2vec_text.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/data2vec/__pycache__/modeling_data2vec_vision.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/data2vec/__pycache__/modeling_data2vec_vision.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b52297b16207a82c7fd982c52510506fee80c376
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/data2vec/__pycache__/modeling_data2vec_vision.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/data2vec/__pycache__/modular_data2vec_audio.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/data2vec/__pycache__/modular_data2vec_audio.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3a3455fac1e8b5c9d193c6d2bedc128d985cf8fa
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/data2vec/__pycache__/modular_data2vec_audio.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/data2vec/__pycache__/modular_data2vec_text.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/data2vec/__pycache__/modular_data2vec_text.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bff86ba6a319506e53e76a1f5b4b78daad8c84f7
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/data2vec/__pycache__/modular_data2vec_text.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/data2vec/configuration_data2vec_audio.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/data2vec/configuration_data2vec_audio.py
new file mode 100644
index 0000000000000000000000000000000000000000..55020e087866af243ede72a8745c179480046d20
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/data2vec/configuration_data2vec_audio.py
@@ -0,0 +1,197 @@
+# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Data2VecText configuration"""
+
+import math
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring
+
+
+@auto_docstring(checkpoint="facebook/data2vec-audio-base-960h")
+@strict
+class Data2VecAudioConfig(PreTrainedConfig):
+ r"""
+ feat_proj_dropout (`float`, *optional*, defaults to 0.0):
+ The dropout probability for output of the feature encoder.
+ final_dropout (`float`, *optional*, defaults to 0.1):
+ The dropout probability for the final projection layer of [`Data2VecAudioForCTC`].
+ feat_extract_activation (`str, `optional`, defaults to `"gelu"`):
+ The non-linear activation function (function or string) in the 1D convolutional layers of the feature
+ extractor. If string, `"gelu"`, `"relu"`, `"selu"` and `"gelu_new"` are supported.
+ conv_dim (`tuple[int]` or `list[int]`, *optional*, defaults to `(512, 512, 512, 512, 512, 512, 512)`):
+ A tuple of integers defining the number of input and output channels of each 1D convolutional layer in the
+ feature encoder. The length of *conv_dim* defines the number of 1D convolutional layers.
+ conv_stride (`tuple[int]` or `list[int]`, *optional*, defaults to `(5, 2, 2, 2, 2, 2, 2)`):
+ A tuple of integers defining the stride of each 1D convolutional layer in the feature encoder. The length
+ of *conv_stride* defines the number of convolutional layers and has to match the length of *conv_dim*.
+ conv_bias (`bool`, *optional*, defaults to `False`):
+ Whether the 1D convolutional layers have a bias.
+ num_conv_pos_embedding_groups (`int`, *optional*, defaults to 16):
+ Number of groups of 1D convolutional positional embeddings layer.
+ conv_pos_kernel_size (`int`, *optional*, defaults to `19`):
+ Kernel size of positional conv module.
+ num_conv_pos_embeddings (`int`, *optional*, defaults to 128):
+ Number of convolutional positional embeddings. Defines the kernel size of 1D convolutional positional
+ embeddings layer.
+ mask_time_prob (`float`, *optional*, defaults to 0.05):
+ Percentage (between 0 and 1) of all feature vectors along the time axis which will be masked. The masking
+ procedure generates ''mask_time_prob*len(time_axis)/mask_time_length'' independent masks over the axis. If
+ reasoning from the probability of each feature vector to be chosen as the start of the vector span to be
+ masked, *mask_time_prob* should be `prob_vector_start*mask_time_length`. Note that overlap may decrease the
+ mask_time_length (`int`, *optional*, defaults to 10):
+ Length of vector span along the time axis.
+ mask_time_min_masks (`int`, *optional*, defaults to 2),:
+ The minimum number of masks of length `mask_feature_length` generated along the time axis, each time step,
+ irrespectively of `mask_feature_prob`. Only relevant if ''mask_time_prob*len(time_axis)/mask_time_length <
+ mask_time_min_masks''
+ mask_feature_prob (`float`, *optional*, defaults to 0.0):
+ Percentage (between 0 and 1) of all feature vectors along the feature axis which will be masked. The
+ masking procedure generates ''mask_feature_prob*len(feature_axis)/mask_time_length'' independent masks over
+ the axis. If reasoning from the probability of each feature vector to be chosen as the start of the vector
+ span to be masked, *mask_feature_prob* should be `prob_vector_start*mask_feature_length`. Note that overlap
+ may decrease the actual percentage of masked vectors. This is only relevant if `apply_spec_augment is
+ True`.
+ mask_feature_length (`int`, *optional*, defaults to 10):
+ Length of vector span along the feature axis.
+ mask_feature_min_masks (`int`, *optional*, defaults to 0):
+ The minimum number of masks of length `mask_feature_length` generated along the feature axis, each time
+ step, irrespectively of `mask_feature_prob`. Only relevant if
+ ''mask_feature_prob*len(feature_axis)/mask_feature_length < mask_feature_min_masks''
+ ctc_loss_reduction (`str`, *optional*, defaults to `"sum"`):
+ Specifies the reduction to apply to the output of `torch.nn.CTCLoss`. Only relevant when training an
+ instance of [`Data2VecAudioForCTC`].
+ ctc_zero_infinity (`bool`, *optional*, defaults to `False`):
+ Whether to zero infinite losses and the associated gradients of `torch.nn.CTCLoss`. Infinite losses mainly
+ occur when the inputs are too short to be aligned to the targets. Only relevant when training an instance
+ of [`Data2VecAudioForCTC`].
+ use_weighted_layer_sum (`bool`, *optional*, defaults to `False`):
+ Whether to use a weighted average of layer outputs with learned weights. Only relevant when using an
+ instance of [`Data2VecAudioForSequenceClassification`].
+ classifier_proj_size (`int`, *optional*, defaults to 256):
+ Dimensionality of the projection before token mean-pooling for classification.
+ tdnn_dim (`tuple[int]` or `list[int]`, *optional*, defaults to `(512, 512, 512, 512, 1500)`):
+ A tuple of integers defining the number of output channels of each 1D convolutional layer in the *TDNN*
+ module of the *XVector* model. The length of *tdnn_dim* defines the number of *TDNN* layers.
+ tdnn_kernel (`tuple[int]` or `list[int]`, *optional*, defaults to `(5, 3, 3, 1, 1)`):
+ A tuple of integers defining the kernel size of each 1D convolutional layer in the *TDNN* module of the
+ *XVector* model. The length of *tdnn_kernel* has to match the length of *tdnn_dim*.
+ tdnn_dilation (`tuple[int]` or `list[int]`, *optional*, defaults to `(1, 2, 3, 1, 1)`):
+ A tuple of integers defining the dilation factor of each 1D convolutional layer in *TDNN* module of the
+ *XVector* model. The length of *tdnn_dilation* has to match the length of *tdnn_dim*.
+ xvector_output_dim (`int`, *optional*, defaults to 512):
+ Dimensionality of the *XVector* embedding vectors.
+ add_adapter (`bool`, *optional*, defaults to `False`):
+ Whether a convolutional network should be stacked on top of the Data2VecAudio Encoder. Can be very useful
+ for warm-starting Data2VecAudio for SpeechEncoderDecoder models.
+ adapter_kernel_size (`int`, *optional*, defaults to 3):
+ Kernel size of the convolutional layers in the adapter network. Only relevant if `add_adapter is True`.
+ adapter_stride (`int`, *optional*, defaults to 2):
+ Stride of the convolutional layers in the adapter network. Only relevant if `add_adapter is True`.
+ num_adapter_layers (`int`, *optional*, defaults to 3):
+ Number of convolutional layers that should be used in the adapter network. Only relevant if `add_adapter is
+ True`.
+ output_hidden_size (`int`, *optional*):
+ Dimensionality of the encoder output layer. If not defined, this defaults to *hidden-size*. Only relevant
+ if `add_adapter is True`.
+
+ Example:
+
+ ```python
+ >>> from transformers import Data2VecAudioConfig, Data2VecAudioModel
+
+ >>> # Initializing a Data2VecAudio facebook/data2vec-audio-base-960h style configuration
+ >>> configuration = Data2VecAudioConfig()
+
+ >>> # Initializing a model (with random weights) from the facebook/data2vec-audio-base-960h style configuration
+ >>> model = Data2VecAudioModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "data2vec-audio"
+
+ vocab_size: int = 32
+ hidden_size: int = 768
+ num_hidden_layers: int = 12
+ num_attention_heads: int = 12
+ intermediate_size: int = 3072
+ hidden_act: str = "gelu"
+ hidden_dropout: float | int = 0.1
+ activation_dropout: float | int = 0.1
+ attention_dropout: float | int = 0.1
+ feat_proj_dropout: float | int = 0.0
+ final_dropout: float | int = 0.1
+ layerdrop: float | int = 0.1
+ initializer_range: float = 0.02
+ layer_norm_eps: float = 1e-5
+ feat_extract_activation: str = "gelu"
+ conv_dim: list[int] | tuple[int, ...] = (512, 512, 512, 512, 512, 512, 512)
+ conv_stride: list[int] | tuple[int, ...] = (5, 2, 2, 2, 2, 2, 2)
+ conv_kernel: list[int] | tuple[int, ...] = (10, 3, 3, 3, 3, 2, 2)
+ conv_bias: bool = False
+ num_conv_pos_embedding_groups: int = 16
+ conv_pos_kernel_size: int = 19
+ num_conv_pos_embeddings: int = 5
+ mask_time_prob: float | int = 0.05
+ mask_time_length: int = 10
+ mask_time_min_masks: int = 2
+ mask_feature_prob: float | int = 0.0
+ mask_feature_length: int = 10
+ mask_feature_min_masks: int = 0
+ ctc_loss_reduction: str = "sum"
+ ctc_zero_infinity: bool = False
+ use_weighted_layer_sum: bool = False
+ classifier_proj_size: int = 256
+ tdnn_dim: list[int] | tuple[int, ...] = (512, 512, 512, 512, 1500)
+ tdnn_kernel: list[int] | tuple[int, ...] = (5, 3, 3, 1, 1)
+ tdnn_dilation: list[int] | tuple[int, ...] = (1, 2, 3, 1, 1)
+ xvector_output_dim: int = 512
+ pad_token_id: int | None = 0
+ bos_token_id: int | None = 1
+ eos_token_id: int | list[int] | None = 2
+ add_adapter: bool = False
+ adapter_kernel_size: int = 3
+ adapter_stride: int = 2
+ num_adapter_layers: int = 3
+ output_hidden_size: int | None = None
+
+ def __post_init__(self, **kwargs):
+ self.output_hidden_size = self.output_hidden_size or self.hidden_size
+ self.num_feat_extract_layers = len(self.conv_dim)
+ super().__post_init__(**kwargs)
+
+ def validate_architecture(self):
+ """Part of `@strict`-powered validation. Validates the architecture of the config."""
+ if (
+ (len(self.conv_stride) != self.num_feat_extract_layers)
+ or (len(self.conv_kernel) != self.num_feat_extract_layers)
+ or (len(self.conv_dim) != self.num_feat_extract_layers)
+ ):
+ raise ValueError(
+ "Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` =="
+ " `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) ="
+ f" {len(self.conv_dim)}`, `len(config.conv_stride) = {len(self.conv_stride)}`,"
+ f" `len(config.conv_kernel) = {len(self.conv_kernel)}`."
+ )
+
+ @property
+ def inputs_to_logits_ratio(self):
+ return math.prod(self.conv_stride)
+
+
+__all__ = ["Data2VecAudioConfig"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/data2vec/configuration_data2vec_text.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/data2vec/configuration_data2vec_text.py
new file mode 100644
index 0000000000000000000000000000000000000000..c26d419fe28358bad422a270b5f789752471f827
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/data2vec/configuration_data2vec_text.py
@@ -0,0 +1,65 @@
+# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Data2VecText configuration"""
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring
+
+
+@auto_docstring(checkpoint="facebook/data2vec-text-base")
+@strict
+class Data2VecTextConfig(PreTrainedConfig):
+ r"""
+ Examples:
+
+ ```python
+ >>> from transformers import Data2VecTextConfig, Data2VecTextModel
+
+ >>> # Initializing a Data2VecText facebook/data2vec-text-base style configuration
+ >>> configuration = Data2VecTextConfig()
+
+ >>> # Initializing a model (with random weights) from the facebook/data2vec-text-base style configuration
+ >>> model = Data2VecTextModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "data2vec-text"
+
+ vocab_size: int = 30522
+ hidden_size: int = 768
+ num_hidden_layers: int = 12
+ num_attention_heads: int = 12
+ intermediate_size: int = 3072
+ hidden_act: str = "gelu"
+ hidden_dropout_prob: float | int = 0.1
+ attention_probs_dropout_prob: float | int = 0.1
+ max_position_embeddings: int = 512
+ type_vocab_size: int = 2
+ initializer_range: float = 0.02
+ layer_norm_eps: float = 1e-12
+ pad_token_id: int | None = 1
+ bos_token_id: int | None = 0
+ eos_token_id: int | list[int] | None = 2
+ use_cache: bool = True
+ classifier_dropout: float | int | None = None
+ is_decoder: bool = False
+ add_cross_attention: bool = False
+ tie_word_embeddings: bool = True
+
+
+__all__ = ["Data2VecTextConfig"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/data2vec/configuration_data2vec_vision.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/data2vec/configuration_data2vec_vision.py
new file mode 100644
index 0000000000000000000000000000000000000000..9c51900ac59309e30050401ff11a5a41657fccb5
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/data2vec/configuration_data2vec_vision.py
@@ -0,0 +1,92 @@
+# Copyright Meta Platforms and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Data2VecVision model configuration"""
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring
+
+
+@auto_docstring(checkpoint="facebook/data2vec-vision-base")
+@strict
+class Data2VecVisionConfig(PreTrainedConfig):
+ r"""
+ use_mask_token (`bool`, *optional*, defaults to `False`):
+ Whether to use a mask token for masked image modeling.
+ use_shared_relative_position_bias (`bool`, *optional*, defaults to `False`):
+ Whether to use the same relative position embeddings across all self-attention layers of the Transformer.
+ use_mean_pooling (`bool`, *optional*, defaults to `True`):
+ Whether to mean pool the final hidden states of the patches instead of using the final hidden state of the
+ CLS token, before applying the classification head.
+ pool_scales (`tuple[int]`, *optional*, defaults to `[1, 2, 3, 6]`):
+ Pooling scales used in Pooling Pyramid Module applied on the last feature map.
+ use_auxiliary_head (`bool`, *optional*, defaults to `True`):
+ Whether to use an auxiliary head during training.
+ auxiliary_loss_weight (`float`, *optional*, defaults to 0.4):
+ Weight of the cross-entropy loss of the auxiliary head.
+ auxiliary_channels (`int`, *optional*, defaults to 256):
+ Number of channels to use in the auxiliary head.
+ auxiliary_num_convs (`int`, *optional*, defaults to 1):
+ Number of convolutional layers to use in the auxiliary head.
+ auxiliary_concat_input (`bool`, *optional*, defaults to `False`):
+ Whether to concatenate the output of the auxiliary head with the input before the classification layer.
+
+ Example:
+
+ ```python
+ >>> from transformers import Data2VecVisionConfig, Data2VecVisionModel
+
+ >>> # Initializing a Data2VecVision data2vec_vision-base-patch16-224-in22k style configuration
+ >>> configuration = Data2VecVisionConfig()
+
+ >>> # Initializing a model (with random weights) from the data2vec_vision-base-patch16-224-in22k style configuration
+ >>> model = Data2VecVisionModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "data2vec-vision"
+
+ hidden_size: int = 768
+ num_hidden_layers: int = 12
+ num_attention_heads: int = 12
+ intermediate_size: int = 3072
+ hidden_act: str = "gelu"
+ hidden_dropout_prob: float | int = 0.0
+ attention_probs_dropout_prob: float | int = 0.0
+ initializer_range: float = 0.02
+ layer_norm_eps: float = 1e-12
+ image_size: int | list[int] | tuple[int, int] = 224
+ patch_size: int | list[int] | tuple[int, int] = 16
+ num_channels: int = 3
+ use_mask_token: bool = False
+ use_absolute_position_embeddings: bool = False
+ use_relative_position_bias: bool = False
+ use_shared_relative_position_bias: bool = False
+ layer_scale_init_value: float = 0.1
+ drop_path_rate: float | int = 0.1
+ use_mean_pooling: bool = True
+ out_indices: list[int] | tuple[int, ...] = (3, 5, 7, 11)
+ pool_scales: list[int] | tuple[int, ...] = (1, 2, 3, 6)
+ use_auxiliary_head: bool = True
+ auxiliary_loss_weight: float = 0.4
+ auxiliary_channels: int = 256
+ auxiliary_num_convs: int = 1
+ auxiliary_concat_input: bool = False
+ semantic_loss_ignore_index: int = 255
+
+
+__all__ = ["Data2VecVisionConfig"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/data2vec/modeling_data2vec_audio.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/data2vec/modeling_data2vec_audio.py
new file mode 100644
index 0000000000000000000000000000000000000000..bb3af4ecf25a56549c1acbb55736c87880cce45a
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/data2vec/modeling_data2vec_audio.py
@@ -0,0 +1,1324 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/data2vec/modular_data2vec_audio.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_data2vec_audio.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2022 The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import math
+import warnings
+from collections.abc import Callable
+
+import numpy as np
+import torch
+from torch import nn
+from torch.nn import CrossEntropyLoss
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...integrations.deepspeed import is_deepspeed_zero3_enabled
+from ...integrations.fsdp import is_fsdp_managed_module
+from ...masking_utils import create_bidirectional_mask
+from ...modeling_flash_attention_utils import FlashAttentionKwargs
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import (
+ BaseModelOutput,
+ CausalLMOutput,
+ SequenceClassifierOutput,
+ TokenClassifierOutput,
+ Wav2Vec2BaseModelOutput,
+ XVectorOutput,
+)
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import TransformersKwargs, auto_docstring, is_peft_available
+from .configuration_data2vec_audio import Data2VecAudioConfig
+
+
+class Data2VecAudioConvLayer(GradientCheckpointingLayer):
+ def __init__(self, config, layer_id=0):
+ super().__init__()
+ self.in_conv_dim = config.conv_dim[layer_id - 1] if layer_id > 0 else 1
+ self.out_conv_dim = config.conv_dim[layer_id]
+
+ self.conv = nn.Conv1d(
+ self.in_conv_dim,
+ self.out_conv_dim,
+ kernel_size=config.conv_kernel[layer_id],
+ stride=config.conv_stride[layer_id],
+ bias=config.conv_bias,
+ )
+ self.layer_norm = nn.LayerNorm(self.out_conv_dim, elementwise_affine=True)
+ self.activation = ACT2FN[config.feat_extract_activation]
+
+ def forward(self, hidden_states):
+ hidden_states = self.conv(hidden_states)
+
+ hidden_states = hidden_states.transpose(-2, -1)
+ hidden_states = self.layer_norm(hidden_states)
+ hidden_states = hidden_states.transpose(-2, -1)
+
+ hidden_states = self.activation(hidden_states)
+ return hidden_states
+
+
+class Data2VecAudioPadLayer(nn.Module):
+ def __init__(self, num_conv_pos_embeddings):
+ super().__init__()
+ self.num_pad_remove = 1 if num_conv_pos_embeddings % 2 == 0 else 0
+
+ def forward(self, hidden_states):
+ if self.num_pad_remove > 0:
+ hidden_states = hidden_states[:, :, : -self.num_pad_remove]
+ return hidden_states
+
+
+class Data2VecAudioPositionalConvLayer(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.conv = nn.Conv1d(
+ config.hidden_size,
+ config.hidden_size,
+ kernel_size=config.conv_pos_kernel_size,
+ padding=config.conv_pos_kernel_size // 2,
+ groups=config.num_conv_pos_embedding_groups,
+ )
+
+ self.padding = Data2VecAudioPadLayer(config.conv_pos_kernel_size)
+ self.activation = ACT2FN[config.feat_extract_activation]
+ # no learnable parameters
+ self.layer_norm = nn.LayerNorm(config.hidden_size, elementwise_affine=False)
+
+ def forward(self, hidden_states):
+ hidden_states = self.conv(hidden_states)
+ hidden_states = self.padding(hidden_states)
+
+ hidden_states = hidden_states.transpose(1, 2)
+ hidden_states = self.layer_norm(hidden_states)
+ hidden_states = hidden_states.transpose(1, 2)
+ hidden_states = self.activation(hidden_states)
+ return hidden_states
+
+
+class Data2VecAudioPositionalConvEmbedding(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.layers = nn.ModuleList(
+ [Data2VecAudioPositionalConvLayer(config) for _ in range(config.num_conv_pos_embeddings)]
+ )
+
+ def forward(self, hidden_states):
+ hidden_states = hidden_states.transpose(1, 2)
+ for layer in self.layers:
+ hidden_states = layer(hidden_states)
+ hidden_states = hidden_states.transpose(1, 2)
+ return hidden_states
+
+
+class Data2VecAudioFeatureEncoder(nn.Module):
+ """Construct the features from raw audio waveform"""
+
+ def __init__(self, config):
+ super().__init__()
+ self.conv_layers = nn.ModuleList(
+ [Data2VecAudioConvLayer(config, layer_id=i) for i in range(config.num_feat_extract_layers)]
+ )
+ self.gradient_checkpointing = False
+ self._requires_grad = True
+
+ def _freeze_parameters(self):
+ for param in self.parameters():
+ param.requires_grad = False
+ self._requires_grad = False
+
+ def forward(self, input_values):
+ hidden_states = input_values[:, None]
+
+ # make sure hidden_states require grad for gradient_checkpointing
+ if self._requires_grad and self.training:
+ hidden_states.requires_grad = True
+
+ for conv_layer in self.conv_layers:
+ hidden_states = conv_layer(hidden_states)
+
+ return hidden_states
+
+
+class Data2VecAudioFeatureProjection(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.layer_norm = nn.LayerNorm(config.conv_dim[-1], eps=config.layer_norm_eps)
+ self.projection = nn.Linear(config.conv_dim[-1], config.hidden_size)
+ self.dropout = nn.Dropout(config.feat_proj_dropout)
+
+ def forward(self, hidden_states):
+ # non-projected hidden states are needed for quantization
+ norm_hidden_states = self.layer_norm(hidden_states)
+ hidden_states = self.projection(norm_hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ return hidden_states, norm_hidden_states
+
+
+def eager_attention_forward(
+ module: nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: torch.Tensor | None,
+ scaling: float | None = None,
+ dropout: float = 0.0,
+ **kwargs: Unpack[TransformersKwargs],
+):
+ if scaling is None:
+ scaling = query.size(-1) ** -0.5
+
+ # Take the dot product between "query" and "key" to get the raw attention scores.
+ attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
+
+ if attention_mask is not None:
+ attn_weights = attn_weights + attention_mask
+
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
+
+ attn_output = torch.matmul(attn_weights, value)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+
+ return attn_output, attn_weights
+
+
+class Data2VecAudioAttention(nn.Module):
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
+
+ def __init__(
+ self,
+ embed_dim: int,
+ num_heads: int,
+ dropout: float = 0.0,
+ is_decoder: bool = False,
+ bias: bool = True,
+ is_causal: bool = False,
+ config: Data2VecAudioConfig | None = None,
+ ):
+ super().__init__()
+ self.embed_dim = embed_dim
+ self.num_heads = num_heads
+ self.dropout = dropout
+ self.head_dim = embed_dim // num_heads
+ self.config = config
+
+ if (self.head_dim * num_heads) != self.embed_dim:
+ raise ValueError(
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
+ f" and `num_heads`: {num_heads})."
+ )
+ self.scaling = self.head_dim**-0.5
+ self.is_decoder = is_decoder
+ self.is_causal = is_causal
+
+ self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
+ self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ key_value_states: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ output_attentions: bool | None = False,
+ # TODO: we need a refactor so that the different attention modules can get their specific kwargs
+ # ATM, we have mixed things encoder, decoder, and encoder-decoder attn
+ **kwargs: Unpack[FlashAttentionKwargs],
+ ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
+ """Input shape: Batch x Time x Channel"""
+
+ # if key_value_states are provided this layer is used as a cross-attention layer
+ # for the decoder
+ is_cross_attention = key_value_states is not None
+
+ # determine input shapes
+ input_shape = hidden_states.shape[:-1]
+
+ hidden_shape = (*input_shape, -1, self.head_dim)
+
+ # get query proj
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+
+ current_states = key_value_states if is_cross_attention else hidden_states
+ kv_shape = (*current_states.shape[:-1], -1, self.head_dim)
+ key_states = self.k_proj(current_states).view(kv_shape).transpose(1, 2)
+ value_states = self.v_proj(current_states).view(kv_shape).transpose(1, 2)
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_states,
+ key_states,
+ value_states,
+ attention_mask,
+ dropout=0.0 if not self.training else self.dropout,
+ scaling=self.scaling,
+ output_attentions=output_attentions,
+ **kwargs,
+ )
+
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ attn_output = self.out_proj(attn_output)
+
+ return attn_output, attn_weights, None
+
+
+class Data2VecAudioFeedForward(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.intermediate_dropout = nn.Dropout(config.activation_dropout)
+
+ self.intermediate_dense = nn.Linear(config.hidden_size, config.intermediate_size)
+ if isinstance(config.hidden_act, str):
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
+ else:
+ self.intermediate_act_fn = config.hidden_act
+
+ self.output_dense = nn.Linear(config.intermediate_size, config.hidden_size)
+ self.output_dropout = nn.Dropout(config.hidden_dropout)
+
+ def forward(self, hidden_states):
+ hidden_states = self.intermediate_dense(hidden_states)
+ hidden_states = self.intermediate_act_fn(hidden_states)
+ hidden_states = self.intermediate_dropout(hidden_states)
+
+ hidden_states = self.output_dense(hidden_states)
+ hidden_states = self.output_dropout(hidden_states)
+ return hidden_states
+
+
+class Data2VecAudioEncoderLayer(GradientCheckpointingLayer):
+ def __init__(self, config):
+ super().__init__()
+ self.attention = Data2VecAudioAttention(
+ embed_dim=config.hidden_size,
+ num_heads=config.num_attention_heads,
+ dropout=config.attention_dropout,
+ is_decoder=False,
+ config=config,
+ )
+
+ self.dropout = nn.Dropout(config.hidden_dropout)
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.feed_forward = Data2VecAudioFeedForward(config)
+ self.final_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+
+ def forward(self, hidden_states, attention_mask=None, output_attentions=False):
+ attn_residual = hidden_states
+ hidden_states, attn_weights, _ = self.attention(
+ hidden_states, attention_mask=attention_mask, output_attentions=output_attentions
+ )
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = attn_residual + hidden_states
+
+ hidden_states = self.layer_norm(hidden_states)
+ hidden_states = hidden_states + self.feed_forward(hidden_states)
+ hidden_states = self.final_layer_norm(hidden_states)
+
+ outputs = (hidden_states,)
+
+ if output_attentions:
+ outputs += (attn_weights,)
+
+ return outputs
+
+
+class Data2VecAudioEncoder(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.pos_conv_embed = Data2VecAudioPositionalConvEmbedding(config)
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout)
+ self.layers = nn.ModuleList([Data2VecAudioEncoderLayer(config) for _ in range(config.num_hidden_layers)])
+ self.gradient_checkpointing = False
+
+ def forward(
+ self,
+ hidden_states: torch.tensor,
+ attention_mask: torch.Tensor | None = None,
+ output_attentions: bool = False,
+ output_hidden_states: bool = False,
+ return_dict: bool = True,
+ ):
+ all_hidden_states = () if output_hidden_states else None
+ all_self_attentions = () if output_attentions else None
+
+ if attention_mask is not None:
+ # make sure padded tokens output 0
+ expand_attention_mask = attention_mask.unsqueeze(-1).repeat(1, 1, hidden_states.shape[2])
+ hidden_states[~expand_attention_mask] = 0
+
+ attention_mask = create_bidirectional_mask(
+ config=self.config,
+ inputs_embeds=hidden_states,
+ attention_mask=attention_mask,
+ )
+
+ position_embeddings = self.pos_conv_embed(hidden_states)
+ hidden_states = hidden_states + position_embeddings.to(hidden_states.device)
+ hidden_states = self.layer_norm(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+
+ synced_gpus = is_deepspeed_zero3_enabled() or is_fsdp_managed_module(self)
+
+ for layer in self.layers:
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ # add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
+ dropout_probability = torch.rand([])
+
+ skip_the_layer = self.training and dropout_probability < self.config.layerdrop
+ if not skip_the_layer or synced_gpus:
+ # under fsdp or deepspeed zero3 all gpus must run in sync
+ layer_outputs = layer(
+ hidden_states, attention_mask=attention_mask, output_attentions=output_attentions
+ )
+ hidden_states = layer_outputs[0]
+
+ if skip_the_layer:
+ layer_outputs = (None, None)
+
+ if output_attentions:
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
+
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ if not return_dict:
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
+ return BaseModelOutput(
+ last_hidden_state=hidden_states,
+ hidden_states=all_hidden_states,
+ attentions=all_self_attentions,
+ )
+
+
+class Data2VecAudioAdapterLayer(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.conv = nn.Conv1d(
+ config.output_hidden_size,
+ 2 * config.output_hidden_size,
+ config.adapter_kernel_size,
+ stride=config.adapter_stride,
+ padding=1,
+ )
+
+ def forward(self, hidden_states):
+ hidden_states = self.conv(hidden_states)
+ hidden_states = nn.functional.glu(hidden_states, dim=1)
+
+ return hidden_states
+
+
+class Data2VecAudioAdapter(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+
+ # feature dim might need to be down-projected
+ if config.output_hidden_size != config.hidden_size:
+ self.proj = nn.Linear(config.hidden_size, config.output_hidden_size)
+ self.proj_layer_norm = nn.LayerNorm(config.output_hidden_size)
+ else:
+ self.proj = self.proj_layer_norm = None
+
+ self.layers = nn.ModuleList(Data2VecAudioAdapterLayer(config) for _ in range(config.num_adapter_layers))
+ self.layerdrop = config.layerdrop
+
+ def forward(self, hidden_states):
+ # down project hidden_states if necessary
+ if self.proj is not None and self.proj_layer_norm is not None:
+ hidden_states = self.proj(hidden_states)
+ hidden_states = self.proj_layer_norm(hidden_states)
+
+ hidden_states = hidden_states.transpose(1, 2)
+
+ for layer in self.layers:
+ layerdrop_prob = np.random.random()
+ if not self.training or (layerdrop_prob > self.layerdrop):
+ hidden_states = layer(hidden_states)
+
+ hidden_states = hidden_states.transpose(1, 2)
+ return hidden_states
+
+
+@auto_docstring
+class Data2VecAudioPreTrainedModel(PreTrainedModel):
+ config: Data2VecAudioConfig
+ base_model_prefix = "data2vec_audio"
+ main_input_name = "input_values"
+ input_modalities = "audio"
+ supports_gradient_checkpointing = True
+ _supports_flash_attn = True
+ _supports_sdpa = True
+ _supports_flex_attn = True
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ """Initialize the weights"""
+ if isinstance(module, Data2VecAudioFeatureProjection):
+ k = math.sqrt(1 / module.projection.in_features)
+ init.uniform_(module.projection.weight, a=-k, b=k)
+ init.uniform_(module.projection.bias, a=-k, b=k)
+ elif isinstance(module, Data2VecAudioPositionalConvLayer):
+ init.constant_(module.conv.bias, 0)
+ elif isinstance(module, nn.Linear):
+ init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
+
+ if module.bias is not None:
+ init.zeros_(module.bias)
+ elif isinstance(module, (nn.LayerNorm, nn.GroupNorm)):
+ if module.bias is not None:
+ init.zeros_(module.bias)
+ if module.weight is not None:
+ init.ones_(module.weight)
+ elif isinstance(module, nn.Conv1d):
+ init.kaiming_normal_(module.weight)
+
+ if module.bias is not None:
+ k = math.sqrt(module.groups / (module.in_channels * module.kernel_size[0]))
+ init.uniform_(module.bias, a=-k, b=k)
+
+ def _get_feat_extract_output_lengths(self, input_lengths: torch.LongTensor | int, add_adapter: bool | None = None):
+ """
+ Computes the output length of the convolutional layers
+ """
+
+ add_adapter = self.config.add_adapter if add_adapter is None else add_adapter
+
+ def _conv_out_length(input_length, kernel_size, stride):
+ # 1D convolutional layer output length formula taken
+ # from https://pytorch.org/docs/stable/generated/torch.nn.Conv1d.html
+ return torch.div(input_length - kernel_size, stride, rounding_mode="floor") + 1
+
+ for kernel_size, stride in zip(self.config.conv_kernel, self.config.conv_stride):
+ input_lengths = _conv_out_length(input_lengths, kernel_size, stride)
+
+ if add_adapter:
+ for _ in range(self.config.num_adapter_layers):
+ input_lengths = _conv_out_length(input_lengths, 1, self.config.adapter_stride)
+
+ return input_lengths
+
+ def _get_feature_vector_attention_mask(
+ self, feature_vector_length: int, attention_mask: torch.LongTensor, add_adapter=None
+ ):
+ # Effectively attention_mask.sum(-1), but not inplace to be able to run
+ # on inference mode.
+ non_padded_lengths = attention_mask.cumsum(dim=-1)[:, -1]
+
+ output_lengths = self._get_feat_extract_output_lengths(non_padded_lengths, add_adapter=add_adapter)
+ output_lengths = output_lengths.to(torch.long)
+
+ batch_size = attention_mask.shape[0]
+
+ attention_mask = torch.zeros(
+ (batch_size, feature_vector_length), dtype=attention_mask.dtype, device=attention_mask.device
+ )
+ # these two operations makes sure that all values before the output lengths idxs are attended to
+ attention_mask[(torch.arange(attention_mask.shape[0], device=attention_mask.device), output_lengths - 1)] = 1
+ attention_mask = attention_mask.flip([-1]).cumsum(-1).flip([-1]).bool()
+ return attention_mask
+
+
+def _compute_mask_indices(
+ shape: tuple[int, int],
+ mask_prob: float,
+ mask_length: int,
+ attention_mask: torch.LongTensor | None = None,
+ min_masks: int = 0,
+) -> np.ndarray:
+ """
+ Computes random mask spans for a given shape. Used to implement [SpecAugment: A Simple Data Augmentation Method for
+ ASR](https://huggingface.co/papers/1904.08779). Note that this method is not optimized to run on TPU and should be run on
+ CPU as part of the preprocessing during training.
+
+ Args:
+ shape: The shape for which to compute masks. This should be of a tuple of size 2 where
+ the first element is the batch size and the second element is the length of the axis to span.
+ mask_prob: The percentage of the whole axis (between 0 and 1) which will be masked. The number of
+ independently generated mask spans of length `mask_length` is computed by
+ `mask_prob*shape[1]/mask_length`. Note that due to overlaps, `mask_prob` is an upper bound and the
+ actual percentage will be smaller.
+ mask_length: size of the mask
+ min_masks: minimum number of masked spans
+ attention_mask: A (right-padded) attention mask which independently shortens the feature axis of
+ each batch dimension.
+ """
+ batch_size, sequence_length = shape
+
+ if mask_length < 1:
+ raise ValueError("`mask_length` has to be bigger than 0.")
+
+ if mask_length > sequence_length:
+ raise ValueError(
+ f"`mask_length` has to be smaller than `sequence_length`, but got `mask_length`: {mask_length}"
+ f" and `sequence_length`: {sequence_length}`"
+ )
+
+ # epsilon is used for probabilistic rounding
+ epsilon = np.random.rand(1).item()
+
+ def compute_num_masked_span(input_length):
+ """Given input length, compute how many spans should be masked"""
+ num_masked_span = int(mask_prob * input_length / mask_length + epsilon)
+ num_masked_span = max(num_masked_span, min_masks)
+
+ # make sure num masked span <= sequence_length
+ if num_masked_span * mask_length > sequence_length:
+ num_masked_span = sequence_length // mask_length
+
+ # make sure num_masked span is also <= input_length - (mask_length - 1)
+ if input_length - (mask_length - 1) < num_masked_span:
+ num_masked_span = max(input_length - (mask_length - 1), 0)
+
+ return num_masked_span
+
+ # compute number of masked spans in batch
+ input_lengths = (
+ attention_mask.detach().sum(-1).tolist()
+ if attention_mask is not None
+ else [sequence_length for _ in range(batch_size)]
+ )
+
+ # SpecAugment mask to fill
+ spec_aug_mask = np.zeros((batch_size, sequence_length), dtype=bool)
+ spec_aug_mask_idxs = []
+
+ max_num_masked_span = compute_num_masked_span(sequence_length)
+
+ if max_num_masked_span == 0:
+ return spec_aug_mask
+
+ for input_length in input_lengths:
+ # compute num of masked spans for this input
+ num_masked_span = compute_num_masked_span(input_length)
+
+ # get random indices to mask
+ spec_aug_mask_idx = np.random.choice(
+ np.arange(input_length - (mask_length - 1)), num_masked_span, replace=False
+ )
+
+ # pick first sampled index that will serve as a dummy index to pad vector
+ # to ensure same dimension for all batches due to probabilistic rounding
+ # Picking first sample just pads those vectors twice.
+ if len(spec_aug_mask_idx) == 0:
+ # this case can only happen if `input_length` is strictly smaller then
+ # `sequence_length` in which case the last token has to be a padding
+ # token which we can use as a dummy mask id
+ dummy_mask_idx = sequence_length - 1
+ else:
+ dummy_mask_idx = spec_aug_mask_idx[0]
+
+ spec_aug_mask_idx = np.concatenate(
+ [spec_aug_mask_idx, np.ones(max_num_masked_span - num_masked_span, dtype=np.int32) * dummy_mask_idx]
+ )
+ spec_aug_mask_idxs.append(spec_aug_mask_idx)
+
+ spec_aug_mask_idxs = np.array(spec_aug_mask_idxs)
+
+ # expand masked indices to masked spans
+ spec_aug_mask_idxs = np.broadcast_to(
+ spec_aug_mask_idxs[:, :, None], (batch_size, max_num_masked_span, mask_length)
+ )
+ spec_aug_mask_idxs = spec_aug_mask_idxs.reshape(batch_size, max_num_masked_span * mask_length)
+
+ # add offset to the starting indexes so that indexes now create a span
+ offsets = np.arange(mask_length)[None, None, :]
+ offsets = np.broadcast_to(offsets, (batch_size, max_num_masked_span, mask_length)).reshape(
+ batch_size, max_num_masked_span * mask_length
+ )
+ spec_aug_mask_idxs = spec_aug_mask_idxs + offsets
+
+ # ensure that we cannot have indices larger than sequence_length
+ if spec_aug_mask_idxs.max() > sequence_length - 1:
+ spec_aug_mask_idxs[spec_aug_mask_idxs > sequence_length - 1] = sequence_length - 1
+
+ # scatter indices to mask
+ np.put_along_axis(spec_aug_mask, spec_aug_mask_idxs, 1, -1)
+
+ return spec_aug_mask
+
+
+Data2VecAudioBaseModelOutput = Wav2Vec2BaseModelOutput
+
+
+@auto_docstring
+class Data2VecAudioModel(Data2VecAudioPreTrainedModel):
+ def __init__(self, config: Data2VecAudioConfig):
+ super().__init__(config)
+ self.config = config
+ self.feature_extractor = Data2VecAudioFeatureEncoder(config)
+ self.feature_projection = Data2VecAudioFeatureProjection(config)
+
+ # model only needs masking vector if mask prob is > 0.0
+ if config.mask_time_prob > 0.0 or config.mask_feature_prob > 0.0:
+ self.masked_spec_embed = nn.Parameter(torch.Tensor(config.hidden_size).uniform_())
+
+ self.encoder = Data2VecAudioEncoder(config)
+
+ self.adapter = Data2VecAudioAdapter(config) if config.add_adapter else None
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def freeze_feature_encoder(self):
+ """
+ Calling this function will disable the gradient computation for the feature encoder so that its parameter will
+ not be updated during training.
+ """
+ self.feature_extractor._freeze_parameters()
+
+ def _mask_hidden_states(
+ self,
+ hidden_states: torch.FloatTensor,
+ mask_time_indices: torch.FloatTensor | None = None,
+ attention_mask: torch.LongTensor | None = None,
+ ):
+ """
+ Masks extracted features along time axis and/or along feature axis according to
+ [SpecAugment](https://huggingface.co/papers/1904.08779).
+ """
+
+ # `config.apply_spec_augment` can set masking to False
+ if not getattr(self.config, "apply_spec_augment", True):
+ return hidden_states
+
+ # generate indices & apply SpecAugment along time axis
+ batch_size, sequence_length, hidden_size = hidden_states.size()
+
+ if mask_time_indices is not None:
+ # apply SpecAugment along time axis with given mask_time_indices
+ hidden_states[mask_time_indices] = self.masked_spec_embed.to(hidden_states.dtype)
+ elif self.config.mask_time_prob > 0 and self.training:
+ mask_time_indices = _compute_mask_indices(
+ (batch_size, sequence_length),
+ mask_prob=self.config.mask_time_prob,
+ mask_length=self.config.mask_time_length,
+ attention_mask=attention_mask,
+ min_masks=self.config.mask_time_min_masks,
+ )
+ mask_time_indices = torch.tensor(mask_time_indices, device=hidden_states.device, dtype=torch.bool)
+ hidden_states[mask_time_indices] = self.masked_spec_embed.to(hidden_states.dtype)
+
+ if self.config.mask_feature_prob > 0 and self.training:
+ # generate indices & apply SpecAugment along feature axis
+ mask_feature_indices = _compute_mask_indices(
+ (batch_size, hidden_size),
+ mask_prob=self.config.mask_feature_prob,
+ mask_length=self.config.mask_feature_length,
+ min_masks=self.config.mask_feature_min_masks,
+ )
+ mask_feature_indices = torch.tensor(mask_feature_indices, device=hidden_states.device, dtype=torch.bool)
+ mask_feature_indices = mask_feature_indices[:, None].expand(-1, sequence_length, -1)
+ hidden_states[mask_feature_indices] = 0
+
+ return hidden_states
+
+ @auto_docstring
+ def forward(
+ self,
+ input_values: torch.Tensor | None,
+ attention_mask: torch.Tensor | None = None,
+ mask_time_indices: torch.FloatTensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple | Data2VecAudioBaseModelOutput:
+ r"""
+ mask_time_indices (`torch.BoolTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Indices to mask extracted features for contrastive loss. When in training mode, model learns to predict
+ masked extracted features in *config.proj_codevector_dim* space.
+ """
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ extract_features = self.feature_extractor(input_values)
+ extract_features = extract_features.transpose(1, 2)
+
+ if attention_mask is not None:
+ # compute reduced attention_mask corresponding to feature vectors
+ attention_mask = self._get_feature_vector_attention_mask(
+ extract_features.shape[1], attention_mask, add_adapter=False
+ )
+
+ hidden_states, extract_features = self.feature_projection(extract_features)
+ hidden_states = self._mask_hidden_states(
+ hidden_states, mask_time_indices=mask_time_indices, attention_mask=attention_mask
+ )
+
+ encoder_outputs = self.encoder(
+ hidden_states,
+ attention_mask=attention_mask,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ hidden_states = encoder_outputs[0]
+
+ if self.adapter is not None:
+ hidden_states = self.adapter(hidden_states)
+
+ if not return_dict:
+ return (hidden_states, extract_features) + encoder_outputs[1:]
+
+ return Data2VecAudioBaseModelOutput(
+ last_hidden_state=hidden_states,
+ extract_features=extract_features,
+ hidden_states=encoder_outputs.hidden_states,
+ attentions=encoder_outputs.attentions,
+ )
+
+
+_HIDDEN_STATES_START_POSITION = 2
+
+
+@auto_docstring(
+ custom_intro="""
+ Data2VecAudio Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC).
+ """
+)
+class Data2VecAudioForCTC(Data2VecAudioPreTrainedModel):
+ def __init__(self, config):
+ r"""
+ config ([`Data2VecAudioForCTC`]):
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
+ load the weights associated with the model, only the configuration. Check out the
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
+ """
+ super().__init__(config)
+
+ self.data2vec_audio = Data2VecAudioModel(config)
+ self.dropout = nn.Dropout(config.final_dropout)
+
+ if config.vocab_size is None:
+ raise ValueError(
+ f"You are trying to instantiate {self.__class__} with a configuration that "
+ "does not define the vocabulary size of the language model head. Please "
+ "instantiate the model as follows: `Data2VecAudioForCTC.from_pretrained(..., vocab_size=vocab_size)`. "
+ "or define `vocab_size` of your model's configuration."
+ )
+ output_hidden_size = (
+ config.output_hidden_size if hasattr(config, "add_adapter") and config.add_adapter else config.hidden_size
+ )
+ self.lm_head = nn.Linear(output_hidden_size, config.vocab_size)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def freeze_feature_encoder(self):
+ """
+ Calling this function will disable the gradient computation for the feature encoder so that its parameter will
+ not be updated during training.
+ """
+ self.data2vec_audio.feature_extractor._freeze_parameters()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_values: torch.Tensor | None,
+ attention_mask: torch.Tensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ labels: torch.Tensor | None = None,
+ **kwargs,
+ ) -> tuple | CausalLMOutput:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, target_length)`, *optional*):
+ Labels for connectionist temporal classification. Note that `target_length` has to be smaller or equal to
+ the sequence length of the output logits. Indices are selected in `[-100, 0, ..., config.vocab_size - 1]`.
+ All labels set to `-100` are ignored (masked), the loss is only computed for labels in `[0, ...,
+ config.vocab_size - 1]`.
+ """
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ if labels is not None and labels.max() >= self.config.vocab_size:
+ raise ValueError(f"Label values must be <= vocab_size: {self.config.vocab_size}")
+
+ outputs = self.data2vec_audio(
+ input_values,
+ attention_mask=attention_mask,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ hidden_states = outputs[0]
+ hidden_states = self.dropout(hidden_states)
+
+ logits = self.lm_head(hidden_states)
+
+ loss = None
+ if labels is not None:
+ # retrieve loss input_lengths from attention_mask
+ attention_mask = (
+ attention_mask if attention_mask is not None else torch.ones_like(input_values, dtype=torch.long)
+ )
+ input_lengths = self._get_feat_extract_output_lengths(attention_mask.sum(-1)).to(torch.long)
+
+ # assuming that padded tokens are filled with -100
+ # when not being attended to
+ labels_mask = labels >= 0
+ target_lengths = labels_mask.sum(-1)
+ flattened_targets = labels.masked_select(labels_mask)
+
+ # ctc_loss doesn't support fp16
+ log_probs = nn.functional.log_softmax(logits, dim=-1, dtype=torch.float32).transpose(0, 1)
+
+ with torch.backends.cudnn.flags(enabled=False):
+ loss = nn.functional.ctc_loss(
+ log_probs,
+ flattened_targets,
+ input_lengths,
+ target_lengths,
+ blank=self.config.pad_token_id,
+ reduction=self.config.ctc_loss_reduction,
+ zero_infinity=self.config.ctc_zero_infinity,
+ )
+
+ if not return_dict:
+ output = (logits,) + outputs[_HIDDEN_STATES_START_POSITION:]
+ return ((loss,) + output) if loss is not None else output
+
+ return CausalLMOutput(
+ loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ Data2VecAudio Model with a sequence classification head on top (a linear layer over the pooled output) for tasks like
+ SUPERB Keyword Spotting.
+ """
+)
+class Data2VecAudioForSequenceClassification(Data2VecAudioPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ if hasattr(config, "add_adapter") and config.add_adapter:
+ raise ValueError(
+ "Sequence classification does not support the use of Data2VecAudio adapters (config.add_adapter=True)"
+ )
+ self.data2vec_audio = Data2VecAudioModel(config)
+ num_layers = config.num_hidden_layers + 1 # transformer layers + input embeddings
+ if config.use_weighted_layer_sum:
+ self.layer_weights = nn.Parameter(torch.ones(num_layers) / num_layers)
+ self.projector = nn.Linear(config.hidden_size, config.classifier_proj_size)
+ self.classifier = nn.Linear(config.classifier_proj_size, config.num_labels)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def freeze_feature_encoder(self):
+ """
+ Calling this function will disable the gradient computation for the feature encoder so that its parameter will
+ not be updated during training.
+ """
+ self.data2vec_audio.feature_extractor._freeze_parameters()
+
+ def freeze_base_model(self):
+ """
+ Calling this function will disable the gradient computation for the base model so that its parameters will not
+ be updated during training. Only the classification head will be updated.
+ """
+ for param in self.data2vec_audio.parameters():
+ param.requires_grad = False
+
+ @auto_docstring
+ def forward(
+ self,
+ input_values: torch.Tensor | None,
+ attention_mask: torch.Tensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ labels: torch.Tensor | None = None,
+ **kwargs,
+ ) -> tuple | SequenceClassifierOutput:
+ r"""
+ input_values (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
+ Float values of input raw speech waveform. Values can be obtained by loading a `.flac` or `.wav` audio file
+ into an array of type `list[float]`, a `numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library
+ (`pip install torchcodec`) or the soundfile library (`pip install soundfile`).
+ To prepare the array into `input_values`, the [`AutoProcessor`] should be used for padding and conversion
+ into a tensor of type `torch.FloatTensor`. See [`Data2VecAudioProcessor.__call__`] for details.
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+ output_hidden_states = True if self.config.use_weighted_layer_sum else output_hidden_states
+
+ outputs = self.data2vec_audio(
+ input_values,
+ attention_mask=attention_mask,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ if self.config.use_weighted_layer_sum:
+ hidden_states = outputs[_HIDDEN_STATES_START_POSITION]
+ hidden_states = torch.stack(hidden_states, dim=1)
+ norm_weights = nn.functional.softmax(self.layer_weights, dim=-1)
+ hidden_states = (hidden_states * norm_weights.view(-1, 1, 1)).sum(dim=1)
+ else:
+ hidden_states = outputs[0]
+
+ hidden_states = self.projector(hidden_states)
+ if attention_mask is None:
+ pooled_output = hidden_states.mean(dim=1)
+ else:
+ padding_mask = self._get_feature_vector_attention_mask(hidden_states.shape[1], attention_mask)
+ expand_padding_mask = padding_mask.unsqueeze(-1).repeat(1, 1, hidden_states.shape[2])
+ hidden_states[~expand_padding_mask] = 0.0
+ pooled_output = hidden_states.sum(dim=1) / padding_mask.sum(dim=1).view(-1, 1)
+
+ logits = self.classifier(pooled_output)
+
+ loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.config.num_labels), labels.view(-1))
+
+ if not return_dict:
+ output = (logits,) + outputs[_HIDDEN_STATES_START_POSITION:]
+ return ((loss,) + output) if loss is not None else output
+
+ return SequenceClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+class Data2VecAudioForAudioFrameClassification(Data2VecAudioPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ if hasattr(config, "add_adapter") and config.add_adapter:
+ raise ValueError(
+ "Audio frame classification does not support the use of Data2VecAudio adapters (config.add_adapter=True)"
+ )
+ self.data2vec_audio = Data2VecAudioModel(config)
+ num_layers = config.num_hidden_layers + 1 # transformer layers + input embeddings
+ if config.use_weighted_layer_sum:
+ self.layer_weights = nn.Parameter(torch.ones(num_layers) / num_layers)
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
+ self.num_labels = config.num_labels
+
+ self.post_init()
+
+ def freeze_feature_encoder(self):
+ """
+ Calling this function will disable the gradient computation for the feature encoder so that its parameter will
+ not be updated during training.
+ """
+ self.data2vec_audio.feature_extractor._freeze_parameters()
+
+ def freeze_base_model(self):
+ """
+ Calling this function will disable the gradient computation for the base model so that its parameters will not
+ be updated during training. Only the classification head will be updated.
+ """
+ for param in self.data2vec_audio.parameters():
+ param.requires_grad = False
+
+ @auto_docstring
+ def forward(
+ self,
+ input_values: torch.Tensor | None,
+ attention_mask: torch.Tensor | None = None,
+ labels: torch.Tensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple | TokenClassifierOutput:
+ r"""
+ input_values (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
+ Float values of input raw speech waveform. Values can be obtained by loading a `.flac` or `.wav` audio file
+ into an array of type `list[float]`, a `numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library
+ (`pip install torchcodec`) or the soundfile library (`pip install soundfile`).
+ To prepare the array into `input_values`, the [`AutoProcessor`] should be used for padding and conversion
+ into a tensor of type `torch.FloatTensor`. See [`Data2VecAudioProcessor.__call__`] for details.
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+ output_hidden_states = True if self.config.use_weighted_layer_sum else output_hidden_states
+
+ outputs = self.data2vec_audio(
+ input_values,
+ attention_mask=attention_mask,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ if self.config.use_weighted_layer_sum:
+ hidden_states = outputs[_HIDDEN_STATES_START_POSITION]
+ hidden_states = torch.stack(hidden_states, dim=1)
+ norm_weights = nn.functional.softmax(self.layer_weights, dim=-1)
+ hidden_states = (hidden_states * norm_weights.view(-1, 1, 1)).sum(dim=1)
+ else:
+ hidden_states = outputs[0]
+
+ logits = self.classifier(hidden_states)
+
+ loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), torch.argmax(labels.view(-1, self.num_labels), axis=1))
+
+ if not return_dict:
+ output = (logits,) + outputs[_HIDDEN_STATES_START_POSITION:]
+ return output
+
+ return TokenClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+class AMSoftmaxLoss(nn.Module):
+ def __init__(self, input_dim, num_labels, scale=30.0, margin=0.4):
+ super().__init__()
+ self.scale = scale
+ self.margin = margin
+ self.num_labels = num_labels
+ self.weight = nn.Parameter(torch.randn(input_dim, num_labels), requires_grad=True)
+ self.loss = nn.CrossEntropyLoss()
+
+ def forward(self, hidden_states, labels):
+ labels = labels.flatten()
+ weight = nn.functional.normalize(self.weight, dim=0)
+ hidden_states = nn.functional.normalize(hidden_states, dim=1)
+ cos_theta = torch.mm(hidden_states, weight)
+ psi = cos_theta - self.margin
+
+ onehot = nn.functional.one_hot(labels, self.num_labels)
+ logits = self.scale * torch.where(onehot.bool(), psi, cos_theta)
+ loss = self.loss(logits, labels)
+
+ return loss
+
+
+class TDNNLayer(nn.Module):
+ def __init__(self, config, layer_id=0):
+ super().__init__()
+ self.in_conv_dim = config.tdnn_dim[layer_id - 1] if layer_id > 0 else config.tdnn_dim[layer_id]
+ self.out_conv_dim = config.tdnn_dim[layer_id]
+ self.kernel_size = config.tdnn_kernel[layer_id]
+ self.dilation = config.tdnn_dilation[layer_id]
+
+ self.kernel = nn.Linear(self.in_conv_dim * self.kernel_size, self.out_conv_dim)
+ self.activation = nn.ReLU()
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ if is_peft_available():
+ from peft.tuners.lora import LoraLayer
+
+ if is_peft_available():
+ if isinstance(self.kernel, LoraLayer):
+ warnings.warn(
+ "Detected LoRA on TDNNLayer. LoRA weights won't be applied due to optimization. "
+ "You should exclude TDNNLayer from LoRA's target modules.",
+ )
+
+ # for backward compatibility, we keep nn.Linear but call F.conv1d for speed up
+ hidden_states = hidden_states.transpose(1, 2)
+ weight = self.kernel.weight.view(self.out_conv_dim, self.kernel_size, self.in_conv_dim).transpose(1, 2)
+ hidden_states = nn.functional.conv1d(hidden_states, weight, self.kernel.bias, dilation=self.dilation)
+ hidden_states = hidden_states.transpose(1, 2)
+
+ hidden_states = self.activation(hidden_states)
+ return hidden_states
+
+
+@auto_docstring(
+ custom_intro="""
+ Data2VecAudio Model with an XVector feature extraction head on top for tasks like Speaker Verification.
+ """
+)
+class Data2VecAudioForXVector(Data2VecAudioPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.data2vec_audio = Data2VecAudioModel(config)
+ num_layers = config.num_hidden_layers + 1 # transformer layers + input embeddings
+ if config.use_weighted_layer_sum:
+ self.layer_weights = nn.Parameter(torch.ones(num_layers) / num_layers)
+ self.projector = nn.Linear(config.hidden_size, config.tdnn_dim[0])
+
+ tdnn_layers = [TDNNLayer(config, i) for i in range(len(config.tdnn_dim))]
+ self.tdnn = nn.ModuleList(tdnn_layers)
+
+ self.feature_extractor = nn.Linear(config.tdnn_dim[-1] * 2, config.xvector_output_dim)
+ self.classifier = nn.Linear(config.xvector_output_dim, config.xvector_output_dim)
+
+ self.objective = AMSoftmaxLoss(config.xvector_output_dim, config.num_labels)
+
+ self.post_init()
+
+ def freeze_feature_encoder(self):
+ """
+ Calling this function will disable the gradient computation for the feature encoder so that its parameter will
+ not be updated during training.
+ """
+ self.data2vec_audio.feature_extractor._freeze_parameters()
+
+ def freeze_base_model(self):
+ """
+ Calling this function will disable the gradient computation for the base model so that its parameters will not
+ be updated during training. Only the classification head will be updated.
+ """
+ for param in self.data2vec_audio.parameters():
+ param.requires_grad = False
+
+ def _get_tdnn_output_lengths(self, input_lengths: torch.LongTensor | int):
+ """
+ Computes the output length of the TDNN layers
+ """
+
+ def _conv_out_length(input_length, kernel_size, stride):
+ # 1D convolutional layer output length formula taken
+ # from https://pytorch.org/docs/stable/generated/torch.nn.Conv1d.html
+ return (input_length - kernel_size) // stride + 1
+
+ for kernel_size in self.config.tdnn_kernel:
+ input_lengths = _conv_out_length(input_lengths, kernel_size, 1)
+
+ return input_lengths
+
+ @auto_docstring
+ def forward(
+ self,
+ input_values: torch.Tensor | None,
+ attention_mask: torch.Tensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ labels: torch.Tensor | None = None,
+ **kwargs,
+ ) -> tuple | XVectorOutput:
+ r"""
+ input_values (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
+ Float values of input raw speech waveform. Values can be obtained by loading a `.flac` or `.wav` audio file
+ into an array of type `list[float]`, a `numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library
+ (`pip install torchcodec`) or the soundfile library (`pip install soundfile`).
+ To prepare the array into `input_values`, the [`AutoProcessor`] should be used for padding and conversion
+ into a tensor of type `torch.FloatTensor`. See [`Data2VecAudioProcessor.__call__`] for details.
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+ output_hidden_states = True if self.config.use_weighted_layer_sum else output_hidden_states
+
+ outputs = self.data2vec_audio(
+ input_values,
+ attention_mask=attention_mask,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ if self.config.use_weighted_layer_sum:
+ hidden_states = outputs[_HIDDEN_STATES_START_POSITION]
+ hidden_states = torch.stack(hidden_states, dim=1)
+ norm_weights = nn.functional.softmax(self.layer_weights, dim=-1)
+ hidden_states = (hidden_states * norm_weights.view(-1, 1, 1)).sum(dim=1)
+ else:
+ hidden_states = outputs[0]
+
+ hidden_states = self.projector(hidden_states)
+
+ for tdnn_layer in self.tdnn:
+ hidden_states = tdnn_layer(hidden_states)
+
+ # Statistic Pooling
+ if attention_mask is None:
+ mean_features = hidden_states.mean(dim=1)
+ std_features = hidden_states.std(dim=1)
+ else:
+ feat_extract_output_lengths = self._get_feat_extract_output_lengths(attention_mask.sum(dim=1))
+ tdnn_output_lengths = self._get_tdnn_output_lengths(feat_extract_output_lengths)
+ mean_features = []
+ std_features = []
+ for i, length in enumerate(tdnn_output_lengths):
+ mean_features.append(hidden_states[i, :length].mean(dim=0))
+ std_features.append(hidden_states[i, :length].std(dim=0))
+ mean_features = torch.stack(mean_features)
+ std_features = torch.stack(std_features)
+ statistic_pooling = torch.cat([mean_features, std_features], dim=-1)
+
+ output_embeddings = self.feature_extractor(statistic_pooling)
+ logits = self.classifier(output_embeddings)
+
+ loss = None
+ if labels is not None:
+ loss = self.objective(logits, labels)
+
+ if not return_dict:
+ output = (logits, output_embeddings) + outputs[_HIDDEN_STATES_START_POSITION:]
+ return ((loss,) + output) if loss is not None else output
+
+ return XVectorOutput(
+ loss=loss,
+ logits=logits,
+ embeddings=output_embeddings,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+__all__ = [
+ "Data2VecAudioForAudioFrameClassification",
+ "Data2VecAudioForCTC",
+ "Data2VecAudioForSequenceClassification",
+ "Data2VecAudioForXVector",
+ "Data2VecAudioModel",
+ "Data2VecAudioPreTrainedModel",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/data2vec/modeling_data2vec_text.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/data2vec/modeling_data2vec_text.py
new file mode 100644
index 0000000000000000000000000000000000000000..512431cb3b0a293d58d9133875818eaaee5b810a
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/data2vec/modeling_data2vec_text.py
@@ -0,0 +1,1208 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/data2vec/modular_data2vec_text.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_data2vec_text.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2022 The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from collections.abc import Callable
+
+import torch
+import torch.nn as nn
+from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
+
+from ... import initialization as init
+from ...activations import ACT2FN, gelu
+from ...cache_utils import Cache, DynamicCache, EncoderDecoderCache
+from ...generation import GenerationMixin
+from ...masking_utils import create_bidirectional_mask, create_causal_mask
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import (
+ BaseModelOutputWithPastAndCrossAttentions,
+ BaseModelOutputWithPoolingAndCrossAttentions,
+ CausalLMOutputWithCrossAttentions,
+ MaskedLMOutput,
+ MultipleChoiceModelOutput,
+ QuestionAnsweringModelOutput,
+ SequenceClassifierOutput,
+ TokenClassifierOutput,
+)
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
+from ...processing_utils import Unpack
+from ...pytorch_utils import apply_chunking_to_forward
+from ...utils import TransformersKwargs, auto_docstring, logging
+from ...utils.generic import can_return_tuple, merge_with_config_defaults
+from ...utils.output_capturing import capture_outputs
+from .configuration_data2vec_text import Data2VecTextConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+class Data2VecTextEmbeddings(nn.Module):
+ """Construct the embeddings from word, position and token_type embeddings."""
+
+ def __init__(self, config):
+ super().__init__()
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
+ self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
+
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
+ self.register_buffer(
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
+ )
+ self.register_buffer(
+ "token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False
+ )
+
+ self.padding_idx = config.pad_token_id
+ self.position_embeddings = nn.Embedding(
+ config.max_position_embeddings, config.hidden_size, padding_idx=self.padding_idx
+ )
+
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ past_key_values_length: int = 0,
+ ) -> torch.Tensor:
+ if position_ids is None:
+ if input_ids is not None:
+ # Create the position ids from the input token ids. Any padded tokens remain padded.
+ position_ids = self.create_position_ids_from_input_ids(
+ input_ids, self.padding_idx, past_key_values_length
+ )
+ else:
+ position_ids = self.create_position_ids_from_inputs_embeds(inputs_embeds, self.padding_idx)
+
+ if input_ids is not None:
+ input_shape = input_ids.size()
+ else:
+ input_shape = inputs_embeds.size()[:-1]
+
+ batch_size, seq_length = input_shape
+
+ # Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
+ # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
+ # issue #5664
+ if token_type_ids is None:
+ if hasattr(self, "token_type_ids"):
+ # NOTE: We assume either pos ids to have bsz == 1 (broadcastable) or bsz == effective bsz (input_shape[0])
+ buffered_token_type_ids = self.token_type_ids.expand(position_ids.shape[0], -1)
+ buffered_token_type_ids = torch.gather(buffered_token_type_ids, dim=1, index=position_ids)
+ token_type_ids = buffered_token_type_ids.expand(batch_size, seq_length)
+ else:
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
+
+ if inputs_embeds is None:
+ inputs_embeds = self.word_embeddings(input_ids)
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
+ embeddings = inputs_embeds + token_type_embeddings
+
+ position_embeddings = self.position_embeddings(position_ids)
+ embeddings = embeddings + position_embeddings
+
+ embeddings = self.LayerNorm(embeddings)
+ embeddings = self.dropout(embeddings)
+ return embeddings
+
+ @staticmethod
+ def create_position_ids_from_inputs_embeds(inputs_embeds, padding_idx):
+ """
+ We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids.
+
+ Args:
+ inputs_embeds: torch.Tensor
+
+ Returns: torch.Tensor
+ """
+ input_shape = inputs_embeds.size()[:-1]
+ sequence_length = input_shape[1]
+
+ position_ids = torch.arange(
+ padding_idx + 1, sequence_length + padding_idx + 1, dtype=torch.long, device=inputs_embeds.device
+ )
+ return position_ids.unsqueeze(0).expand(input_shape)
+
+ @staticmethod
+ def create_position_ids_from_input_ids(input_ids, padding_idx, past_key_values_length=0):
+ """
+ Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols
+ are ignored. This is modified from fairseq's `utils.make_positions`.
+
+ Args:
+ x: torch.Tensor x:
+
+ Returns: torch.Tensor
+ """
+ # The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA.
+ mask = input_ids.ne(padding_idx).int()
+ incremental_indices = (torch.cumsum(mask, dim=1).type_as(mask) + past_key_values_length) * mask
+ return incremental_indices.long() + padding_idx
+
+
+def eager_attention_forward(
+ module: nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: torch.Tensor | None,
+ scaling: float | None = None,
+ dropout: float = 0.0,
+ **kwargs: Unpack[TransformersKwargs],
+):
+ if scaling is None:
+ scaling = query.size(-1) ** -0.5
+
+ # Take the dot product between "query" and "key" to get the raw attention scores.
+ attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
+
+ if attention_mask is not None:
+ attn_weights = attn_weights + attention_mask
+
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
+
+ attn_output = torch.matmul(attn_weights, value)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+
+ return attn_output, attn_weights
+
+
+class Data2VecTextSelfAttention(nn.Module):
+ def __init__(self, config, is_causal=False, layer_idx=None):
+ super().__init__()
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
+ raise ValueError(
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
+ f"heads ({config.num_attention_heads})"
+ )
+ self.config = config
+
+ self.num_attention_heads = config.num_attention_heads
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
+ self.scaling = self.attention_head_size**-0.5
+
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
+
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
+
+ self.is_decoder = config.is_decoder
+ self.is_causal = is_causal
+ self.layer_idx = layer_idx
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.FloatTensor | None = None,
+ past_key_values: Cache | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor]:
+ input_shape = hidden_states.shape[:-1]
+ hidden_shape = (*input_shape, -1, self.attention_head_size)
+
+ # get all proj
+ query_layer = self.query(hidden_states).view(*hidden_shape).transpose(1, 2)
+ key_layer = self.key(hidden_states).view(*hidden_shape).transpose(1, 2)
+ value_layer = self.value(hidden_states).view(*hidden_shape).transpose(1, 2)
+
+ if past_key_values is not None:
+ # decoder-only data2vec_text can have a simple dynamic cache for example
+ current_past_key_values = past_key_values
+ if isinstance(past_key_values, EncoderDecoderCache):
+ current_past_key_values = past_key_values.self_attention_cache
+
+ # save all key/value_layer to cache to be re-used for fast auto-regressive generation
+ key_layer, value_layer = current_past_key_values.update(key_layer, value_layer, self.layer_idx)
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_layer,
+ key_layer,
+ value_layer,
+ attention_mask,
+ dropout=0.0 if not self.training else self.dropout.p,
+ scaling=self.scaling,
+ **kwargs,
+ )
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ return attn_output, attn_weights
+
+
+class Data2VecTextCrossAttention(nn.Module):
+ def __init__(self, config, is_causal=False, layer_idx=None):
+ super().__init__()
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
+ raise ValueError(
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
+ f"heads ({config.num_attention_heads})"
+ )
+ self.config = config
+
+ self.num_attention_heads = config.num_attention_heads
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
+ self.scaling = self.attention_head_size**-0.5
+
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
+
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
+
+ self.is_causal = is_causal
+ self.layer_idx = layer_idx
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ past_key_values: EncoderDecoderCache | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor]:
+ # determine input shapes
+ input_shape = hidden_states.shape[:-1]
+
+ hidden_shape = (*input_shape, -1, self.attention_head_size)
+
+ # get query proj
+ query_layer = self.query(hidden_states).view(hidden_shape).transpose(1, 2)
+
+ is_updated = past_key_values.is_updated.get(self.layer_idx) if past_key_values is not None else False
+ if past_key_values is not None and is_updated:
+ # reuse k,v, cross_attentions
+ key_layer = past_key_values.cross_attention_cache.layers[self.layer_idx].keys
+ value_layer = past_key_values.cross_attention_cache.layers[self.layer_idx].values
+ else:
+ kv_shape = (*encoder_hidden_states.shape[:-1], -1, self.attention_head_size)
+ key_layer = self.key(encoder_hidden_states).view(kv_shape).transpose(1, 2)
+ value_layer = self.value(encoder_hidden_states).view(kv_shape).transpose(1, 2)
+
+ if past_key_values is not None:
+ # save all states to the cache
+ key_layer, value_layer = past_key_values.cross_attention_cache.update(
+ key_layer, value_layer, self.layer_idx
+ )
+ # set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls
+ past_key_values.is_updated[self.layer_idx] = True
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_layer,
+ key_layer,
+ value_layer,
+ attention_mask,
+ dropout=0.0 if not self.training else self.dropout.p,
+ scaling=self.scaling,
+ **kwargs,
+ )
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ return attn_output, attn_weights
+
+
+class Data2VecTextSelfOutput(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
+ return hidden_states
+
+
+class Data2VecTextAttention(nn.Module):
+ def __init__(self, config, is_causal=False, layer_idx=None, is_cross_attention=False):
+ super().__init__()
+ self.is_cross_attention = is_cross_attention
+ attention_class = Data2VecTextCrossAttention if is_cross_attention else Data2VecTextSelfAttention
+ self.self = attention_class(config, is_causal=is_causal, layer_idx=layer_idx)
+ self.output = Data2VecTextSelfOutput(config)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.FloatTensor | None = None,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ encoder_attention_mask: torch.FloatTensor | None = None,
+ past_key_values: Cache | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor]:
+ attention_mask = attention_mask if not self.is_cross_attention else encoder_attention_mask
+ attention_output, attn_weights = self.self(
+ hidden_states,
+ encoder_hidden_states=encoder_hidden_states,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ **kwargs,
+ )
+ attention_output = self.output(attention_output, hidden_states)
+ return attention_output, attn_weights
+
+
+class Data2VecTextIntermediate(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
+ if isinstance(config.hidden_act, str):
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
+ else:
+ self.intermediate_act_fn = config.hidden_act
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.intermediate_act_fn(hidden_states)
+ return hidden_states
+
+
+class Data2VecTextOutput(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
+ return hidden_states
+
+
+class Data2VecTextLayer(GradientCheckpointingLayer):
+ def __init__(self, config, layer_idx=None):
+ super().__init__()
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
+ self.seq_len_dim = 1
+ self.attention = Data2VecTextAttention(config, is_causal=config.is_decoder, layer_idx=layer_idx)
+ self.is_decoder = config.is_decoder
+ self.add_cross_attention = config.add_cross_attention
+ if self.add_cross_attention:
+ if not self.is_decoder:
+ raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
+ self.crossattention = Data2VecTextAttention(
+ config,
+ is_causal=False,
+ layer_idx=layer_idx,
+ is_cross_attention=True,
+ )
+ self.intermediate = Data2VecTextIntermediate(config)
+ self.output = Data2VecTextOutput(config)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.FloatTensor | None = None,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ encoder_attention_mask: torch.FloatTensor | None = None,
+ past_key_values: Cache | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.Tensor:
+ self_attention_output, _ = self.attention(
+ hidden_states,
+ attention_mask,
+ past_key_values=past_key_values,
+ **kwargs,
+ )
+ attention_output = self_attention_output
+
+ if self.is_decoder and encoder_hidden_states is not None:
+ if not hasattr(self, "crossattention"):
+ raise ValueError(
+ f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
+ " by setting `config.add_cross_attention=True`"
+ )
+
+ cross_attention_output, _ = self.crossattention(
+ self_attention_output,
+ None, # attention_mask
+ encoder_hidden_states,
+ encoder_attention_mask,
+ past_key_values=past_key_values,
+ **kwargs,
+ )
+ attention_output = cross_attention_output
+
+ layer_output = apply_chunking_to_forward(
+ self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
+ )
+ return layer_output
+
+ def feed_forward_chunk(self, attention_output):
+ intermediate_output = self.intermediate(attention_output)
+ layer_output = self.output(intermediate_output, attention_output)
+ return layer_output
+
+
+@auto_docstring
+class Data2VecTextPreTrainedModel(PreTrainedModel):
+ config_class = Data2VecTextConfig
+ base_model_prefix = "data2vec_text"
+ supports_gradient_checkpointing = True
+ _no_split_modules = ["Data2VecTextForTextEmbeddings", "Data2VecTextLayer"]
+ _supports_flash_attn = True
+ _supports_sdpa = True
+ _supports_flex_attn = True
+ _supports_attention_backend = True
+ _can_record_outputs = {
+ "hidden_states": Data2VecTextLayer,
+ "attentions": Data2VecTextSelfAttention,
+ "cross_attentions": Data2VecTextCrossAttention,
+ }
+
+ def _init_weights(self, module):
+ super()._init_weights(module)
+ if isinstance(module, Data2VecTextEmbeddings):
+ init.copy_(module.position_ids, torch.arange(module.position_ids.shape[-1]).expand((1, -1)))
+ init.zeros_(module.token_type_ids)
+
+
+class Data2VecTextEncoder(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.layer = nn.ModuleList([Data2VecTextLayer(config, layer_idx=i) for i in range(config.num_hidden_layers)])
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.FloatTensor | None = None,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ encoder_attention_mask: torch.FloatTensor | None = None,
+ past_key_values: Cache | None = None,
+ use_cache: bool | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | BaseModelOutputWithPastAndCrossAttentions:
+ for i, layer_module in enumerate(self.layer):
+ hidden_states = layer_module(
+ hidden_states,
+ attention_mask,
+ encoder_hidden_states, # as a positional argument for gradient checkpointing
+ encoder_attention_mask=encoder_attention_mask,
+ past_key_values=past_key_values,
+ **kwargs,
+ )
+
+ return BaseModelOutputWithPastAndCrossAttentions(
+ last_hidden_state=hidden_states,
+ past_key_values=past_key_values if use_cache else None,
+ )
+
+
+class Data2VecTextPooler(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.activation = nn.Tanh()
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ # We "pool" the model by simply taking the hidden state corresponding
+ # to the first token.
+ first_token_tensor = hidden_states[:, 0]
+ pooled_output = self.dense(first_token_tensor)
+ pooled_output = self.activation(pooled_output)
+ return pooled_output
+
+
+@auto_docstring
+class Data2VecTextModel(Data2VecTextPreTrainedModel):
+ _no_split_modules = ["Data2VecTextEmbeddings", "Data2VecTextLayer"]
+
+ def __init__(self, config, add_pooling_layer=True):
+ r"""
+ add_pooling_layer (bool, *optional*, defaults to `True`):
+ Whether to add a pooling layer
+ """
+ super().__init__(config)
+ self.config = config
+ self.gradient_checkpointing = False
+
+ self.embeddings = Data2VecTextEmbeddings(config)
+ self.encoder = Data2VecTextEncoder(config)
+
+ self.pooler = Data2VecTextPooler(config) if add_pooling_layer else None
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.embeddings.word_embeddings
+
+ def set_input_embeddings(self, value):
+ self.embeddings.word_embeddings = value
+
+ @merge_with_config_defaults
+ @capture_outputs
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ token_type_ids: torch.Tensor | None = None,
+ position_ids: torch.Tensor | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ encoder_hidden_states: torch.Tensor | None = None,
+ encoder_attention_mask: torch.Tensor | None = None,
+ past_key_values: Cache | None = None,
+ use_cache: bool | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | BaseModelOutputWithPoolingAndCrossAttentions:
+ if (input_ids is None) ^ (inputs_embeds is not None):
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
+
+ if self.config.is_decoder:
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
+ else:
+ use_cache = False
+
+ if use_cache and past_key_values is None:
+ past_key_values = (
+ EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache(config=self.config))
+ if encoder_hidden_states is not None or self.config.is_encoder_decoder
+ else DynamicCache(config=self.config)
+ )
+
+ past_key_values_length = past_key_values.get_seq_length() if past_key_values is not None else 0
+
+ embedding_output = self.embeddings(
+ input_ids=input_ids,
+ position_ids=position_ids,
+ token_type_ids=token_type_ids,
+ inputs_embeds=inputs_embeds,
+ past_key_values_length=past_key_values_length,
+ )
+
+ attention_mask, encoder_attention_mask = self._create_attention_masks(
+ attention_mask=attention_mask,
+ encoder_attention_mask=encoder_attention_mask,
+ embedding_output=embedding_output,
+ encoder_hidden_states=encoder_hidden_states,
+ past_key_values=past_key_values,
+ )
+
+ encoder_outputs = self.encoder(
+ embedding_output,
+ attention_mask=attention_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ position_ids=position_ids,
+ **kwargs,
+ )
+ sequence_output = encoder_outputs.last_hidden_state
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
+
+ return BaseModelOutputWithPoolingAndCrossAttentions(
+ last_hidden_state=sequence_output,
+ pooler_output=pooled_output,
+ past_key_values=encoder_outputs.past_key_values,
+ )
+
+ def _create_attention_masks(
+ self,
+ attention_mask,
+ encoder_attention_mask,
+ embedding_output,
+ encoder_hidden_states,
+ past_key_values,
+ ):
+ if self.config.is_decoder:
+ attention_mask = create_causal_mask(
+ config=self.config,
+ inputs_embeds=embedding_output,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ )
+ else:
+ attention_mask = create_bidirectional_mask(
+ config=self.config,
+ inputs_embeds=embedding_output,
+ attention_mask=attention_mask,
+ )
+
+ if encoder_attention_mask is not None:
+ encoder_attention_mask = create_bidirectional_mask(
+ config=self.config,
+ inputs_embeds=embedding_output,
+ attention_mask=encoder_attention_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ )
+
+ return attention_mask, encoder_attention_mask
+
+
+class Data2VecTextLMHead(nn.Module):
+ """Data2VecText Head for masked language modeling."""
+
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size)
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
+
+ def forward(self, features, **kwargs):
+ x = self.dense(features)
+ x = gelu(x)
+ x = self.layer_norm(x)
+
+ # project back to size of vocabulary with bias
+ x = self.decoder(x)
+
+ return x
+
+
+class Data2VecTextClassificationHead(nn.Module):
+ """Head for sentence-level classification tasks."""
+
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ classifier_dropout = (
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
+ )
+ self.dropout = nn.Dropout(classifier_dropout)
+ self.out_proj = nn.Linear(config.hidden_size, config.num_labels)
+
+ def forward(self, features, **kwargs):
+ x = features[:, 0, :] # take token (equiv. to [CLS])
+ x = self.dropout(x)
+ x = self.dense(x)
+ x = torch.tanh(x)
+ x = self.dropout(x)
+ x = self.out_proj(x)
+ return x
+
+
+@auto_docstring(
+ custom_intro="""
+ Data2VecText Model with a `language modeling` head on top for CLM fine-tuning.
+ """
+)
+class Data2VecTextForCausalLM(Data2VecTextPreTrainedModel, GenerationMixin):
+ _tied_weights_keys = {
+ "lm_head.decoder.weight": "data2vec_text.embeddings.word_embeddings.weight",
+ "lm_head.decoder.bias": "lm_head.bias",
+ }
+
+ def __init__(self, config):
+ super().__init__(config)
+
+ if not config.is_decoder:
+ logger.warning("If you want to use `Data2VecTextLMHeadModel` as a standalone, add `is_decoder=True.`")
+
+ self.data2vec_text = Data2VecTextModel(config, add_pooling_layer=False)
+ self.lm_head = Data2VecTextLMHead(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_output_embeddings(self):
+ return self.lm_head.decoder
+
+ def set_output_embeddings(self, new_embeddings):
+ self.lm_head.decoder = new_embeddings
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ encoder_attention_mask: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ past_key_values: tuple[tuple[torch.FloatTensor]] | None = None,
+ use_cache: bool | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | CausalLMOutputWithCrossAttentions:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
+ `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
+ ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
+
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, Data2VecTextForCausalLM, Data2VecTextConfig
+ >>> import torch
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("facebook/data2vec-text-base")
+ >>> config = Data2VecTextConfig.from_pretrained("facebook/data2vec-text-base")
+ >>> config.is_decoder = True
+ >>> model = Data2VecTextForCausalLM.from_pretrained("facebook/data2vec-text-base", config=config)
+
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
+ >>> outputs = model(**inputs)
+
+ >>> prediction_logits = outputs.logits
+ ```"""
+ if labels is not None:
+ use_cache = False
+
+ outputs: BaseModelOutputWithPoolingAndCrossAttentions = self.data2vec_text(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ return_dict=True,
+ **kwargs,
+ )
+
+ hidden_states = outputs.last_hidden_state
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
+
+ return CausalLMOutputWithCrossAttentions(
+ loss=loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ cross_attentions=outputs.cross_attentions,
+ )
+
+
+@auto_docstring
+class Data2VecTextForMaskedLM(Data2VecTextPreTrainedModel):
+ _tied_weights_keys = {
+ "lm_head.decoder.weight": "data2vec_text.embeddings.word_embeddings.weight",
+ "lm_head.decoder.bias": "lm_head.bias",
+ }
+
+ def __init__(self, config):
+ super().__init__(config)
+
+ if config.is_decoder:
+ logger.warning(
+ "If you want to use `Data2VecTextForMaskedLM` make sure `config.is_decoder=False` for "
+ "bi-directional self-attention."
+ )
+
+ self.data2vec_text = Data2VecTextModel(config, add_pooling_layer=False)
+ self.lm_head = Data2VecTextLMHead(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_output_embeddings(self):
+ return self.lm_head.decoder
+
+ def set_output_embeddings(self, new_embeddings):
+ self.lm_head.decoder = new_embeddings
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ encoder_attention_mask: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | MaskedLMOutput:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
+ """
+ outputs = self.data2vec_text(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ return_dict=True,
+ **kwargs,
+ )
+ sequence_output = outputs[0]
+ prediction_scores = self.lm_head(sequence_output)
+
+ masked_lm_loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+
+ labels = labels.to(prediction_scores.device)
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
+
+ return MaskedLMOutput(
+ loss=masked_lm_loss,
+ logits=prediction_scores,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ Data2VecText Model transformer with a sequence classification/regression head on top (a linear layer on top of the
+ pooled output) e.g. for GLUE tasks.
+ """
+)
+class Data2VecTextForSequenceClassification(Data2VecTextPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+ self.config = config
+
+ self.data2vec_text = Data2VecTextModel(config, add_pooling_layer=False)
+ self.classifier = Data2VecTextClassificationHead(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | SequenceClassifierOutput:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+ outputs = self.data2vec_text(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ return_dict=True,
+ **kwargs,
+ )
+ sequence_output = outputs[0]
+ logits = self.classifier(sequence_output)
+
+ loss = None
+ if labels is not None:
+ labels = labels.to(logits.device)
+
+ if self.config.problem_type is None:
+ if self.num_labels == 1:
+ self.config.problem_type = "regression"
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
+ self.config.problem_type = "single_label_classification"
+ else:
+ self.config.problem_type = "multi_label_classification"
+
+ if self.config.problem_type == "regression":
+ loss_fct = MSELoss()
+ if self.num_labels == 1:
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
+ else:
+ loss = loss_fct(logits, labels)
+ elif self.config.problem_type == "single_label_classification":
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+ elif self.config.problem_type == "multi_label_classification":
+ loss_fct = BCEWithLogitsLoss()
+ loss = loss_fct(logits, labels)
+
+ return SequenceClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+class Data2VecTextForMultipleChoice(Data2VecTextPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.data2vec_text = Data2VecTextModel(config)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+ self.classifier = nn.Linear(config.hidden_size, 1)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | MultipleChoiceModelOutput:
+ r"""
+ input_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input-ids)
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
+ 1]`:
+
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
+ num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
+ `input_ids` above)
+ position_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
+ config.max_position_embeddings - 1]`.
+
+ [What are position IDs?](../glossary#position-ids)
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_choices, sequence_length, hidden_size)`, *optional*):
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
+ model's internal embedding lookup matrix.
+ """
+ num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
+
+ flat_input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
+ flat_position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
+ flat_token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
+ flat_attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
+ flat_inputs_embeds = (
+ inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
+ if inputs_embeds is not None
+ else None
+ )
+
+ outputs = self.data2vec_text(
+ flat_input_ids,
+ position_ids=flat_position_ids,
+ token_type_ids=flat_token_type_ids,
+ attention_mask=flat_attention_mask,
+ inputs_embeds=flat_inputs_embeds,
+ return_dict=True,
+ **kwargs,
+ )
+ pooled_output = outputs[1]
+
+ pooled_output = self.dropout(pooled_output)
+ logits = self.classifier(pooled_output)
+ reshaped_logits = logits.view(-1, num_choices)
+
+ loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+
+ labels = labels.to(reshaped_logits.device)
+ loss = loss_fct(reshaped_logits, labels)
+
+ return MultipleChoiceModelOutput(
+ loss=loss,
+ logits=reshaped_logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+class Data2VecTextForTokenClassification(Data2VecTextPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+
+ self.data2vec_text = Data2VecTextModel(config, add_pooling_layer=False)
+ classifier_dropout = (
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
+ )
+ self.dropout = nn.Dropout(classifier_dropout)
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | TokenClassifierOutput:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
+ """
+ outputs = self.data2vec_text(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ return_dict=True,
+ **kwargs,
+ )
+
+ sequence_output = outputs[0]
+
+ sequence_output = self.dropout(sequence_output)
+ logits = self.classifier(sequence_output)
+
+ loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+
+ labels = labels.to(logits.device)
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+
+ return TokenClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+class Data2VecTextForQuestionAnswering(Data2VecTextPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+
+ self.data2vec_text = Data2VecTextModel(config, add_pooling_layer=False)
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ start_positions: torch.LongTensor | None = None,
+ end_positions: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | QuestionAnsweringModelOutput:
+ outputs = self.data2vec_text(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ return_dict=True,
+ **kwargs,
+ )
+
+ sequence_output = outputs[0]
+
+ logits = self.qa_outputs(sequence_output)
+ start_logits, end_logits = logits.split(1, dim=-1)
+ start_logits = start_logits.squeeze(-1).contiguous()
+ end_logits = end_logits.squeeze(-1).contiguous()
+
+ total_loss = None
+ if start_positions is not None and end_positions is not None:
+ # If we are on multi-GPU, split add a dimension
+ if len(start_positions.size()) > 1:
+ start_positions = start_positions.squeeze(-1)
+ if len(end_positions.size()) > 1:
+ end_positions = end_positions.squeeze(-1)
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
+ ignored_index = start_logits.size(1)
+ start_positions = start_positions.clamp(0, ignored_index)
+ end_positions = end_positions.clamp(0, ignored_index)
+
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
+ start_loss = loss_fct(start_logits, start_positions)
+ end_loss = loss_fct(end_logits, end_positions)
+ total_loss = (start_loss + end_loss) / 2
+
+ return QuestionAnsweringModelOutput(
+ loss=total_loss,
+ start_logits=start_logits,
+ end_logits=end_logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+__all__ = [
+ "Data2VecTextForCausalLM",
+ "Data2VecTextForMaskedLM",
+ "Data2VecTextForMultipleChoice",
+ "Data2VecTextForQuestionAnswering",
+ "Data2VecTextForSequenceClassification",
+ "Data2VecTextForTokenClassification",
+ "Data2VecTextModel",
+ "Data2VecTextPreTrainedModel",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/data2vec/modeling_data2vec_vision.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/data2vec/modeling_data2vec_vision.py
new file mode 100644
index 0000000000000000000000000000000000000000..b8d8d7721c591dd661c2f1ec743a908696531222
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/data2vec/modeling_data2vec_vision.py
@@ -0,0 +1,1214 @@
+# Copyright 2022 Meta Platforms and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch Data2VecVision model."""
+
+import collections.abc
+import math
+from dataclasses import dataclass
+from typing import Optional
+
+import torch
+from torch import nn
+from torch.nn import CrossEntropyLoss
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import (
+ BaseModelOutput,
+ BaseModelOutputWithPooling,
+ ImageClassifierOutput,
+ SemanticSegmenterOutput,
+)
+from ...modeling_utils import PreTrainedModel
+from ...pytorch_utils import compile_compatible_method_lru_cache
+from ...utils import auto_docstring, logging, torch_int
+from .configuration_data2vec_vision import Data2VecVisionConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+@auto_docstring(
+ custom_intro="""
+ Class for outputs of [`Data2VecVisionModel`].
+ """
+)
+@dataclass
+# Copied from transformers.models.beit.modeling_beit.BeitModelOutputWithPooling with Beit->Data2VecVision
+class Data2VecVisionModelOutputWithPooling(BaseModelOutputWithPooling):
+ r"""
+ pooler_output (`torch.FloatTensor` of shape `(batch_size, hidden_size)`):
+ Average of the last layer hidden states of the patch tokens (excluding the *[CLS]* token) if
+ *config.use_mean_pooling* is set to True. If set to False, then the final hidden state of the *[CLS]* token
+ will be returned.
+ """
+
+
+# Todo - Refactor as part of vision refactor. Copied from transformers.models.beit.modeling_beit.BeitEmbeddings with Beit->Data2VecVision
+class Data2VecVisionEmbeddings(nn.Module):
+ """
+ Construct the CLS token, position and patch embeddings. Optionally, also the mask token.
+
+ """
+
+ def __init__(self, config: Data2VecVisionConfig) -> None:
+ super().__init__()
+
+ self.cls_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
+ if config.use_mask_token:
+ self.mask_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
+ else:
+ self.mask_token = None
+ self.patch_embeddings = Data2VecVisionPatchEmbeddings(config)
+ self.patch_size = config.patch_size
+ self.image_size = (
+ config.image_size
+ if isinstance(config.image_size, collections.abc.Iterable)
+ else (config.image_size, config.image_size)
+ )
+ num_patches = self.patch_embeddings.num_patches
+ if config.use_absolute_position_embeddings:
+ self.position_embeddings = nn.Parameter(torch.zeros(1, num_patches + 1, config.hidden_size))
+ else:
+ self.position_embeddings = None
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ # Copied from transformers.models.vit.modeling_vit.ViTEmbeddings.interpolate_pos_encoding
+ def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor:
+ """
+ This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher resolution
+ images. This method is also adapted to support torch.jit tracing.
+
+ Adapted from:
+ - https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174-L194, and
+ - https://github.com/facebookresearch/dinov2/blob/e1277af2ba9496fbadf7aec6eba56e8d882d1e35/dinov2/models/vision_transformer.py#L179-L211
+ """
+
+ num_patches = embeddings.shape[1] - 1
+ num_positions = self.position_embeddings.shape[1] - 1
+
+ # always interpolate when tracing to ensure the exported model works for dynamic input shapes
+ if not torch.jit.is_tracing() and num_patches == num_positions and height == width:
+ return self.position_embeddings
+
+ class_pos_embed = self.position_embeddings[:, :1]
+ patch_pos_embed = self.position_embeddings[:, 1:]
+
+ dim = embeddings.shape[-1]
+
+ new_height = height // self.patch_size
+ new_width = width // self.patch_size
+
+ sqrt_num_positions = torch_int(num_positions**0.5)
+ patch_pos_embed = patch_pos_embed.reshape(1, sqrt_num_positions, sqrt_num_positions, dim)
+ patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2)
+
+ patch_pos_embed = nn.functional.interpolate(
+ patch_pos_embed,
+ size=(new_height, new_width),
+ mode="bicubic",
+ align_corners=False,
+ )
+
+ patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
+
+ return torch.cat((class_pos_embed, patch_pos_embed), dim=1)
+
+ def forward(
+ self,
+ pixel_values: torch.Tensor,
+ bool_masked_pos: torch.BoolTensor | None = None,
+ ) -> torch.Tensor:
+ _, _, height, width = pixel_values.shape
+ embeddings, (patch_height, patch_width) = self.patch_embeddings(pixel_values)
+ batch_size, seq_len, _ = embeddings.size()
+
+ if bool_masked_pos is not None:
+ mask_tokens = self.mask_token.expand(batch_size, seq_len, -1)
+ # replace the masked visual tokens by mask_tokens
+ w = bool_masked_pos.unsqueeze(-1).type_as(mask_tokens)
+ embeddings = embeddings * (1 - w) + mask_tokens * w
+
+ cls_tokens = self.cls_token.expand(batch_size, -1, -1)
+ embeddings = torch.cat((cls_tokens, embeddings), dim=1)
+
+ if self.position_embeddings is not None:
+ embeddings = embeddings + self.interpolate_pos_encoding(embeddings, height, width)
+
+ embeddings = self.dropout(embeddings)
+
+ return embeddings, (patch_height, patch_width)
+
+
+# Todo - Refactor as part of vision refactor. Copied from transformers.models.beit.modeling_beit.BeitPatchEmbeddings with Beit->Data2VecVision
+class Data2VecVisionPatchEmbeddings(nn.Module):
+ """
+ This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
+ `hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
+ Transformer.
+ """
+
+ def __init__(self, config):
+ super().__init__()
+ image_size, patch_size = config.image_size, config.patch_size
+ num_channels, hidden_size = config.num_channels, config.hidden_size
+
+ image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
+ patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
+ num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
+ patch_shape = (image_size[0] // patch_size[0], image_size[1] // patch_size[1])
+ self.image_size = image_size
+ self.patch_size = patch_size
+ self.num_channels = num_channels
+ self.num_patches = num_patches
+ self.patch_shape = patch_shape
+
+ self.projection = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=patch_size)
+
+ def forward(self, pixel_values: torch.Tensor) -> torch.Tensor:
+ batch_size, num_channels, height, width = pixel_values.shape
+ if num_channels != self.num_channels:
+ raise ValueError(
+ "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
+ )
+
+ embeddings = self.projection(pixel_values.to(self.projection.weight.dtype))
+ patch_height, patch_width = embeddings.shape[2], embeddings.shape[3]
+ embeddings = embeddings.flatten(2).transpose(1, 2)
+
+ return embeddings, (patch_height, patch_width)
+
+
+# Todo - Refactor as part of vision refactor. Copied from transformers.models.beit.modeling_beit.BeitSelfAttention with Beit->Data2VecVision
+class Data2VecVisionSelfAttention(nn.Module):
+ def __init__(self, config: Data2VecVisionConfig, window_size: tuple | None = None) -> None:
+ super().__init__()
+ self.config = config
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
+ raise ValueError(
+ f"The hidden size {config.hidden_size} is not a multiple of the number of attention "
+ f"heads {config.num_attention_heads}."
+ )
+
+ self.num_attention_heads = config.num_attention_heads
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
+
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
+ self.key = nn.Linear(config.hidden_size, self.all_head_size, bias=False)
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
+
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
+
+ self.has_relative_position_bias = bool(window_size)
+ if self.has_relative_position_bias:
+ self.relative_position_bias = Data2VecVisionRelativePositionBias(config, window_size=window_size)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ output_attentions: bool = False,
+ relative_position_bias: torch.Tensor | None = None,
+ interpolate_pos_encoding: bool = False,
+ resolution: tuple[int] | None = None,
+ ) -> tuple[torch.Tensor] | tuple[torch.Tensor, torch.Tensor]:
+ input_shape = hidden_states.shape[:-1]
+ hidden_shape = (*input_shape, -1, self.attention_head_size)
+ query_layer = self.query(hidden_states).view(hidden_shape).transpose(1, 2)
+ key_layer = self.key(hidden_states).view(hidden_shape).transpose(1, 2)
+ value_layer = self.value(hidden_states).view(hidden_shape).transpose(1, 2)
+
+ # Take the dot product between "query" and "key" to get the raw attention scores.
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
+
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
+
+ # Add relative position bias if present.
+ if self.has_relative_position_bias:
+ height, width = resolution
+ window_size = (height // self.config.patch_size, width // self.config.patch_size)
+ attention_scores = attention_scores + self.relative_position_bias(
+ window_size, interpolate_pos_encoding, dim_size=hidden_states.shape[1]
+ )
+
+ # Add shared relative position bias if provided.
+ if relative_position_bias is not None:
+ attention_scores = attention_scores + relative_position_bias
+
+ # Normalize the attention scores to probabilities.
+ attention_probs = nn.functional.softmax(attention_scores, dim=-1)
+
+ # This is actually dropping out entire tokens to attend to, which might
+ # seem a bit unusual, but is taken from the original Transformer paper.
+ attention_probs = self.dropout(attention_probs)
+
+ context_layer = torch.matmul(attention_probs, value_layer)
+
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
+ context_layer = context_layer.view(*new_context_layer_shape)
+
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
+
+ return outputs
+
+
+# Todo - Refactor as part of vision refactor. Copied from transformers.models.beit.modeling_beit.BeitSdpaSelfAttention with Beit->Data2VecVision
+class Data2VecVisionSdpaSelfAttention(Data2VecVisionSelfAttention):
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ output_attentions: bool = False,
+ relative_position_bias: torch.Tensor | None = None,
+ interpolate_pos_encoding: bool = False,
+ resolution: tuple[int] | None = None,
+ ) -> tuple[torch.Tensor] | tuple[torch.Tensor, torch.Tensor]:
+ if output_attentions:
+ logger.warning_once(
+ f"{self.__class__.__name__} does not support `output_attentions=True`. The returned attention weights will "
+ "be `None`. If you want to get attention weights, please set `attn_implementation='eager'` when loading the model."
+ )
+ input_shape = hidden_states.shape[:-1]
+ hidden_shape = (*input_shape, -1, self.attention_head_size)
+ query_layer = self.query(hidden_states).view(hidden_shape).transpose(1, 2)
+ key_layer = self.key(hidden_states).view(hidden_shape).transpose(1, 2)
+ value_layer = self.value(hidden_states).view(hidden_shape).transpose(1, 2)
+
+ attn_bias = None
+ if self.has_relative_position_bias:
+ height, width = resolution
+ window_size = (height // self.config.patch_size, width // self.config.patch_size)
+ attn_bias = self.relative_position_bias(
+ window_size, interpolate_pos_encoding, dim_size=hidden_states.shape[1]
+ )
+
+ # Add shared relative position bias if provided.
+ if relative_position_bias is not None:
+ if attn_bias is None:
+ attn_bias = relative_position_bias
+ else:
+ attn_bias += relative_position_bias
+
+ scaling = 1 / math.sqrt(self.attention_head_size)
+ context_layer = torch.nn.functional.scaled_dot_product_attention(
+ query_layer,
+ key_layer,
+ value_layer,
+ attn_mask=attn_bias,
+ dropout_p=self.config.attention_probs_dropout_prob if self.training else 0.0,
+ is_causal=False,
+ scale=scaling,
+ )
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
+ context_layer = context_layer.view(*new_context_layer_shape)
+ return context_layer, None
+
+
+# Todo - Refactor as part of vision refactor. Copied from transformers.models.beit.modeling_beit.BeitSelfOutput with Beit->Data2VecVision
+class Data2VecVisionSelfOutput(nn.Module):
+ """
+ The residual connection is defined in Data2VecVisionLayer instead of here (as is the case with other models), due to the
+ layernorm applied before each block.
+ """
+
+ def __init__(self, config: Data2VecVisionConfig) -> None:
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor, gamma=None) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+
+ return hidden_states
+
+
+DATA2VEC_VISION_SELF_ATTENTION_CLASSES = {
+ "eager": Data2VecVisionSelfAttention,
+ "sdpa": Data2VecVisionSdpaSelfAttention,
+}
+
+
+# Copied from tests.models.beit.modeling_beit.BeitAttention with Beit->Data2VecVision, BEIT->DATA2VEC_VISION
+class Data2VecVisionAttention(nn.Module):
+ def __init__(self, config: Data2VecVisionConfig, window_size: tuple | None = None) -> None:
+ super().__init__()
+ self.attention = DATA2VEC_VISION_SELF_ATTENTION_CLASSES[config._attn_implementation](
+ config, window_size=window_size
+ )
+ self.output = Data2VecVisionSelfOutput(config)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ output_attentions: bool = False,
+ relative_position_bias: Optional["Data2VecVisionRelativePositionBias"] = None,
+ interpolate_pos_encoding: bool = False,
+ resolution: tuple[int] | None = None,
+ ) -> tuple[torch.Tensor] | tuple[torch.Tensor, torch.Tensor]:
+ self_outputs = self.attention(
+ hidden_states, output_attentions, relative_position_bias, interpolate_pos_encoding, resolution
+ )
+
+ attention_output = self.output(self_outputs[0], hidden_states)
+
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
+ return outputs
+
+
+# Todo - Refactor as part of vision refactor. Copied from transformers.models.beit.modeling_beit.BeitIntermediate with Beit->Data2VecVision
+class Data2VecVisionIntermediate(nn.Module):
+ def __init__(self, config: Data2VecVisionConfig) -> None:
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
+ if isinstance(config.hidden_act, str):
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
+ else:
+ self.intermediate_act_fn = config.hidden_act
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.intermediate_act_fn(hidden_states)
+
+ return hidden_states
+
+
+# Todo - Refactor as part of vision refactor. Copied from transformers.models.beit.modeling_beit.BeitOutput with Beit->Data2VecVision
+class Data2VecVisionOutput(nn.Module):
+ def __init__(self, config: Data2VecVisionConfig) -> None:
+ super().__init__()
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+
+ return hidden_states
+
+
+# Copied from transformers.models.swin.modular_swin.SwinDropPath with SwinDropPath->Data2VecVisionDropPath
+class Data2VecVisionDropPath(nn.Module):
+ """Stochastic depth (DropPath) per sample, for residual blocks.
+
+ Identity when ``drop_prob`` is 0 or outside training. See `Deep Networks with Stochastic Depth
+ `_.
+ """
+
+ def __init__(self, drop_prob: float = 0.0) -> None:
+ super().__init__()
+ self.drop_prob = drop_prob
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ if self.drop_prob == 0.0 or not self.training:
+ return hidden_states
+ keep_prob = 1 - self.drop_prob
+ shape = (hidden_states.shape[0],) + (1,) * (hidden_states.ndim - 1)
+ random_tensor = torch.rand(shape, dtype=hidden_states.dtype, device=hidden_states.device)
+ random_tensor = torch.floor(random_tensor + keep_prob)
+ return hidden_states.div(keep_prob) * random_tensor
+
+ def extra_repr(self) -> str:
+ return f"p={self.drop_prob}"
+
+
+# Todo - Refactor as part of vision refactor. Copied from transformers.models.beit.modeling_beit.BeitLayer with Beit->Data2VecVision,BEiT->Data2VecVision
+class Data2VecVisionLayer(GradientCheckpointingLayer):
+ """This corresponds to the Block class in the timm implementation."""
+
+ def __init__(
+ self, config: Data2VecVisionConfig, window_size: tuple | None = None, drop_path_rate: float = 0.0
+ ) -> None:
+ super().__init__()
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
+ self.seq_len_dim = 1
+ self.attention = Data2VecVisionAttention(config, window_size=window_size)
+ self.intermediate = Data2VecVisionIntermediate(config)
+ self.output = Data2VecVisionOutput(config)
+ self.layernorm_before = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.drop_path = Data2VecVisionDropPath(drop_path_rate) if drop_path_rate > 0.0 else nn.Identity()
+ self.layernorm_after = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+
+ init_values = config.layer_scale_init_value
+ if init_values > 0:
+ self.lambda_1 = nn.Parameter(init_values * torch.ones(config.hidden_size), requires_grad=True)
+ self.lambda_2 = nn.Parameter(init_values * torch.ones(config.hidden_size), requires_grad=True)
+ else:
+ self.lambda_1, self.lambda_2 = None, None
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ output_attentions: bool = False,
+ relative_position_bias: torch.Tensor | None = None,
+ interpolate_pos_encoding: bool = False,
+ resolution: tuple[int, int] | None = None,
+ ) -> tuple[torch.Tensor] | tuple[torch.Tensor, torch.Tensor]:
+ self_attention_outputs = self.attention(
+ self.layernorm_before(hidden_states), # in Data2VecVision, layernorm is applied before self-attention
+ output_attentions=output_attentions,
+ relative_position_bias=relative_position_bias,
+ interpolate_pos_encoding=interpolate_pos_encoding,
+ resolution=resolution,
+ )
+ attention_output = self_attention_outputs[0]
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
+
+ # apply lambda_1 if present
+ if self.lambda_1 is not None:
+ attention_output = self.lambda_1 * attention_output
+
+ # first residual connection
+ hidden_states = self.drop_path(attention_output) + hidden_states
+
+ # in Data2VecVision, layernorm is also applied after self-attention
+ layer_output = self.layernorm_after(hidden_states)
+
+ layer_output = self.intermediate(layer_output)
+ layer_output = self.output(layer_output)
+
+ if self.lambda_2 is not None:
+ layer_output = self.lambda_2 * layer_output
+
+ # second residual connection
+ layer_output = self.drop_path(layer_output) + hidden_states
+
+ outputs = (layer_output,) + outputs
+
+ return outputs
+
+
+# Todo - Refactor as part of vision refactor. Copied from transformers.models.beit.modeling_beit.BeitRelativePositionBias with Beit->Data2VecVision
+class Data2VecVisionRelativePositionBias(nn.Module):
+ def __init__(self, config: Data2VecVisionConfig, window_size: tuple) -> None:
+ super().__init__()
+ self.window_size = window_size
+ self.num_relative_distance = (2 * window_size[0] - 1) * (2 * window_size[1] - 1) + 3
+ self.relative_position_bias_table = nn.Parameter(
+ torch.zeros(self.num_relative_distance, config.num_attention_heads)
+ ) # 2*Wh-1 * 2*Ww-1, nH
+ # cls to token & token 2 cls & cls to cls
+
+ @staticmethod
+ @compile_compatible_method_lru_cache(maxsize=10)
+ def generate_relative_position_index(window_size: tuple[int, int]) -> torch.Tensor:
+ """
+ This method creates the relative position index, modified to support arbitrary window sizes,
+ as introduced in [MiDaS v3.1](https://huggingface.co/papers/2307.14460).
+ """
+ num_relative_distance = (2 * window_size[0] - 1) * (2 * window_size[1] - 1) + 3
+ # cls to token & token 2 cls & cls to cls
+ # get pair-wise relative position index for each token inside the window
+ window_area = window_size[0] * window_size[1]
+ grid = torch.meshgrid(torch.arange(window_size[0]), torch.arange(window_size[1]), indexing="ij")
+ coords = torch.stack(grid) # 2, Wh, Ww
+ coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww
+ relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww
+ relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2
+ relative_coords[:, :, 0] += window_size[0] - 1 # shift to start from 0
+ relative_coords[:, :, 1] += window_size[1] - 1
+ relative_coords[:, :, 0] *= 2 * window_size[1] - 1
+ relative_position_index = torch.zeros(size=(window_area + 1,) * 2, dtype=relative_coords.dtype)
+ relative_position_index[1:, 1:] = relative_coords.sum(-1) # Wh*Ww, Wh*Ww
+ relative_position_index[0, 0:] = num_relative_distance - 3
+ relative_position_index[0:, 0] = num_relative_distance - 2
+ relative_position_index[0, 0] = num_relative_distance - 1
+ return relative_position_index
+
+ def forward(self, window_size, interpolate_pos_encoding: bool = False, dim_size=None) -> torch.Tensor:
+ """
+ Modification of timm.models.beit.py: Attention._get_rel_pos_bias to support arbitrary window sizes.
+ """
+ old_height = 2 * self.window_size[0] - 1
+ old_width = 2 * self.window_size[1] - 1
+
+ new_height = 2 * window_size[0] - 1
+ new_width = 2 * window_size[1] - 1
+
+ old_relative_position_bias_table = self.relative_position_bias_table
+
+ old_num_relative_distance = self.num_relative_distance
+ new_num_relative_distance = new_height * new_width + 3
+
+ old_sub_table = old_relative_position_bias_table[: old_num_relative_distance - 3]
+
+ old_sub_table = old_sub_table.reshape(1, old_width, old_height, -1).permute(0, 3, 1, 2)
+ new_sub_table = nn.functional.interpolate(
+ old_sub_table, size=(torch_int(new_height), torch_int(new_width)), mode="bilinear"
+ )
+ new_sub_table = new_sub_table.permute(0, 2, 3, 1).reshape(new_num_relative_distance - 3, -1)
+
+ new_relative_position_bias_table = torch.cat(
+ [new_sub_table, old_relative_position_bias_table[old_num_relative_distance - 3 :]]
+ )
+
+ relative_position_index = self.generate_relative_position_index(window_size)
+ relative_position_bias = new_relative_position_bias_table[relative_position_index.view(-1)]
+
+ # patch_size*num_patches_height, patch_size*num_patches_width, num_attention_heads
+ relative_position_bias = relative_position_bias.view(
+ window_size[0] * window_size[1] + 1, window_size[0] * window_size[1] + 1, -1
+ )
+ # num_attention_heads, patch_size*num_patches_width, patch_size*num_patches_height
+ relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous()
+
+ if interpolate_pos_encoding:
+ relative_position_bias = nn.functional.interpolate(
+ relative_position_bias.unsqueeze(1),
+ size=(dim_size, dim_size),
+ mode="bilinear",
+ align_corners=False,
+ ).squeeze(1)
+
+ return relative_position_bias.unsqueeze(0)
+
+
+# Todo - Refactor as part of vision refactor. Copied from transformers.models.beit.modeling_beit.BeitEncoder with Beit->Data2VecVision
+class Data2VecVisionEncoder(nn.Module):
+ def __init__(self, config: Data2VecVisionConfig, window_size: tuple | None = None) -> None:
+ super().__init__()
+ self.config = config
+ self.has_relative_position_bias = config.use_shared_relative_position_bias
+ if self.has_relative_position_bias:
+ self.relative_position_bias = Data2VecVisionRelativePositionBias(config, window_size=window_size)
+
+ # stochastic depth decay rule
+ dpr = [x.item() for x in torch.linspace(0, config.drop_path_rate, config.num_hidden_layers, device="cpu")]
+ self.layer = nn.ModuleList(
+ [
+ Data2VecVisionLayer(
+ config,
+ window_size=window_size if config.use_relative_position_bias else None,
+ drop_path_rate=dpr[i],
+ )
+ for i in range(config.num_hidden_layers)
+ ]
+ )
+ self.gradient_checkpointing = False
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ output_attentions: bool = False,
+ output_hidden_states: bool = False,
+ interpolate_pos_encoding: bool = False,
+ resolution: tuple[int, int] | None = None,
+ return_dict: bool = True,
+ ) -> tuple | BaseModelOutput:
+ all_hidden_states = () if output_hidden_states else None
+ all_self_attentions = () if output_attentions else None
+
+ for i, layer_module in enumerate(self.layer):
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ if self.has_relative_position_bias:
+ height, width = resolution
+ window_size = (height // self.config.patch_size, width // self.config.patch_size)
+ relative_position_bias = self.relative_position_bias(
+ window_size, interpolate_pos_encoding=interpolate_pos_encoding, dim_size=hidden_states.shape[1]
+ )
+ else:
+ relative_position_bias = None
+
+ layer_outputs = layer_module(
+ hidden_states,
+ output_attentions=output_attentions,
+ relative_position_bias=relative_position_bias,
+ interpolate_pos_encoding=interpolate_pos_encoding,
+ resolution=resolution,
+ )
+
+ hidden_states = layer_outputs[0]
+
+ if output_attentions:
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
+
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ if not return_dict:
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
+ return BaseModelOutput(
+ last_hidden_state=hidden_states,
+ hidden_states=all_hidden_states,
+ attentions=all_self_attentions,
+ )
+
+
+@auto_docstring
+# Todo - Refactor as part of vision refactor. Copied from transformers.models.beit.modeling_beit.BeitPreTrainedModel with Beit->Data2VecVision,beit->data2vec_vision
+class Data2VecVisionPreTrainedModel(PreTrainedModel):
+ config: Data2VecVisionConfig
+ base_model_prefix = "data2vec_vision"
+ input_modalities = ("image",)
+ main_input_name = "pixel_values"
+ supports_gradient_checkpointing = True
+ _no_split_modules = ["Data2VecVisionLayer"]
+ _keys_to_ignore_on_load_unexpected = [r".*relative_position_index.*"]
+ _supports_sdpa = True
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ """Initialize the weights"""
+ super()._init_weights(module)
+ if isinstance(module, Data2VecVisionEmbeddings):
+ init.zeros_(module.cls_token)
+ if module.mask_token is not None:
+ init.zeros_(module.mask_token)
+ if module.position_embeddings is not None:
+ init.zeros_(module.position_embeddings)
+ elif isinstance(module, Data2VecVisionRelativePositionBias):
+ init.zeros_(module.relative_position_bias_table)
+ elif isinstance(module, Data2VecVisionLayer):
+ if module.lambda_1 is not None:
+ init.constant_(module.lambda_1, self.config.layer_scale_init_value)
+ init.constant_(module.lambda_2, self.config.layer_scale_init_value)
+
+
+@auto_docstring
+# Todo - Refactor as part of vision refactor. Copied from transformers.models.beit.modeling_beit.BeitModel with BEIT->DATA2VEC_VISION,Beit->Data2VecVision,True->False
+class Data2VecVisionModel(Data2VecVisionPreTrainedModel):
+ def __init__(self, config: Data2VecVisionConfig, add_pooling_layer: bool = False) -> None:
+ r"""
+ add_pooling_layer (bool, *optional*, defaults to `False`):
+ Whether to add a pooling layer
+ """
+ super().__init__(config)
+ self.config = config
+
+ self.embeddings = Data2VecVisionEmbeddings(config)
+ self.encoder = Data2VecVisionEncoder(config, window_size=self.embeddings.patch_embeddings.patch_shape)
+
+ self.layernorm = (
+ nn.Identity() if config.use_mean_pooling else nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ )
+ self.pooler = Data2VecVisionPooler(config) if add_pooling_layer else None
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.embeddings.patch_embeddings
+
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: torch.Tensor,
+ bool_masked_pos: torch.BoolTensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ interpolate_pos_encoding: bool = False,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple | Data2VecVisionModelOutputWithPooling:
+ r"""
+ bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, num_patches)`, *optional*):
+ Boolean masked positions. Indicates which patches are masked (1) and which aren't (0).
+ """
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ embedding_output, _ = self.embeddings(pixel_values, bool_masked_pos=bool_masked_pos)
+ resolution = pixel_values.shape[2:]
+
+ encoder_outputs = self.encoder(
+ embedding_output,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ resolution=resolution,
+ return_dict=return_dict,
+ interpolate_pos_encoding=interpolate_pos_encoding,
+ )
+ sequence_output = encoder_outputs[0]
+ sequence_output = self.layernorm(sequence_output)
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
+
+ if not return_dict:
+ head_outputs = (sequence_output, pooled_output) if pooled_output is not None else (sequence_output,)
+ return head_outputs + encoder_outputs[1:]
+
+ return Data2VecVisionModelOutputWithPooling(
+ last_hidden_state=sequence_output,
+ pooler_output=pooled_output,
+ hidden_states=encoder_outputs.hidden_states,
+ attentions=encoder_outputs.attentions,
+ )
+
+
+# Copied from transformers.models.beit.modeling_beit.BeitPooler with Beit->Data2VecVision
+class Data2VecVisionPooler(nn.Module):
+ def __init__(self, config: Data2VecVisionConfig) -> None:
+ super().__init__()
+ self.layernorm = (
+ nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) if config.use_mean_pooling else None
+ )
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ # Mean pool patch tokens with layernorm, or take the [CLS] token
+ return self.layernorm(hidden_states[:, 1:, :].mean(1)) if self.layernorm is not None else hidden_states[:, 0]
+
+
+@auto_docstring(
+ custom_intro="""
+ Data2VecVision Model transformer with an image classification head on top (a linear layer on top of the average of
+ the final hidden states of the patch tokens) e.g. for ImageNet.
+ """
+)
+# Todo - Refactor as part of vision refactor. Copied from transformers.models.beit.modeling_beit.BeitForImageClassification with BEIT->DATA2VEC_VISION,Beit->Data2VecVision,beit->data2vec_vision
+class Data2VecVisionForImageClassification(Data2VecVisionPreTrainedModel):
+ def __init__(self, config: Data2VecVisionConfig) -> None:
+ super().__init__(config)
+
+ self.num_labels = config.num_labels
+ self.data2vec_vision = Data2VecVisionModel(config, add_pooling_layer=True)
+
+ # Classifier head
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels) if config.num_labels > 0 else nn.Identity()
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: torch.Tensor | None = None,
+ labels: torch.Tensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ interpolate_pos_encoding: bool = False,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple | ImageClassifierOutput:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+ outputs = self.data2vec_vision(
+ pixel_values,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ interpolate_pos_encoding=interpolate_pos_encoding,
+ return_dict=return_dict,
+ )
+
+ pooled_output = outputs.pooler_output if return_dict else outputs[1]
+
+ logits = self.classifier(pooled_output)
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(labels, logits, self.config)
+
+ if not return_dict:
+ output = (logits,) + outputs[2:]
+ return ((loss,) + output) if loss is not None else output
+
+ return ImageClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+# Copied from transformers.models.beit.modeling_beit.BeitConvLayer with Beit->Data2VecVision
+class Data2VecVisionConvLayer(nn.Module):
+ def __init__(
+ self,
+ in_channels: int,
+ out_channels: int,
+ kernel_size: int | tuple[int, int] = 3,
+ stride: int = 1,
+ padding: int | tuple[int, int] | str = 0,
+ bias: bool = False,
+ dilation: int | tuple[int, int] = 1,
+ groups: int = 1,
+ activation: str = "relu",
+ ):
+ super().__init__()
+ self.convolution = nn.Conv2d(
+ in_channels=in_channels,
+ out_channels=out_channels,
+ kernel_size=kernel_size,
+ stride=stride,
+ padding=padding,
+ dilation=dilation,
+ groups=groups,
+ bias=bias,
+ )
+ self.normalization = nn.BatchNorm2d(out_channels)
+ self.activation = ACT2FN[activation] if activation is not None else nn.Identity()
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.convolution(hidden_states)
+ hidden_states = self.normalization(hidden_states)
+ hidden_states = self.activation(hidden_states)
+ return hidden_states
+
+
+# Copied from transformers.models.beit.modeling_beit.BeitPyramidPoolingBlock with Beit->Data2VecVision
+class Data2VecVisionPyramidPoolingBlock(nn.Module):
+ def __init__(self, pool_scale: int, in_channels: int, channels: int) -> None:
+ super().__init__()
+ self.pooling = nn.AdaptiveAvgPool2d(pool_scale)
+ self.conv = Data2VecVisionConvLayer(in_channels, channels, kernel_size=1)
+
+ def forward(self, input: torch.Tensor, size: tuple[int, int]) -> torch.Tensor:
+ hidden_state = self.pooling(input)
+ hidden_state = self.conv(hidden_state)
+ hidden_state = nn.functional.interpolate(hidden_state, size=size, mode="bilinear", align_corners=False)
+ return hidden_state
+
+
+# Copied from transformers.models.beit.modeling_beit.BeitPyramidPoolingModule with Beit->Data2VecVision
+class Data2VecVisionPyramidPoolingModule(nn.Module):
+ """
+ Pyramid Pooling Module (PPM) used in PSPNet.
+
+ Args:
+ pool_scales (tuple[int]): Pooling scales used in Pooling Pyramid
+ Module.
+ in_channels (int): Input channels.
+ channels (int): Channels after modules, before conv_seg.
+
+ Based on OpenMMLab's implementation, found in https://github.com/open-mmlab/mmsegmentation.
+ """
+
+ def __init__(self, pool_scales: tuple[int, ...], in_channels: int, channels: int) -> None:
+ super().__init__()
+ self.pool_scales = pool_scales
+ self.in_channels = in_channels
+ self.channels = channels
+ self.blocks = nn.ModuleList(
+ [
+ Data2VecVisionPyramidPoolingBlock(pool_scale=pool_scale, in_channels=in_channels, channels=channels)
+ for pool_scale in pool_scales
+ ]
+ )
+
+ def forward(self, hidden_states: torch.Tensor) -> list[torch.Tensor]:
+ original_size = hidden_states.size()[2:]
+ return [block(hidden_states, size=original_size) for block in self.blocks]
+
+
+# Copied from transformers.models.beit.modeling_beit.BeitUperHead with Beit->Data2VecVision
+class Data2VecVisionUperHead(nn.Module):
+ """
+ Unified Perceptual Parsing for Scene Understanding. This head is the implementation of
+ [UPerNet](https://huggingface.co/papers/1807.10221).
+
+ Based on OpenMMLab's implementation, found in https://github.com/open-mmlab/mmsegmentation.
+ """
+
+ def __init__(self, config: Data2VecVisionConfig) -> None:
+ super().__init__()
+
+ self.pool_scales = config.pool_scales # e.g. (1, 2, 3, 6)
+ self.in_channels = [config.hidden_size] * 4 # e.g. [768, 768, 768, 768]
+ self.channels = config.hidden_size
+ self.classifier = nn.Conv2d(self.channels, config.num_labels, kernel_size=1)
+
+ # PSP Module
+ self.psp_modules = Data2VecVisionPyramidPoolingModule(
+ self.pool_scales,
+ self.in_channels[-1],
+ self.channels,
+ )
+ self.psp_bottleneck = Data2VecVisionConvLayer(
+ self.in_channels[-1] + len(self.pool_scales) * self.channels,
+ self.channels,
+ kernel_size=3,
+ padding=1,
+ )
+ # FPN Module
+ self.lateral_convs = nn.ModuleList()
+ self.fpn_convs = nn.ModuleList()
+ for in_channels in self.in_channels[:-1]: # skip the top layer
+ self.lateral_convs.append(Data2VecVisionConvLayer(in_channels, self.channels, kernel_size=1))
+ self.fpn_convs.append(Data2VecVisionConvLayer(self.channels, self.channels, kernel_size=3, padding=1))
+
+ self.fpn_bottleneck = Data2VecVisionConvLayer(
+ len(self.in_channels) * self.channels,
+ self.channels,
+ kernel_size=3,
+ padding=1,
+ )
+
+ def psp_forward(self, hidden_states: list[torch.Tensor]) -> torch.Tensor:
+ hidden_state = hidden_states[-1]
+ hidden_state = torch.cat([hidden_state, *self.psp_modules(hidden_state)], dim=1)
+ return self.psp_bottleneck(hidden_state)
+
+ def forward(self, encoder_hidden_states: list[torch.Tensor]) -> torch.Tensor:
+ # build laterals
+ laterals = []
+ for lateral_conv, hidden_state in zip(self.lateral_convs, encoder_hidden_states):
+ laterals.append(lateral_conv(hidden_state))
+
+ laterals.append(self.psp_forward(encoder_hidden_states))
+
+ # build top-down path
+ used_backbone_levels = len(laterals)
+ for i in range(used_backbone_levels - 1, 0, -1):
+ prev_shape = laterals[i - 1].shape[2:]
+ laterals[i - 1] = laterals[i - 1] + nn.functional.interpolate(
+ laterals[i], size=prev_shape, mode="bilinear", align_corners=False
+ )
+
+ # build outputs
+ fpn_outs = []
+ for i in range(used_backbone_levels - 1):
+ fpn_outs.append(self.fpn_convs[i](laterals[i]))
+ # append psp feature
+ fpn_outs.append(laterals[-1])
+
+ for i in range(used_backbone_levels - 1, 0, -1):
+ fpn_outs[i] = nn.functional.interpolate(
+ fpn_outs[i], size=fpn_outs[0].shape[2:], mode="bilinear", align_corners=False
+ )
+ fpn_outs = torch.cat(fpn_outs, dim=1)
+ output = self.fpn_bottleneck(fpn_outs)
+ output = self.classifier(output)
+
+ return output
+
+
+# Copied from transformers.models.beit.modeling_beit.BeitFCNHead with Beit->Data2VecVision
+class Data2VecVisionFCNHead(nn.Module):
+ """
+ Fully Convolution Networks for Semantic Segmentation. This head is implemented of
+ [FCNNet](https://huggingface.co/papers/1411.4038>).
+
+ Args:
+ config (Data2VecVisionConfig): Configuration.
+ in_channels
+ kernel_size (int): The kernel size for convs in the head. Default: 3.
+ dilation (int): The dilation rate for convs in the head. Default: 1.
+
+
+ Based on OpenMMLab's implementation, found in https://github.com/open-mmlab/mmsegmentation.
+ """
+
+ def __init__(
+ self,
+ config: Data2VecVisionConfig,
+ in_index: int = 2,
+ kernel_size: int = 3,
+ dilation: int | tuple[int, int] = 1,
+ ) -> None:
+ super().__init__()
+ self.in_channels = config.hidden_size
+ self.channels = config.auxiliary_channels
+ self.num_convs = config.auxiliary_num_convs
+ self.concat_input = config.auxiliary_concat_input
+ self.in_index = in_index
+
+ conv_padding = (kernel_size // 2) * dilation
+ self.convs = nn.ModuleList()
+ if self.num_convs > 0:
+ self.convs.append(
+ Data2VecVisionConvLayer(
+ self.in_channels, self.channels, kernel_size=kernel_size, padding=conv_padding, dilation=dilation
+ )
+ )
+ for _ in range(self.num_convs - 1):
+ self.convs.append(
+ Data2VecVisionConvLayer(
+ self.channels,
+ self.channels,
+ kernel_size=kernel_size,
+ padding=conv_padding,
+ dilation=dilation,
+ )
+ )
+ if self.concat_input:
+ self.conv_cat = Data2VecVisionConvLayer(
+ self.in_channels + self.channels, self.channels, kernel_size=kernel_size, padding=kernel_size // 2
+ )
+
+ self.classifier = nn.Conv2d(self.channels, config.num_labels, kernel_size=1)
+
+ def forward(self, encoder_hidden_states: list[torch.Tensor]) -> torch.Tensor:
+ residual = encoder_hidden_states[self.in_index]
+ hidden_states = residual
+ for conv in self.convs:
+ hidden_states = conv(hidden_states)
+ if self.concat_input:
+ hidden_states = self.conv_cat(torch.cat([residual, hidden_states], dim=1))
+ hidden_states = self.classifier(hidden_states)
+ return hidden_states
+
+
+@auto_docstring
+# Todo - Refactor as part of vision refactor. Copied from transformers.models.beit.modeling_beit.BeitForSemanticSegmentation with BEIT->DATA2VEC_VISION,Beit->Data2VecVision,microsoft/beit-base-finetuned-ade-640-640->facebook/data2vec-vision-base,beit->data2vec_vision
+class Data2VecVisionForSemanticSegmentation(Data2VecVisionPreTrainedModel):
+ def __init__(self, config: Data2VecVisionConfig) -> None:
+ super().__init__(config)
+
+ self.num_labels = config.num_labels
+ self.data2vec_vision = Data2VecVisionModel(config, add_pooling_layer=False)
+
+ # FPNs
+ if len(self.config.out_indices) != 4:
+ raise ValueError(
+ "Data2VecVisionForSemanticSegmentation requires config.out_indices to be a list of 4 integers, "
+ "specifying which features to use from the backbone. One can use [3, 5, 7, 11] in case of "
+ "a base-sized architecture."
+ )
+ self.fpn1 = nn.Sequential(
+ nn.ConvTranspose2d(config.hidden_size, config.hidden_size, kernel_size=2, stride=2),
+ nn.BatchNorm2d(config.hidden_size),
+ nn.GELU(),
+ nn.ConvTranspose2d(config.hidden_size, config.hidden_size, kernel_size=2, stride=2),
+ )
+ self.fpn2 = nn.Sequential(
+ nn.ConvTranspose2d(config.hidden_size, config.hidden_size, kernel_size=2, stride=2),
+ )
+ self.fpn3 = nn.Identity()
+ self.fpn4 = nn.MaxPool2d(kernel_size=2, stride=2)
+
+ # Semantic segmentation head(s)
+ self.decode_head = Data2VecVisionUperHead(config)
+ self.auxiliary_head = Data2VecVisionFCNHead(config) if config.use_auxiliary_head else None
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def compute_loss(self, logits, auxiliary_logits, labels):
+ # upsample logits to the images' original size
+ upsampled_logits = nn.functional.interpolate(
+ logits, size=labels.shape[-2:], mode="bilinear", align_corners=False
+ )
+ if auxiliary_logits is not None:
+ upsampled_auxiliary_logits = nn.functional.interpolate(
+ auxiliary_logits, size=labels.shape[-2:], mode="bilinear", align_corners=False
+ )
+ # compute weighted loss
+ loss_fct = CrossEntropyLoss(ignore_index=self.config.semantic_loss_ignore_index)
+ main_loss = loss_fct(upsampled_logits, labels)
+ loss = main_loss
+ if auxiliary_logits is not None:
+ auxiliary_loss = loss_fct(upsampled_auxiliary_logits, labels)
+ loss += self.config.auxiliary_loss_weight * auxiliary_loss
+
+ return loss
+
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: torch.Tensor | None = None,
+ labels: torch.Tensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ interpolate_pos_encoding: bool = False,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple | SemanticSegmenterOutput:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, height, width)`, *optional*):
+ Ground truth semantic segmentation maps for computing the loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels > 1`, a classification loss is computed (Cross-Entropy).
+
+ Examples:
+
+ ```python
+ >>> from transformers import AutoImageProcessor, Data2VecVisionForSemanticSegmentation
+ >>> from PIL import Image
+ >>> import httpx
+ >>> from io import BytesIO
+
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
+ >>> with httpx.stream("GET", url) as response:
+ ... image = Image.open(BytesIO(response.read()))
+
+ >>> image_processor = AutoImageProcessor.from_pretrained("facebook/data2vec-vision-base")
+ >>> model = Data2VecVisionForSemanticSegmentation.from_pretrained("facebook/data2vec-vision-base")
+
+ >>> inputs = image_processor(images=image, return_tensors="pt")
+ >>> outputs = model(**inputs)
+ >>> # logits are of shape (batch_size, num_labels, height, width)
+ >>> logits = outputs.logits
+ ```"""
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+
+ if labels is not None and self.config.num_labels == 1:
+ raise ValueError("The number of labels should be greater than one")
+
+ outputs = self.data2vec_vision(
+ pixel_values,
+ output_attentions=output_attentions,
+ output_hidden_states=True, # we need the intermediate hidden states
+ interpolate_pos_encoding=interpolate_pos_encoding,
+ return_dict=return_dict,
+ )
+
+ encoder_hidden_states = outputs.hidden_states if return_dict else outputs[1]
+
+ # only keep certain features, and reshape
+ # note that we do +1 as the encoder_hidden_states also includes the initial embeddings
+ features = [feature for idx, feature in enumerate(encoder_hidden_states) if idx + 1 in self.config.out_indices]
+ batch_size = pixel_values.shape[0]
+ patch_resolution = self.config.image_size // self.config.patch_size
+ features = [
+ x[:, 1:, :].permute(0, 2, 1).reshape(batch_size, -1, patch_resolution, patch_resolution) for x in features
+ ]
+
+ # apply FPNs
+ ops = [self.fpn1, self.fpn2, self.fpn3, self.fpn4]
+ for i in range(len(features)):
+ features[i] = ops[i](features[i])
+
+ logits = self.decode_head(features)
+
+ auxiliary_logits = None
+ if self.auxiliary_head is not None:
+ auxiliary_logits = self.auxiliary_head(features)
+
+ loss = None
+ if labels is not None:
+ loss = self.compute_loss(logits, auxiliary_logits, labels)
+
+ if not return_dict:
+ if output_hidden_states:
+ output = (logits,) + outputs[1:]
+ else:
+ output = (logits,) + outputs[2:]
+ return ((loss,) + output) if loss is not None else output
+
+ return SemanticSegmenterOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states if output_hidden_states else None,
+ attentions=outputs.attentions,
+ )
+
+
+__all__ = [
+ "Data2VecVisionForImageClassification",
+ "Data2VecVisionForSemanticSegmentation",
+ "Data2VecVisionModel",
+ "Data2VecVisionPreTrainedModel",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/data2vec/modular_data2vec_audio.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/data2vec/modular_data2vec_audio.py
new file mode 100644
index 0000000000000000000000000000000000000000..a6f5dda725dadfae5749f43ebb9e4c5a4bf40a32
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/data2vec/modular_data2vec_audio.py
@@ -0,0 +1,272 @@
+# Copyright 2022 The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch Data2VecText model."""
+
+import math
+
+import torch
+from torch import nn
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import Wav2Vec2BaseModelOutput
+from ...modeling_utils import PreTrainedModel
+from ..wav2vec2.modeling_wav2vec2 import (
+ Wav2Vec2Adapter,
+ Wav2Vec2Encoder,
+ Wav2Vec2FeatureEncoder,
+ Wav2Vec2FeatureProjection,
+ Wav2Vec2ForAudioFrameClassification,
+ Wav2Vec2ForCTC,
+ Wav2Vec2ForSequenceClassification,
+ Wav2Vec2ForXVector,
+ Wav2Vec2Model,
+ Wav2Vec2PreTrainedModel,
+ Wav2Vec2SamePadLayer,
+)
+from .configuration_data2vec_audio import Data2VecAudioConfig
+
+
+class Data2VecAudioConvLayer(GradientCheckpointingLayer):
+ def __init__(self, config, layer_id=0):
+ super().__init__()
+ self.in_conv_dim = config.conv_dim[layer_id - 1] if layer_id > 0 else 1
+ self.out_conv_dim = config.conv_dim[layer_id]
+
+ self.conv = nn.Conv1d(
+ self.in_conv_dim,
+ self.out_conv_dim,
+ kernel_size=config.conv_kernel[layer_id],
+ stride=config.conv_stride[layer_id],
+ bias=config.conv_bias,
+ )
+ self.layer_norm = nn.LayerNorm(self.out_conv_dim, elementwise_affine=True)
+ self.activation = ACT2FN[config.feat_extract_activation]
+
+ def forward(self, hidden_states):
+ hidden_states = self.conv(hidden_states)
+
+ hidden_states = hidden_states.transpose(-2, -1)
+ hidden_states = self.layer_norm(hidden_states)
+ hidden_states = hidden_states.transpose(-2, -1)
+
+ hidden_states = self.activation(hidden_states)
+ return hidden_states
+
+
+class Data2VecAudioPadLayer(Wav2Vec2SamePadLayer):
+ pass
+
+
+class Data2VecAudioPositionalConvLayer(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.conv = nn.Conv1d(
+ config.hidden_size,
+ config.hidden_size,
+ kernel_size=config.conv_pos_kernel_size,
+ padding=config.conv_pos_kernel_size // 2,
+ groups=config.num_conv_pos_embedding_groups,
+ )
+
+ self.padding = Data2VecAudioPadLayer(config.conv_pos_kernel_size)
+ self.activation = ACT2FN[config.feat_extract_activation]
+ # no learnable parameters
+ self.layer_norm = nn.LayerNorm(config.hidden_size, elementwise_affine=False)
+
+ def forward(self, hidden_states):
+ hidden_states = self.conv(hidden_states)
+ hidden_states = self.padding(hidden_states)
+
+ hidden_states = hidden_states.transpose(1, 2)
+ hidden_states = self.layer_norm(hidden_states)
+ hidden_states = hidden_states.transpose(1, 2)
+ hidden_states = self.activation(hidden_states)
+ return hidden_states
+
+
+class Data2VecAudioPositionalConvEmbedding(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.layers = nn.ModuleList(
+ [Data2VecAudioPositionalConvLayer(config) for _ in range(config.num_conv_pos_embeddings)]
+ )
+
+ def forward(self, hidden_states):
+ hidden_states = hidden_states.transpose(1, 2)
+ for layer in self.layers:
+ hidden_states = layer(hidden_states)
+ hidden_states = hidden_states.transpose(1, 2)
+ return hidden_states
+
+
+class Data2VecAudioFeatureEncoder(Wav2Vec2FeatureEncoder):
+ def __init__(self, config):
+ nn.Module.__init__(self)
+ self.conv_layers = nn.ModuleList(
+ [Data2VecAudioConvLayer(config, layer_id=i) for i in range(config.num_feat_extract_layers)]
+ )
+ self.gradient_checkpointing = False
+ self._requires_grad = True
+
+
+class Data2VecAudioFeatureProjection(Wav2Vec2FeatureProjection):
+ pass
+
+
+class Data2VecAudioEncoder(Wav2Vec2Encoder):
+ pass
+
+
+class Data2VecAudioAdapter(Wav2Vec2Adapter):
+ pass
+
+
+class Data2VecAudioPreTrainedModel(PreTrainedModel, Wav2Vec2PreTrainedModel):
+ config: Data2VecAudioConfig
+ base_model_prefix = "data2vec_audio"
+ main_input_name = "input_values"
+ input_modalities = "audio"
+ supports_gradient_checkpointing = True
+ _supports_flash_attn = True
+ _supports_sdpa = True
+ _supports_flex_attn = True
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ """Initialize the weights"""
+ if isinstance(module, Data2VecAudioFeatureProjection):
+ k = math.sqrt(1 / module.projection.in_features)
+ init.uniform_(module.projection.weight, a=-k, b=k)
+ init.uniform_(module.projection.bias, a=-k, b=k)
+ elif isinstance(module, Data2VecAudioPositionalConvLayer):
+ init.constant_(module.conv.bias, 0)
+ elif isinstance(module, nn.Linear):
+ init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
+
+ if module.bias is not None:
+ init.zeros_(module.bias)
+ elif isinstance(module, (nn.LayerNorm, nn.GroupNorm)):
+ if module.bias is not None:
+ init.zeros_(module.bias)
+ if module.weight is not None:
+ init.ones_(module.weight)
+ elif isinstance(module, nn.Conv1d):
+ init.kaiming_normal_(module.weight)
+
+ if module.bias is not None:
+ k = math.sqrt(module.groups / (module.in_channels * module.kernel_size[0]))
+ init.uniform_(module.bias, a=-k, b=k)
+
+ def _get_adapters(self):
+ raise AttributeError("Not needed for Data2VecAudio")
+
+ def init_adapter_layers(self):
+ raise AttributeError("Not needed for Data2VecAudio")
+
+ def load_adapter(self):
+ raise AttributeError("Not needed for Data2VecAudio")
+
+
+Data2VecAudioBaseModelOutput = Wav2Vec2BaseModelOutput
+
+
+class Data2VecAudioModel(Data2VecAudioPreTrainedModel, Wav2Vec2Model):
+ def __init__(self, config: Data2VecAudioConfig):
+ Data2VecAudioPreTrainedModel.__init__(self, config)
+ self.config = config
+ self.feature_extractor = Data2VecAudioFeatureEncoder(config)
+ self.feature_projection = Data2VecAudioFeatureProjection(config)
+
+ # model only needs masking vector if mask prob is > 0.0
+ if config.mask_time_prob > 0.0 or config.mask_feature_prob > 0.0:
+ self.masked_spec_embed = nn.Parameter(torch.Tensor(config.hidden_size).uniform_())
+
+ self.encoder = Data2VecAudioEncoder(config)
+
+ self.adapter = Data2VecAudioAdapter(config) if config.add_adapter else None
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def freeze_feature_encoder(self):
+ """
+ Calling this function will disable the gradient computation for the feature encoder so that its parameter will
+ not be updated during training.
+ """
+ self.feature_extractor._freeze_parameters()
+
+ def forward(self, **super_kwargs):
+ return super().forward(**super_kwargs)
+
+
+class Data2VecAudioForCTC(Data2VecAudioPreTrainedModel, Wav2Vec2ForCTC):
+ def __init__(self, config):
+ r"""
+ config ([`Data2VecAudioForCTC`]):
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
+ load the weights associated with the model, only the configuration. Check out the
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
+ """
+ Data2VecAudioPreTrainedModel.__init__(self, config)
+
+ self.data2vec_audio = Data2VecAudioModel(config)
+ self.dropout = nn.Dropout(config.final_dropout)
+
+ if config.vocab_size is None:
+ raise ValueError(
+ f"You are trying to instantiate {self.__class__} with a configuration that "
+ "does not define the vocabulary size of the language model head. Please "
+ "instantiate the model as follows: `Data2VecAudioForCTC.from_pretrained(..., vocab_size=vocab_size)`. "
+ "or define `vocab_size` of your model's configuration."
+ )
+ output_hidden_size = (
+ config.output_hidden_size if hasattr(config, "add_adapter") and config.add_adapter else config.hidden_size
+ )
+ self.lm_head = nn.Linear(output_hidden_size, config.vocab_size)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def freeze_base_model(self):
+ raise AttributeError("Not needed for Data2VecAudio")
+
+ def tie_weights(self):
+ raise AttributeError("Not needed for Data2VecAudio")
+
+ def forward(self, **super_kwargs):
+ return super().forward(**super_kwargs)
+
+
+class Data2VecAudioForSequenceClassification(Wav2Vec2ForSequenceClassification):
+ pass
+
+
+class Data2VecAudioForAudioFrameClassification(Wav2Vec2ForAudioFrameClassification):
+ pass
+
+
+class Data2VecAudioForXVector(Wav2Vec2ForXVector):
+ pass
+
+
+__all__ = [
+ "Data2VecAudioForAudioFrameClassification",
+ "Data2VecAudioForCTC",
+ "Data2VecAudioForSequenceClassification",
+ "Data2VecAudioForXVector",
+ "Data2VecAudioModel",
+ "Data2VecAudioPreTrainedModel",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/data2vec/modular_data2vec_text.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/data2vec/modular_data2vec_text.py
new file mode 100644
index 0000000000000000000000000000000000000000..1adc7abfcd2f4cbfb36e5db31a67c0b86967ea42
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/data2vec/modular_data2vec_text.py
@@ -0,0 +1,599 @@
+# Copyright 2022 The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch Data2VecText model."""
+
+import torch
+import torch.nn as nn
+from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
+
+from ... import initialization as init
+from ...generation import GenerationMixin
+from ...modeling_outputs import (
+ BaseModelOutputWithPoolingAndCrossAttentions,
+ CausalLMOutputWithCrossAttentions,
+ MaskedLMOutput,
+ MultipleChoiceModelOutput,
+ QuestionAnsweringModelOutput,
+ SequenceClassifierOutput,
+ TokenClassifierOutput,
+)
+from ...modeling_utils import PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import TransformersKwargs, auto_docstring, logging
+from ...utils.generic import can_return_tuple
+from ..roberta.modeling_roberta import (
+ RobertaClassificationHead,
+ RobertaCrossAttention,
+ RobertaEmbeddings,
+ RobertaLayer,
+ RobertaLMHead,
+ RobertaModel,
+ RobertaSelfAttention,
+)
+from .configuration_data2vec_text import Data2VecTextConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+class Data2VecTextEmbeddings(RobertaEmbeddings):
+ pass
+
+
+class Data2VecTextSelfAttention(RobertaSelfAttention):
+ pass
+
+
+class Data2VecTextCrossAttention(RobertaCrossAttention):
+ pass
+
+
+class Data2VecTextLayer(RobertaLayer):
+ pass
+
+
+@auto_docstring
+class Data2VecTextPreTrainedModel(PreTrainedModel):
+ config_class = Data2VecTextConfig
+ base_model_prefix = "data2vec_text"
+ supports_gradient_checkpointing = True
+ _no_split_modules = ["Data2VecTextForTextEmbeddings", "Data2VecTextLayer"]
+ _supports_flash_attn = True
+ _supports_sdpa = True
+ _supports_flex_attn = True
+ _supports_attention_backend = True
+ _can_record_outputs = {
+ "hidden_states": Data2VecTextLayer,
+ "attentions": Data2VecTextSelfAttention,
+ "cross_attentions": Data2VecTextCrossAttention,
+ }
+
+ def _init_weights(self, module):
+ super()._init_weights(module)
+ if isinstance(module, Data2VecTextEmbeddings):
+ init.copy_(module.position_ids, torch.arange(module.position_ids.shape[-1]).expand((1, -1)))
+ init.zeros_(module.token_type_ids)
+
+
+@auto_docstring
+class Data2VecTextModel(RobertaModel):
+ pass
+
+
+class Data2VecTextLMHead(RobertaLMHead):
+ pass
+
+
+class Data2VecTextClassificationHead(RobertaClassificationHead):
+ pass
+
+
+@auto_docstring(
+ custom_intro="""
+ Data2VecText Model with a `language modeling` head on top for CLM fine-tuning.
+ """
+)
+class Data2VecTextForCausalLM(Data2VecTextPreTrainedModel, GenerationMixin):
+ _tied_weights_keys = {
+ "lm_head.decoder.weight": "data2vec_text.embeddings.word_embeddings.weight",
+ "lm_head.decoder.bias": "lm_head.bias",
+ }
+
+ def __init__(self, config):
+ super().__init__(config)
+
+ if not config.is_decoder:
+ logger.warning("If you want to use `Data2VecTextLMHeadModel` as a standalone, add `is_decoder=True.`")
+
+ self.data2vec_text = Data2VecTextModel(config, add_pooling_layer=False)
+ self.lm_head = Data2VecTextLMHead(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_output_embeddings(self):
+ return self.lm_head.decoder
+
+ def set_output_embeddings(self, new_embeddings):
+ self.lm_head.decoder = new_embeddings
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ encoder_attention_mask: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ past_key_values: tuple[tuple[torch.FloatTensor]] | None = None,
+ use_cache: bool | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | CausalLMOutputWithCrossAttentions:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
+ `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
+ ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
+
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, Data2VecTextForCausalLM, Data2VecTextConfig
+ >>> import torch
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("facebook/data2vec-text-base")
+ >>> config = Data2VecTextConfig.from_pretrained("facebook/data2vec-text-base")
+ >>> config.is_decoder = True
+ >>> model = Data2VecTextForCausalLM.from_pretrained("facebook/data2vec-text-base", config=config)
+
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
+ >>> outputs = model(**inputs)
+
+ >>> prediction_logits = outputs.logits
+ ```"""
+ if labels is not None:
+ use_cache = False
+
+ outputs: BaseModelOutputWithPoolingAndCrossAttentions = self.data2vec_text(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ return_dict=True,
+ **kwargs,
+ )
+
+ hidden_states = outputs.last_hidden_state
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
+
+ return CausalLMOutputWithCrossAttentions(
+ loss=loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ cross_attentions=outputs.cross_attentions,
+ )
+
+
+@auto_docstring
+class Data2VecTextForMaskedLM(Data2VecTextPreTrainedModel):
+ _tied_weights_keys = {
+ "lm_head.decoder.weight": "data2vec_text.embeddings.word_embeddings.weight",
+ "lm_head.decoder.bias": "lm_head.bias",
+ }
+
+ def __init__(self, config):
+ super().__init__(config)
+
+ if config.is_decoder:
+ logger.warning(
+ "If you want to use `Data2VecTextForMaskedLM` make sure `config.is_decoder=False` for "
+ "bi-directional self-attention."
+ )
+
+ self.data2vec_text = Data2VecTextModel(config, add_pooling_layer=False)
+ self.lm_head = Data2VecTextLMHead(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_output_embeddings(self):
+ return self.lm_head.decoder
+
+ def set_output_embeddings(self, new_embeddings):
+ self.lm_head.decoder = new_embeddings
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ encoder_attention_mask: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | MaskedLMOutput:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
+ """
+ outputs = self.data2vec_text(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ return_dict=True,
+ **kwargs,
+ )
+ sequence_output = outputs[0]
+ prediction_scores = self.lm_head(sequence_output)
+
+ masked_lm_loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+
+ labels = labels.to(prediction_scores.device)
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
+
+ return MaskedLMOutput(
+ loss=masked_lm_loss,
+ logits=prediction_scores,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ Data2VecText Model transformer with a sequence classification/regression head on top (a linear layer on top of the
+ pooled output) e.g. for GLUE tasks.
+ """
+)
+class Data2VecTextForSequenceClassification(Data2VecTextPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+ self.config = config
+
+ self.data2vec_text = Data2VecTextModel(config, add_pooling_layer=False)
+ self.classifier = Data2VecTextClassificationHead(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | SequenceClassifierOutput:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+ outputs = self.data2vec_text(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ return_dict=True,
+ **kwargs,
+ )
+ sequence_output = outputs[0]
+ logits = self.classifier(sequence_output)
+
+ loss = None
+ if labels is not None:
+ labels = labels.to(logits.device)
+
+ if self.config.problem_type is None:
+ if self.num_labels == 1:
+ self.config.problem_type = "regression"
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
+ self.config.problem_type = "single_label_classification"
+ else:
+ self.config.problem_type = "multi_label_classification"
+
+ if self.config.problem_type == "regression":
+ loss_fct = MSELoss()
+ if self.num_labels == 1:
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
+ else:
+ loss = loss_fct(logits, labels)
+ elif self.config.problem_type == "single_label_classification":
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+ elif self.config.problem_type == "multi_label_classification":
+ loss_fct = BCEWithLogitsLoss()
+ loss = loss_fct(logits, labels)
+
+ return SequenceClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+class Data2VecTextForMultipleChoice(Data2VecTextPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.data2vec_text = Data2VecTextModel(config)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+ self.classifier = nn.Linear(config.hidden_size, 1)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | MultipleChoiceModelOutput:
+ r"""
+ input_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input-ids)
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
+ 1]`:
+
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
+ num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
+ `input_ids` above)
+ position_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
+ config.max_position_embeddings - 1]`.
+
+ [What are position IDs?](../glossary#position-ids)
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_choices, sequence_length, hidden_size)`, *optional*):
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
+ model's internal embedding lookup matrix.
+ """
+ num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
+
+ flat_input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
+ flat_position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
+ flat_token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
+ flat_attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
+ flat_inputs_embeds = (
+ inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
+ if inputs_embeds is not None
+ else None
+ )
+
+ outputs = self.data2vec_text(
+ flat_input_ids,
+ position_ids=flat_position_ids,
+ token_type_ids=flat_token_type_ids,
+ attention_mask=flat_attention_mask,
+ inputs_embeds=flat_inputs_embeds,
+ return_dict=True,
+ **kwargs,
+ )
+ pooled_output = outputs[1]
+
+ pooled_output = self.dropout(pooled_output)
+ logits = self.classifier(pooled_output)
+ reshaped_logits = logits.view(-1, num_choices)
+
+ loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+
+ labels = labels.to(reshaped_logits.device)
+ loss = loss_fct(reshaped_logits, labels)
+
+ return MultipleChoiceModelOutput(
+ loss=loss,
+ logits=reshaped_logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+class Data2VecTextForTokenClassification(Data2VecTextPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+
+ self.data2vec_text = Data2VecTextModel(config, add_pooling_layer=False)
+ classifier_dropout = (
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
+ )
+ self.dropout = nn.Dropout(classifier_dropout)
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | TokenClassifierOutput:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
+ """
+ outputs = self.data2vec_text(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ return_dict=True,
+ **kwargs,
+ )
+
+ sequence_output = outputs[0]
+
+ sequence_output = self.dropout(sequence_output)
+ logits = self.classifier(sequence_output)
+
+ loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+
+ labels = labels.to(logits.device)
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+
+ return TokenClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+class Data2VecTextForQuestionAnswering(Data2VecTextPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+
+ self.data2vec_text = Data2VecTextModel(config, add_pooling_layer=False)
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ start_positions: torch.LongTensor | None = None,
+ end_positions: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | QuestionAnsweringModelOutput:
+ outputs = self.data2vec_text(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ return_dict=True,
+ **kwargs,
+ )
+
+ sequence_output = outputs[0]
+
+ logits = self.qa_outputs(sequence_output)
+ start_logits, end_logits = logits.split(1, dim=-1)
+ start_logits = start_logits.squeeze(-1).contiguous()
+ end_logits = end_logits.squeeze(-1).contiguous()
+
+ total_loss = None
+ if start_positions is not None and end_positions is not None:
+ # If we are on multi-GPU, split add a dimension
+ if len(start_positions.size()) > 1:
+ start_positions = start_positions.squeeze(-1)
+ if len(end_positions.size()) > 1:
+ end_positions = end_positions.squeeze(-1)
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
+ ignored_index = start_logits.size(1)
+ start_positions = start_positions.clamp(0, ignored_index)
+ end_positions = end_positions.clamp(0, ignored_index)
+
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
+ start_loss = loss_fct(start_logits, start_positions)
+ end_loss = loss_fct(end_logits, end_positions)
+ total_loss = (start_loss + end_loss) / 2
+
+ return QuestionAnsweringModelOutput(
+ loss=total_loss,
+ start_logits=start_logits,
+ end_logits=end_logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+__all__ = [
+ "Data2VecTextForCausalLM",
+ "Data2VecTextForMaskedLM",
+ "Data2VecTextForMultipleChoice",
+ "Data2VecTextForQuestionAnswering",
+ "Data2VecTextForSequenceClassification",
+ "Data2VecTextForTokenClassification",
+ "Data2VecTextModel",
+ "Data2VecTextPreTrainedModel",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/decision_transformer/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/decision_transformer/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..455f7ffec5dee0567039cfd844588cb991c15622
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/decision_transformer/__init__.py
@@ -0,0 +1,27 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_decision_transformer import *
+ from .modeling_decision_transformer import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/decision_transformer/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/decision_transformer/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a73b7e15b5694b633857a706560c18effc2cb700
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/decision_transformer/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/decision_transformer/__pycache__/configuration_decision_transformer.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/decision_transformer/__pycache__/configuration_decision_transformer.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bfd970d9148c83e1a90315b34f05cba6d869146e
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/decision_transformer/__pycache__/configuration_decision_transformer.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/decision_transformer/__pycache__/modeling_decision_transformer.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/decision_transformer/__pycache__/modeling_decision_transformer.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8bd4789d1793bee8689a1d16b1d6ea8298b18496
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/decision_transformer/__pycache__/modeling_decision_transformer.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/decision_transformer/configuration_decision_transformer.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/decision_transformer/configuration_decision_transformer.py
new file mode 100644
index 0000000000000000000000000000000000000000..299c4a08c045d8d921b01bc641f9dd30c853c80c
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/decision_transformer/configuration_decision_transformer.py
@@ -0,0 +1,90 @@
+# Copyright 2022 The HuggingFace Team and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Decision Transformer model configuration"""
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring
+
+
+@auto_docstring(checkpoint="")
+@strict
+class DecisionTransformerConfig(PreTrainedConfig):
+ r"""
+ state_dim (`int`, *optional*, defaults to 17):
+ The state size for the RL environment
+ act_dim (`int`, *optional*, defaults to 4):
+ The size of the output action space
+ max_ep_len (`int`, *optional*, defaults to 4096):
+ The maximum length of an episode in the environment
+ action_tanh (`bool`, *optional*, defaults to True):
+ Whether to use a tanh activation on action prediction
+ scale_attn_weights (`bool`, *optional*, defaults to `True`):
+ Scale attention weights by dividing by sqrt(hidden_size)..
+ scale_attn_by_inverse_layer_idx (`bool`, *optional*, defaults to `False`):
+ Whether to additionally scale attention weights by `1 / layer_idx + 1`.
+ reorder_and_upcast_attn (`bool`, *optional*, defaults to `False`):
+ Whether to scale keys (K) prior to computing attention (dot-product) and upcast attention
+ dot-product/softmax to float() when training with mixed precision.
+
+ Example:
+
+ ```python
+ >>> from transformers import DecisionTransformerConfig, DecisionTransformerModel
+
+ >>> # Initializing a DecisionTransformer configuration
+ >>> configuration = DecisionTransformerConfig()
+
+ >>> # Initializing a model (with random weights) from the configuration
+ >>> model = DecisionTransformerModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "decision_transformer"
+ keys_to_ignore_at_inference = ["past_key_values"]
+ attribute_map = {
+ "max_position_embeddings": "n_positions",
+ "num_attention_heads": "n_head",
+ "num_hidden_layers": "n_layer",
+ }
+
+ state_dim: int = 17
+ act_dim: int = 4
+ hidden_size: int = 128
+ max_ep_len: int = 4096
+ action_tanh: bool = True
+ vocab_size: int = 1
+ n_positions: int = 1024
+ n_layer: int = 3
+ n_head: int = 1
+ n_inner: int | None = None
+ activation_function: str = "relu"
+ resid_pdrop: float | int = 0.1
+ embd_pdrop: float | int = 0.1
+ attn_pdrop: float | int = 0.1
+ layer_norm_epsilon: float = 1e-5
+ initializer_range: float = 0.02
+ scale_attn_weights: bool = True
+ use_cache: bool = True
+ bos_token_id: int | None = 50256
+ eos_token_id: int | list[int] | None = 50256
+ scale_attn_by_inverse_layer_idx: bool = False
+ reorder_and_upcast_attn: bool = False
+ add_cross_attention: bool = False
+
+
+__all__ = ["DecisionTransformerConfig"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/decision_transformer/modeling_decision_transformer.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/decision_transformer/modeling_decision_transformer.py
new file mode 100644
index 0000000000000000000000000000000000000000..4776e43f4e196fe26e00642be4bde196b2b01ea2
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/decision_transformer/modeling_decision_transformer.py
@@ -0,0 +1,674 @@
+# Copyright 2022 The HuggingFace Team The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch DecisionTransformer model."""
+
+import math
+from collections.abc import Callable
+from dataclasses import dataclass
+
+import torch
+from torch import nn
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...cache_utils import Cache, DynamicCache, EncoderDecoderCache
+from ...masking_utils import create_bidirectional_mask, create_causal_mask
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import BaseModelOutputWithPastAndCrossAttentions
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
+from ...processing_utils import Unpack
+from ...pytorch_utils import Conv1D
+from ...utils import (
+ ModelOutput,
+ TransformersKwargs,
+ auto_docstring,
+ logging,
+)
+from ...utils.generic import maybe_autocast, merge_with_config_defaults
+from ...utils.output_capturing import OutputRecorder, capture_outputs
+from .configuration_decision_transformer import DecisionTransformerConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+# Copied from transformers.models.gpt2.modeling_gpt2.eager_attention_forward
+def eager_attention_forward(module, query, key, value, attention_mask, scaling=None, dropout=0.0, **kwargs):
+ if scaling is None:
+ scaling = query.size(-1) ** -0.5
+
+ attn_weights = torch.matmul(query, key.transpose(-1, -2)) * scaling
+
+ if attention_mask is not None:
+ attn_weights = attn_weights + attention_mask
+
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
+
+ # Downcast (if necessary) back to V's dtype (if in mixed-precision) -- No-Op otherwise
+ attn_weights = attn_weights.type(value.dtype)
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
+
+ attn_output = torch.matmul(attn_weights, value)
+ attn_output = attn_output.transpose(1, 2)
+
+ return attn_output, attn_weights
+
+
+# Copied from transformers.models.gpt2.modeling_gpt2.GPT2Attention with GPT2->DecisionTransformerGPT2
+class DecisionTransformerGPT2Attention(nn.Module):
+ def __init__(self, config, is_cross_attention=False, layer_idx=None):
+ super().__init__()
+ self.config = config
+ self.embed_dim = config.hidden_size
+ self.num_heads = config.num_attention_heads
+ self.head_dim = self.embed_dim // self.num_heads
+ self.split_size = self.embed_dim
+ if self.head_dim * self.num_heads != self.embed_dim:
+ raise ValueError(
+ f"`embed_dim` must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
+ f" {self.num_heads})."
+ )
+
+ self.scale_attn_weights = config.scale_attn_weights
+ self.scale_attn_by_inverse_layer_idx = config.scale_attn_by_inverse_layer_idx
+ self.reorder_and_upcast_attn = config.reorder_and_upcast_attn
+ self.is_cross_attention = is_cross_attention
+ self.layer_idx = layer_idx
+
+ # Precompute unified scaling factor (accounts for both head_dim and layer-wise scaling)
+ self.scaling = 1.0
+ if self.scale_attn_weights:
+ self.scaling = self.head_dim**-0.5
+ if self.scale_attn_by_inverse_layer_idx:
+ self.scaling /= float(self.layer_idx + 1)
+
+ if self.is_cross_attention:
+ self.c_attn = Conv1D(2 * self.embed_dim, self.embed_dim)
+ self.q_attn = Conv1D(self.embed_dim, self.embed_dim)
+ else:
+ self.c_attn = Conv1D(3 * self.embed_dim, self.embed_dim)
+ self.c_proj = Conv1D(self.embed_dim, self.embed_dim)
+
+ self.attn_dropout = nn.Dropout(config.attn_pdrop)
+ self.resid_dropout = nn.Dropout(config.resid_pdrop)
+ self.is_causal = not is_cross_attention
+
+ def _upcast_and_reordered_attn(self, query, key, value, attention_mask=None):
+ # Use `torch.baddbmm` (a bit more efficient w/ alpha param for scaling -- from Megatron-LM)
+ bsz, num_heads, q_seq_len, dk = query.size()
+ _, _, k_seq_len, _ = key.size()
+
+ # Preallocate attn_weights for `baddbmm`
+ attn_weights = torch.empty(bsz * num_heads, q_seq_len, k_seq_len, dtype=torch.float32, device=query.device)
+
+ # Upcast (turn off autocast) and reorder (Scale K by 1 / root(dk))
+ with maybe_autocast(query.device.type, enabled=False):
+ q, k = query.reshape(-1, q_seq_len, dk), key.transpose(-1, -2).reshape(-1, dk, k_seq_len)
+ attn_weights = torch.baddbmm(attn_weights, q.float(), k.float(), beta=0, alpha=self.scaling)
+ attn_weights = attn_weights.reshape(bsz, num_heads, q_seq_len, k_seq_len)
+
+ if attention_mask is not None:
+ # Apply the attention mask
+ attn_weights = attn_weights + attention_mask
+
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
+
+ # Downcast (if necessary) back to V's dtype (if in mixed-precision) -- No-Op if otherwise
+ if attn_weights.dtype != torch.float32:
+ raise RuntimeError("Error with upcasting, attn_weights does not have dtype torch.float32")
+ attn_weights = attn_weights.type(value.dtype)
+ attn_weights = self.attn_dropout(attn_weights)
+
+ attn_output = torch.matmul(attn_weights, value)
+ attn_output = attn_output.transpose(1, 2)
+
+ return attn_output, attn_weights
+
+ def forward(
+ self,
+ hidden_states: tuple[torch.FloatTensor] | None,
+ past_key_values: Cache | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ encoder_hidden_states: torch.Tensor | None = None,
+ encoder_attention_mask: torch.FloatTensor | None = None,
+ output_attentions: bool | None = False,
+ **kwargs,
+ ) -> tuple[torch.Tensor | tuple[torch.Tensor], ...]:
+ is_cross_attention = encoder_hidden_states is not None
+ if past_key_values is not None:
+ if isinstance(past_key_values, EncoderDecoderCache):
+ is_updated = past_key_values.is_updated.get(self.layer_idx)
+ if is_cross_attention:
+ # after the first generated id, we can subsequently re-use all key/value_layer from cache
+ curr_past_key_values = past_key_values.cross_attention_cache
+ else:
+ curr_past_key_values = past_key_values.self_attention_cache
+ else:
+ curr_past_key_values = past_key_values
+
+ if is_cross_attention:
+ if not hasattr(self, "q_attn"):
+ raise ValueError(
+ "If class is used as cross attention, the weights `q_attn` have to be defined. "
+ "Please make sure to instantiate class with `DecisionTransformerGPT2Attention(..., is_cross_attention=True)`."
+ )
+ query_states = self.q_attn(hidden_states)
+ attention_mask = encoder_attention_mask
+
+ # Try to get key/value states from cache if possible
+ if past_key_values is not None and is_updated:
+ key_states = curr_past_key_values.layers[self.layer_idx].keys
+ value_states = curr_past_key_values.layers[self.layer_idx].values
+ else:
+ key_states, value_states = self.c_attn(encoder_hidden_states).split(self.split_size, dim=2)
+ shape_kv = (*key_states.shape[:-1], -1, self.head_dim)
+ key_states = key_states.view(shape_kv).transpose(1, 2)
+ value_states = value_states.view(shape_kv).transpose(1, 2)
+ else:
+ query_states, key_states, value_states = self.c_attn(hidden_states).split(self.split_size, dim=2)
+ shape_kv = (*key_states.shape[:-1], -1, self.head_dim)
+ key_states = key_states.view(shape_kv).transpose(1, 2)
+ value_states = value_states.view(shape_kv).transpose(1, 2)
+
+ shape_q = (*query_states.shape[:-1], -1, self.head_dim)
+ query_states = query_states.view(shape_q).transpose(1, 2)
+
+ if (past_key_values is not None and not is_cross_attention) or (
+ past_key_values is not None and is_cross_attention and not is_updated
+ ):
+ key_states, value_states = curr_past_key_values.update(key_states, value_states, self.layer_idx)
+ # set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls
+ if is_cross_attention:
+ past_key_values.is_updated[self.layer_idx] = True
+
+ using_eager = self.config._attn_implementation == "eager"
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ if using_eager and self.reorder_and_upcast_attn:
+ attn_output, attn_weights = self._upcast_and_reordered_attn(
+ query_states, key_states, value_states, attention_mask
+ )
+ else:
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_states,
+ key_states,
+ value_states,
+ attention_mask,
+ dropout=self.attn_dropout.p if self.training else 0.0,
+ scaling=self.scaling,
+ **kwargs,
+ )
+
+ attn_output = attn_output.reshape(*attn_output.shape[:-2], -1).contiguous()
+ attn_output = self.c_proj(attn_output)
+ attn_output = self.resid_dropout(attn_output)
+
+ return attn_output, attn_weights
+
+
+# Copied from transformers.models.gpt2.modeling_gpt2.GPT2MLP with GPT2->DecisionTransformerGPT2
+class DecisionTransformerGPT2MLP(nn.Module):
+ def __init__(self, intermediate_size, config):
+ super().__init__()
+ embed_dim = config.hidden_size
+ self.c_fc = Conv1D(intermediate_size, embed_dim)
+ self.c_proj = Conv1D(embed_dim, intermediate_size)
+ self.act = ACT2FN[config.activation_function]
+ self.dropout = nn.Dropout(config.resid_pdrop)
+
+ def forward(self, hidden_states: tuple[torch.FloatTensor] | None) -> torch.FloatTensor:
+ hidden_states = self.c_fc(hidden_states)
+ hidden_states = self.act(hidden_states)
+ hidden_states = self.c_proj(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ return hidden_states
+
+
+# Copied from transformers.models.gpt2.modeling_gpt2.GPT2Block with GPT2->DecisionTransformerGPT2
+class DecisionTransformerGPT2Block(GradientCheckpointingLayer):
+ # Ignore copy
+ def __init__(self, config, layer_idx=None):
+ super().__init__()
+ hidden_size = config.hidden_size
+ inner_dim = config.n_inner if config.n_inner is not None else 4 * hidden_size
+
+ self.ln_1 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
+ self.attn = DecisionTransformerGPT2Attention(config, layer_idx=layer_idx)
+ self.ln_2 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
+
+ if config.add_cross_attention:
+ self.crossattention = DecisionTransformerGPT2Attention(
+ config, is_cross_attention=True, layer_idx=layer_idx
+ )
+ self.ln_cross_attn = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
+
+ self.mlp = DecisionTransformerGPT2MLP(inner_dim, config)
+
+ def forward(
+ self,
+ hidden_states: tuple[torch.FloatTensor] | None,
+ past_key_values: Cache | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ encoder_hidden_states: torch.Tensor | None = None,
+ encoder_attention_mask: torch.FloatTensor | None = None,
+ use_cache: bool | None = False,
+ **kwargs,
+ ) -> torch.Tensor:
+ residual = hidden_states
+ hidden_states = self.ln_1(hidden_states)
+ attn_output, _ = self.attn(
+ hidden_states,
+ past_key_values=past_key_values,
+ attention_mask=attention_mask,
+ use_cache=use_cache,
+ **kwargs,
+ )
+ # residual connection
+ hidden_states = attn_output + residual
+
+ if encoder_hidden_states is not None:
+ # add one self-attention block for cross-attention
+ if not hasattr(self, "crossattention"):
+ raise ValueError(
+ f"If `encoder_hidden_states` are passed, {self} has to be instantiated with "
+ "cross-attention layers by setting `config.add_cross_attention=True`"
+ )
+ residual = hidden_states
+ hidden_states = self.ln_cross_attn(hidden_states)
+ cross_attn_output, _ = self.crossattention(
+ hidden_states,
+ past_key_values=past_key_values,
+ attention_mask=attention_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ )
+ # residual connection
+ hidden_states = residual + cross_attn_output
+
+ residual = hidden_states
+ hidden_states = self.ln_2(hidden_states)
+ feed_forward_hidden_states = self.mlp(hidden_states)
+ # residual connection
+ hidden_states = residual + feed_forward_hidden_states
+
+ return hidden_states
+
+
+@auto_docstring
+class DecisionTransformerGPT2PreTrainedModel(PreTrainedModel):
+ config: DecisionTransformerConfig
+ base_model_prefix = "transformer"
+ supports_gradient_checkpointing = True
+ _can_compile_fullgraph = False
+ _can_record_outputs = {
+ "hidden_states": DecisionTransformerGPT2Block,
+ "attentions": OutputRecorder(DecisionTransformerGPT2Attention, layer_name=".attn", index=1),
+ "cross_attentions": OutputRecorder(DecisionTransformerGPT2Attention, layer_name=".crossattention", index=1),
+ }
+
+ # No longer used as we directly use our masks instead
+ _keys_to_ignore_on_load_unexpected = ["attn.bias", "crossattention.bias"]
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ """Initialize the weights."""
+ super()._init_weights(module)
+
+ # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
+ # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
+ # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
+ # > -- GPT-2 :: https://openai.com/blog/better-language-models/
+ #
+ # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
+ if isinstance(module, PreTrainedModel):
+ for name, p in module.named_parameters():
+ if "c_proj" in name and "weight" in name:
+ # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
+ init.normal_(p, mean=0.0, std=self.config.initializer_range / math.sqrt(2 * self.config.n_layer))
+
+
+class DecisionTransformerGPT2Model(DecisionTransformerGPT2PreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.embed_dim = config.hidden_size
+
+ self.wte = nn.Embedding(config.vocab_size, self.embed_dim)
+ self.wpe = nn.Embedding(config.max_position_embeddings, self.embed_dim)
+
+ self.drop = nn.Dropout(config.embd_pdrop)
+ self.h = nn.ModuleList(
+ [DecisionTransformerGPT2Block(config, layer_idx=i) for i in range(config.num_hidden_layers)]
+ )
+ self.ln_f = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_epsilon)
+
+ self.gradient_checkpointing = False
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.wte
+
+ def set_input_embeddings(self, new_embeddings):
+ self.wte = new_embeddings
+
+ @merge_with_config_defaults
+ @capture_outputs
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ encoder_hidden_states: torch.Tensor | None = None,
+ encoder_attention_mask: torch.FloatTensor | None = None,
+ use_cache: bool | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> BaseModelOutputWithPastAndCrossAttentions:
+ if (input_ids is None) ^ (inputs_embeds is not None):
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
+
+ if inputs_embeds is None:
+ inputs_embeds = self.wte(input_ids)
+
+ if token_type_ids is not None:
+ token_type_ids = token_type_ids.view(-1, inputs_embeds.shape[1])
+
+ # based on pattern from src/transformers/models/whisper/modeling_whisper.py::WhisperDecoder and similar addition in GPT2Model
+ if use_cache:
+ if past_key_values is None:
+ past_key_values = DynamicCache(config=self.config)
+
+ if self.config.add_cross_attention and not isinstance(past_key_values, EncoderDecoderCache):
+ past_key_values = EncoderDecoderCache(past_key_values, DynamicCache(config=self.config))
+
+ if position_ids is None:
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
+ position_ids = position_ids.unsqueeze(0)
+
+ # Attention mask.
+ attention_mask = create_causal_mask(
+ config=self.config,
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ position_ids=position_ids,
+ )
+
+ encoder_attention_mask = None
+ if encoder_hidden_states is not None:
+ encoder_attention_mask = create_bidirectional_mask(
+ config=self.config,
+ inputs_embeds=inputs_embeds,
+ attention_mask=encoder_attention_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ )
+
+ position_embeds = self.wpe(position_ids)
+ hidden_states = inputs_embeds + position_embeds
+
+ if token_type_ids is not None:
+ token_type_embeds = self.wte(token_type_ids)
+ hidden_states = hidden_states + token_type_embeds
+
+ hidden_states = self.drop(hidden_states)
+
+ output_shape = (
+ -1,
+ inputs_embeds.shape[1],
+ ) + (hidden_states.size(-1),)
+
+ for block in self.h:
+ hidden_states = block(
+ hidden_states,
+ past_key_values if not (self.gradient_checkpointing and self.training) else None,
+ attention_mask,
+ encoder_hidden_states, # as a positional argument for gradient checkpointing
+ encoder_attention_mask=encoder_attention_mask,
+ use_cache=use_cache,
+ **kwargs,
+ )
+
+ hidden_states = self.ln_f(hidden_states)
+
+ hidden_states = hidden_states.view(output_shape)
+
+ past_key_values = past_key_values if use_cache else None
+ return BaseModelOutputWithPastAndCrossAttentions(
+ last_hidden_state=hidden_states,
+ past_key_values=past_key_values,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ Base class for model's outputs that also contains a pooling of the last hidden states.
+ """
+)
+@dataclass
+class DecisionTransformerOutput(ModelOutput):
+ r"""
+ state_preds (`torch.FloatTensor` of shape `(batch_size, sequence_length, state_dim)`):
+ Environment state predictions
+ action_preds (`torch.FloatTensor` of shape `(batch_size, sequence_length, action_dim)`):
+ Model action predictions
+ return_preds (`torch.FloatTensor` of shape `(batch_size, sequence_length, 1)`):
+ Predicted returns for each state
+ """
+
+ state_preds: torch.FloatTensor | None = None
+ action_preds: torch.FloatTensor | None = None
+ return_preds: torch.FloatTensor | None = None
+ hidden_states: torch.FloatTensor | None = None
+ attentions: torch.FloatTensor | None = None
+ last_hidden_state: torch.FloatTensor | None = None
+
+
+class DecisionTransformerPreTrainedModel(PreTrainedModel):
+ """
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
+ models.
+ """
+
+ config: DecisionTransformerConfig
+ base_model_prefix = "decision_transformer"
+ main_input_name = "states"
+ supports_gradient_checkpointing = False
+
+
+@auto_docstring(
+ custom_intro="""
+ The Decision Transformer Model
+ """
+)
+class DecisionTransformerModel(DecisionTransformerPreTrainedModel):
+ """
+
+ The model builds upon the GPT2 architecture to perform autoregressive prediction of actions in an offline RL
+ setting. Refer to the paper for more details: https://huggingface.co/papers/2106.01345
+
+ """
+
+ def __init__(self, config):
+ super().__init__(config)
+ self.config = config
+ self.hidden_size = config.hidden_size
+ # note: the only difference between this GPT2Model and the default Huggingface version
+ # is that the positional embeddings are removed (since we'll add those ourselves)
+ self.encoder = DecisionTransformerGPT2Model(config)
+
+ self.embed_timestep = nn.Embedding(config.max_ep_len, config.hidden_size)
+ self.embed_return = torch.nn.Linear(1, config.hidden_size)
+ self.embed_state = torch.nn.Linear(config.state_dim, config.hidden_size)
+ self.embed_action = torch.nn.Linear(config.act_dim, config.hidden_size)
+
+ self.embed_ln = nn.LayerNorm(config.hidden_size)
+
+ # note: we don't predict states or returns for the paper
+ self.predict_state = torch.nn.Linear(config.hidden_size, config.state_dim)
+ self.predict_action = nn.Sequential(
+ *([nn.Linear(config.hidden_size, config.act_dim)] + ([nn.Tanh()] if config.action_tanh else []))
+ )
+ self.predict_return = torch.nn.Linear(config.hidden_size, 1)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ states: torch.FloatTensor | None = None,
+ actions: torch.FloatTensor | None = None,
+ rewards: torch.FloatTensor | None = None,
+ returns_to_go: torch.FloatTensor | None = None,
+ timesteps: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ output_hidden_states: bool | None = None,
+ output_attentions: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple[torch.FloatTensor] | DecisionTransformerOutput:
+ r"""
+ states (`torch.FloatTensor` of shape `(batch_size, episode_length, state_dim)`):
+ The states for each step in the trajectory
+ actions (`torch.FloatTensor` of shape `(batch_size, episode_length, act_dim)`):
+ The actions taken by the "expert" policy for the current state, these are masked for auto regressive
+ prediction
+ rewards (`torch.FloatTensor` of shape `(batch_size, episode_length, 1)`):
+ The rewards for each state, action
+ returns_to_go (`torch.FloatTensor` of shape `(batch_size, episode_length, 1)`):
+ The returns for each state in the trajectory
+ timesteps (`torch.LongTensor` of shape `(batch_size, episode_length)`):
+ The timestep for each step in the trajectory
+
+ Examples:
+
+ ```python
+ >>> from transformers import DecisionTransformerModel
+ >>> import torch
+
+ >>> model = DecisionTransformerModel.from_pretrained("edbeeching/decision-transformer-gym-hopper-medium")
+ >>> # evaluation
+ >>> model = model.to(device)
+ >>> model.eval()
+
+ >>> env = gym.make("Hopper-v3")
+ >>> state_dim = env.observation_space.shape[0]
+ >>> act_dim = env.action_space.shape[0]
+
+ >>> state = env.reset()
+ >>> states = torch.from_numpy(state).reshape(1, 1, state_dim).to(device=device, dtype=torch.float32)
+ >>> actions = torch.zeros((1, 1, act_dim), device=device, dtype=torch.float32)
+ >>> rewards = torch.zeros(1, 1, device=device, dtype=torch.float32)
+ >>> target_return = torch.tensor(TARGET_RETURN, dtype=torch.float32).reshape(1, 1)
+ >>> timesteps = torch.tensor(0, device=device, dtype=torch.long).reshape(1, 1)
+ >>> attention_mask = torch.zeros(1, 1, device=device, dtype=torch.float32)
+
+ >>> # forward pass
+ >>> with torch.no_grad():
+ ... state_preds, action_preds, return_preds = model(
+ ... states=states,
+ ... actions=actions,
+ ... rewards=rewards,
+ ... returns_to_go=target_return,
+ ... timesteps=timesteps,
+ ... attention_mask=attention_mask,
+ ... return_dict=False,
+ ... )
+ ```"""
+
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ batch_size, seq_length = states.shape[0], states.shape[1]
+
+ if attention_mask is None:
+ # attention mask for GPT: 1 if can be attended to, 0 if not
+ attention_mask = torch.ones((batch_size, seq_length), dtype=torch.long)
+
+ # embed each modality with a different head
+ state_embeddings = self.embed_state(states)
+ action_embeddings = self.embed_action(actions)
+ returns_embeddings = self.embed_return(returns_to_go)
+ time_embeddings = self.embed_timestep(timesteps)
+
+ # time embeddings are treated similar to positional embeddings
+ state_embeddings = state_embeddings + time_embeddings
+ action_embeddings = action_embeddings + time_embeddings
+ returns_embeddings = returns_embeddings + time_embeddings
+
+ # this makes the sequence look like (R_1, s_1, a_1, R_2, s_2, a_2, ...)
+ # which works nice in an autoregressive sense since states predict actions
+ stacked_inputs = (
+ torch.stack((returns_embeddings, state_embeddings, action_embeddings), dim=1)
+ .permute(0, 2, 1, 3)
+ .reshape(batch_size, 3 * seq_length, self.hidden_size)
+ )
+ stacked_inputs = self.embed_ln(stacked_inputs)
+
+ # to make the attention mask fit the stacked inputs, have to stack it as well
+ stacked_attention_mask = (
+ torch.stack((attention_mask, attention_mask, attention_mask), dim=1)
+ .permute(0, 2, 1)
+ .reshape(batch_size, 3 * seq_length)
+ )
+ device = stacked_inputs.device
+ # we feed in the input embeddings (not word indices as in NLP) to the model
+ encoder_outputs = self.encoder(
+ inputs_embeds=stacked_inputs,
+ attention_mask=stacked_attention_mask,
+ position_ids=torch.zeros(stacked_attention_mask.shape, device=device, dtype=torch.long),
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+ x = encoder_outputs[0]
+
+ # reshape x so that the second dimension corresponds to the original
+ # returns (0), states (1), or actions (2); i.e. x[:,1,t] is the token for s_t
+ x = x.reshape(batch_size, seq_length, 3, self.hidden_size).permute(0, 2, 1, 3)
+
+ # get predictions
+ return_preds = self.predict_return(x[:, 2]) # predict next return given state and action
+ state_preds = self.predict_state(x[:, 2]) # predict next state given state and action
+ action_preds = self.predict_action(x[:, 1]) # predict next action given state
+ if not return_dict:
+ return (state_preds, action_preds, return_preds)
+
+ return DecisionTransformerOutput(
+ last_hidden_state=encoder_outputs.last_hidden_state,
+ state_preds=state_preds,
+ action_preds=action_preds,
+ return_preds=return_preds,
+ hidden_states=encoder_outputs.hidden_states,
+ attentions=encoder_outputs.attentions,
+ )
+
+
+__all__ = [
+ "DecisionTransformerGPT2Model",
+ "DecisionTransformerGPT2PreTrainedModel",
+ "DecisionTransformerModel",
+ "DecisionTransformerPreTrainedModel",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/deepseek_v3/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/deepseek_v3/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..298f4c968375e6d90728a3d4e78c5046e4591c01
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/deepseek_v3/__init__.py
@@ -0,0 +1,27 @@
+# Copyright 2025 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_deepseek_v3 import *
+ from .modeling_deepseek_v3 import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/deepseek_v3/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/deepseek_v3/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2abc6d9dbd57b071a0ded874812e87ab6ffd0606
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/deepseek_v3/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/deepseek_v3/__pycache__/configuration_deepseek_v3.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/deepseek_v3/__pycache__/configuration_deepseek_v3.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d2ae430040d588c34db9d2b80868dd09c5bde671
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/deepseek_v3/__pycache__/configuration_deepseek_v3.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/deepseek_v3/__pycache__/modeling_deepseek_v3.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/deepseek_v3/__pycache__/modeling_deepseek_v3.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b037048641a36d1a4abad96d1606939bd40abc8f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/deepseek_v3/__pycache__/modeling_deepseek_v3.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/deepseek_v3/__pycache__/modular_deepseek_v3.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/deepseek_v3/__pycache__/modular_deepseek_v3.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d94e59e495c86da363d890923486cc54b4e04f38
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/deepseek_v3/__pycache__/modular_deepseek_v3.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/deepseek_v3/configuration_deepseek_v3.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/deepseek_v3/configuration_deepseek_v3.py
new file mode 100644
index 0000000000000000000000000000000000000000..4178547a5ff230c0694e07f2068c544c8c62665c
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/deepseek_v3/configuration_deepseek_v3.py
@@ -0,0 +1,115 @@
+# Copyright 2025 bzantium and the HuggingFace Inc. team. All rights reserved.
+#
+# This code is based on the DeepSeekV3 implementations from the DeepSeek AI team. (https://huggingface.co/deepseek-ai/DeepSeek-V3)
+
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""DeepSeekV3 model configuration"""
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...modeling_rope_utils import RopeParameters
+from ...utils import auto_docstring
+
+
+@auto_docstring(checkpoint="bzantium/tiny-deepseek-v3")
+@strict
+class DeepseekV3Config(PreTrainedConfig):
+ r"""
+ n_group (`int`, *optional*, defaults to 8):
+ Number of groups for routed experts.
+ first_k_dense_replace (`int`, *optional*, defaults to 3):
+ Number of dense layers in shallow layers(embed->dense->dense->...->dense->moe->moe...->lm_head).
+ \--k dense layers--/
+ rope_interleave (`bool`, *optional*, defaults to `True`):
+ Whether to interleave the rotary position embeddings.
+
+ Example:
+
+ ```python
+ >>> from transformers import DeepseekV3Model, DeepseekV3Config
+
+ >>> # Initializing a Deepseek-V3 style configuration
+ >>> configuration = DeepseekV3Config()
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "deepseek_v3"
+ keys_to_ignore_at_inference = ["past_key_values"]
+ base_model_tp_plan = {
+ "layers.*.mlp.experts.gate_up_proj": "packed_colwise",
+ "layers.*.mlp.experts.down_proj": "rowwise",
+ "layers.*.mlp.experts": "moe_tp_experts",
+ "layers.*.mlp.shared_experts.gate_proj": "colwise",
+ "layers.*.mlp.shared_experts.up_proj": "colwise",
+ "layers.*.mlp.shared_experts.down_proj": "rowwise",
+ "layers.*.mlp.gate_proj": "colwise",
+ "layers.*.mlp.up_proj": "colwise",
+ "layers.*.mlp.down_proj": "rowwise",
+ }
+ base_model_pp_plan = {
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
+ "norm": (["hidden_states"], ["hidden_states"]),
+ }
+ attribute_map = {
+ "num_local_experts": "n_routed_experts",
+ }
+
+ vocab_size: int = 129280
+ hidden_size: int = 7168
+ intermediate_size: int = 18432
+ moe_intermediate_size: int = 2048
+ num_hidden_layers: int = 61
+ num_attention_heads: int = 128
+ num_key_value_heads: int | None = 128
+ n_shared_experts: int = 1
+ n_routed_experts: int = 256
+ routed_scaling_factor: float = 2.5
+ kv_lora_rank: int = 512
+ q_lora_rank: int | None = 1536
+ qk_rope_head_dim: int = 64
+ v_head_dim: int | None = 128
+ qk_nope_head_dim: int = 128
+ n_group: int | None = 8
+ topk_group: int | None = 4
+ num_experts_per_tok: int | None = 8
+ first_k_dense_replace: int | None = 3
+ norm_topk_prob: bool | None = True
+ hidden_act: str = "silu"
+ max_position_embeddings: int = 4096
+ initializer_range: float = 0.02
+ rms_norm_eps: float = 1e-6
+ use_cache: bool = True
+ pad_token_id: int | None = None
+ bos_token_id: int | None = 0
+ eos_token_id: int | list[int] | None = 1
+ pretraining_tp: int | None = 1
+ tie_word_embeddings: bool = False
+ rope_parameters: RopeParameters | dict | None = None
+ rope_interleave: bool | None = True
+ attention_bias: bool = False
+ attention_dropout: float | int | None = 0.0
+
+ def __post_init__(self, **kwargs):
+ if self.num_key_value_heads is None:
+ self.num_key_value_heads = self.num_attention_heads
+
+ self.qk_head_dim = self.qk_nope_head_dim + self.qk_rope_head_dim
+ self.head_dim = self.qk_rope_head_dim
+ super().__post_init__(**kwargs)
+
+
+__all__ = ["DeepseekV3Config"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/deepseek_v3/modeling_deepseek_v3.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/deepseek_v3/modeling_deepseek_v3.py
new file mode 100644
index 0000000000000000000000000000000000000000..fe3acd9aeddd7c050a72dfcc02760e5eea23f632
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/deepseek_v3/modeling_deepseek_v3.py
@@ -0,0 +1,722 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/deepseek_v3/modular_deepseek_v3.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_deepseek_v3.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+import math
+from collections.abc import Callable
+from typing import Optional
+
+import torch
+import torch.nn.functional as F
+from torch import nn
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...cache_utils import Cache, DynamicCache
+from ...generation import GenerationMixin
+from ...integrations import use_experts_implementation, use_kernel_forward_from_hub, use_kernel_func_from_hub
+from ...masking_utils import create_causal_mask
+from ...modeling_flash_attention_utils import FlashAttentionKwargs
+from ...modeling_layers import (
+ GenericForSequenceClassification,
+ GenericForTokenClassification,
+ GradientCheckpointingLayer,
+)
+from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
+from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import TransformersKwargs, auto_docstring, can_return_tuple
+from ...utils.generic import is_flash_attention_requested, maybe_autocast, merge_with_config_defaults
+from ...utils.output_capturing import capture_outputs
+from .configuration_deepseek_v3 import DeepseekV3Config
+
+
+@use_kernel_forward_from_hub("RMSNorm")
+class DeepseekV3RMSNorm(nn.Module):
+ def __init__(self, hidden_size, eps: float = 1e-6) -> None:
+ """
+ DeepseekV3RMSNorm is equivalent to T5LayerNorm
+ """
+ super().__init__()
+ self.weight = nn.Parameter(torch.ones(hidden_size))
+ self.variance_epsilon = eps
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ input_dtype = hidden_states.dtype
+ hidden_states = hidden_states.to(torch.float32)
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
+ return self.weight * hidden_states.to(input_dtype)
+
+ def extra_repr(self):
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
+
+
+class DeepseekV3RotaryEmbedding(nn.Module):
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
+
+ def __init__(self, config: DeepseekV3Config, device=None):
+ super().__init__()
+ self.max_seq_len_cached = config.max_position_embeddings
+ self.original_max_seq_len = config.max_position_embeddings
+
+ self.config = config
+
+ self.rope_type = self.config.rope_parameters["rope_type"]
+ rope_init_fn: Callable = self.compute_default_rope_parameters
+ if self.rope_type != "default":
+ rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
+ inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
+
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
+ self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
+
+ @staticmethod
+ def compute_default_rope_parameters(
+ config: DeepseekV3Config | None = None,
+ device: Optional["torch.device"] = None,
+ seq_len: int | None = None,
+ ) -> tuple["torch.Tensor", float]:
+ """
+ Computes the inverse frequencies according to the original RoPE implementation
+ Args:
+ config ([`~transformers.PreTrainedConfig`]):
+ The model configuration.
+ device (`torch.device`):
+ The device to use for initialization of the inverse frequencies.
+ seq_len (`int`, *optional*):
+ The current sequence length. Unused for this type of RoPE.
+ Returns:
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
+ """
+ base = config.rope_parameters["rope_theta"]
+ dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
+
+ attention_factor = 1.0 # Unused in this type of RoPE
+
+ # Compute the inverse frequencies
+ inv_freq = 1.0 / (
+ base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
+ )
+ return inv_freq, attention_factor
+
+ @torch.no_grad()
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
+ def forward(self, x, position_ids):
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
+ position_ids_expanded = position_ids[:, None, :].float()
+
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
+ with maybe_autocast(device_type=device_type, enabled=False): # Force float32
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
+ emb = torch.cat((freqs, freqs), dim=-1)
+ cos = emb.cos() * self.attention_scaling
+ sin = emb.sin() * self.attention_scaling
+
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
+
+
+class DeepseekV3MLP(nn.Module):
+ def __init__(self, config, intermediate_size=None):
+ super().__init__()
+ self.config = config
+ self.hidden_size = config.hidden_size
+ self.intermediate_size = config.intermediate_size if intermediate_size is None else intermediate_size
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
+ self.act_fn = ACT2FN[config.hidden_act]
+
+ def forward(self, x):
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
+ return down_proj
+
+
+class DeepseekV3TopkRouter(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.n_routed_experts = config.n_routed_experts
+
+ self.weight = nn.Parameter(torch.empty((self.n_routed_experts, config.hidden_size)))
+ self.register_buffer("e_score_correction_bias", torch.zeros(self.n_routed_experts))
+
+ def forward(self, hidden_states):
+ hidden_states = hidden_states.view(-1, self.config.hidden_size)
+ router_logits = F.linear(hidden_states.type(torch.float32), self.weight.type(torch.float32))
+ return router_logits
+
+
+@use_experts_implementation
+class DeepseekV3NaiveMoe(nn.Module):
+ """Collection of expert weights stored as 3D tensors."""
+
+ def __init__(self, config):
+ super().__init__()
+ self.num_experts = config.num_local_experts
+ self.hidden_dim = config.hidden_size
+ self.intermediate_dim = config.moe_intermediate_size
+ self.gate_up_proj = nn.Parameter(torch.empty(self.num_experts, 2 * self.intermediate_dim, self.hidden_dim))
+ self.down_proj = nn.Parameter(torch.empty(self.num_experts, self.hidden_dim, self.intermediate_dim))
+ self.act_fn = ACT2FN[config.hidden_act]
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ top_k_index: torch.Tensor,
+ top_k_weights: torch.Tensor,
+ ) -> torch.Tensor:
+ final_hidden_states = torch.zeros_like(hidden_states)
+ with torch.no_grad():
+ expert_mask = torch.nn.functional.one_hot(top_k_index, num_classes=self.num_experts)
+ expert_mask = expert_mask.permute(2, 1, 0)
+ expert_hit = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero()
+
+ for expert_idx in expert_hit:
+ expert_idx = expert_idx[0]
+ if expert_idx == self.num_experts:
+ continue
+ top_k_pos, token_idx = torch.where(expert_mask[expert_idx])
+ current_state = hidden_states[token_idx]
+ gate, up = nn.functional.linear(current_state, self.gate_up_proj[expert_idx]).chunk(2, dim=-1)
+ current_hidden_states = self.act_fn(gate) * up
+ current_hidden_states = nn.functional.linear(current_hidden_states, self.down_proj[expert_idx])
+ current_hidden_states = current_hidden_states * top_k_weights[token_idx, top_k_pos, None]
+ final_hidden_states.index_add_(0, token_idx, current_hidden_states.to(final_hidden_states.dtype))
+
+ return final_hidden_states
+
+
+class DeepseekV3MoE(nn.Module):
+ """
+ A mixed expert module containing shared experts.
+ """
+
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.experts = DeepseekV3NaiveMoe(config)
+ self.gate = DeepseekV3TopkRouter(config)
+ self.shared_experts = DeepseekV3MLP(
+ config=config, intermediate_size=config.moe_intermediate_size * config.n_shared_experts
+ )
+ self.n_routed_experts = config.n_routed_experts
+ self.n_group = config.n_group
+ self.topk_group = config.topk_group
+ self.norm_topk_prob = config.norm_topk_prob
+ self.routed_scaling_factor = config.routed_scaling_factor
+ self.top_k = config.num_experts_per_tok
+
+ def route_tokens_to_experts(self, router_logits):
+ router_logits = router_logits.sigmoid()
+ router_logits_for_choice = router_logits + self.gate.e_score_correction_bias
+ group_scores = (
+ router_logits_for_choice.view(-1, self.n_group, self.n_routed_experts // self.n_group)
+ .topk(2, dim=-1)[0]
+ .sum(dim=-1)
+ )
+ group_idx = torch.topk(group_scores, k=self.topk_group, dim=-1, sorted=False)[1]
+ group_mask = torch.zeros_like(group_scores)
+ group_mask.scatter_(1, group_idx, 1)
+ score_mask = (
+ group_mask.unsqueeze(-1)
+ .expand(-1, self.n_group, self.n_routed_experts // self.n_group)
+ .reshape(-1, self.n_routed_experts)
+ )
+ scores_for_choice = router_logits_for_choice.masked_fill(~score_mask.bool(), float("-inf"))
+ topk_indices = torch.topk(scores_for_choice, k=self.top_k, dim=-1, sorted=False)[1]
+ topk_weights = router_logits.gather(1, topk_indices)
+ if self.norm_topk_prob:
+ denominator = topk_weights.sum(dim=-1, keepdim=True) + 1e-20
+ topk_weights /= denominator
+ topk_weights = topk_weights * self.routed_scaling_factor
+ return topk_indices, topk_weights
+
+ def forward(self, hidden_states):
+ residuals = hidden_states
+ orig_shape = hidden_states.shape
+ router_logits = self.gate(hidden_states)
+ topk_indices, topk_weights = self.route_tokens_to_experts(router_logits)
+ hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
+ hidden_states = self.experts(hidden_states, topk_indices, topk_weights).view(*orig_shape)
+ hidden_states = hidden_states + self.shared_experts(residuals)
+ return hidden_states
+
+
+def rotate_half(x):
+ """Rotates half the hidden dims of the input."""
+ x1 = x[..., : x.shape[-1] // 2]
+ x2 = x[..., x.shape[-1] // 2 :]
+ return torch.cat((-x2, x1), dim=-1)
+
+
+@use_kernel_func_from_hub("rotary_pos_emb")
+def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
+ """Applies Rotary Position Embedding to the query and key tensors.
+
+ Args:
+ q (`torch.Tensor`): The query tensor.
+ k (`torch.Tensor`): The key tensor.
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
+ Returns:
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
+ """
+ cos = cos.unsqueeze(unsqueeze_dim)
+ sin = sin.unsqueeze(unsqueeze_dim)
+ q_embed = (q * cos) + (rotate_half(q) * sin)
+ k_embed = (k * cos) + (rotate_half(k) * sin)
+ return q_embed, k_embed
+
+
+def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
+ """
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
+ """
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
+ if n_rep == 1:
+ return hidden_states
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
+
+
+def eager_attention_forward(
+ module: nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: torch.Tensor | None,
+ scaling: float,
+ dropout: float = 0.0,
+ **kwargs: Unpack[TransformersKwargs],
+):
+ key_states = repeat_kv(key, module.num_key_value_groups)
+ value_states = repeat_kv(value, module.num_key_value_groups)
+
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
+ if attention_mask is not None:
+ attn_weights = attn_weights + attention_mask
+
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
+ attn_output = torch.matmul(attn_weights, value_states)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+
+ return attn_output, attn_weights
+
+
+def apply_rotary_pos_emb_interleave(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
+ r"""
+ TODO let's just use the original freqcis computation to not have the view
+ transpose + reshape! This is not optimized!
+ Applies Rotary Position Embedding to the query and key tensors.
+
+ Args:
+ q (`torch.Tensor`): The query tensor.
+ k (`torch.Tensor`): The key tensor.
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
+ position_ids (`torch.Tensor`):
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
+ used to pass offsetted position ids when working with a KV-cache.
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
+ Returns:
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
+ """
+ cos = cos.unsqueeze(unsqueeze_dim)
+ sin = sin.unsqueeze(unsqueeze_dim)
+
+ b, h, s, d = q.shape
+ q = q.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
+
+ b, h, s, d = k.shape
+ k = k.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
+
+ q_embed = (q * cos) + (rotate_half(q) * sin)
+ k_embed = (k * cos) + (rotate_half(k) * sin)
+ return q_embed, k_embed
+
+
+def yarn_get_mscale(scale=1, mscale=1):
+ if scale <= 1:
+ return 1.0
+ return 0.1 * mscale * math.log(scale) + 1.0
+
+
+class DeepseekV3Attention(nn.Module):
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
+
+ def __init__(self, config: DeepseekV3Config, layer_idx: int):
+ super().__init__()
+ self.config = config
+ self.layer_idx = layer_idx
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
+ self.attention_dropout = config.attention_dropout
+ self.num_heads = config.num_attention_heads
+
+ self.q_lora_rank = config.q_lora_rank
+ self.qk_rope_head_dim = config.qk_rope_head_dim
+ self.kv_lora_rank = config.kv_lora_rank
+ self.v_head_dim = config.v_head_dim
+ self.qk_nope_head_dim = config.qk_nope_head_dim
+ self.qk_head_dim = config.qk_head_dim
+
+ self.is_causal = True
+ if self.q_lora_rank is None:
+ self.q_proj = nn.Linear(config.hidden_size, self.num_heads * self.qk_head_dim, bias=False)
+ else:
+ self.q_a_proj = nn.Linear(config.hidden_size, config.q_lora_rank, bias=config.attention_bias)
+ self.q_a_layernorm = DeepseekV3RMSNorm(config.q_lora_rank)
+ self.q_b_proj = nn.Linear(config.q_lora_rank, self.num_heads * self.qk_head_dim, bias=False)
+
+ self.kv_a_proj_with_mqa = nn.Linear(
+ config.hidden_size,
+ self.kv_lora_rank + self.qk_rope_head_dim,
+ bias=config.attention_bias,
+ )
+ self.kv_a_layernorm = DeepseekV3RMSNorm(self.kv_lora_rank)
+ self.kv_b_proj = nn.Linear(
+ self.kv_lora_rank,
+ self.num_heads * (self.qk_nope_head_dim + self.v_head_dim),
+ bias=False,
+ )
+
+ self.o_proj = nn.Linear(
+ self.num_heads * self.v_head_dim,
+ config.hidden_size,
+ bias=config.attention_bias,
+ )
+
+ self.scaling = self.qk_head_dim ** (-0.5)
+ if self.config.rope_parameters.get("rope_type", "default") != "default":
+ mscale_all_dim = self.config.rope_parameters.get("mscale_all_dim", 0)
+ scaling_factor = self.config.rope_parameters["factor"]
+ if mscale_all_dim:
+ mscale = yarn_get_mscale(scaling_factor, mscale_all_dim)
+ self.scaling = self.scaling * mscale * mscale
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
+ attention_mask: torch.Tensor | None,
+ past_key_values: Cache | None = None,
+ **kwargs: Unpack[FlashAttentionKwargs],
+ ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
+ batch_size, seq_length = hidden_states.shape[:-1]
+ query_shape = (batch_size, seq_length, -1, self.qk_head_dim)
+ key_shape = (batch_size, seq_length, -1, self.qk_nope_head_dim + self.v_head_dim)
+
+ if self.q_lora_rank is None:
+ q_states = self.q_proj(hidden_states)
+ else:
+ q_states = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
+ q_states = q_states.view(query_shape).transpose(1, 2)
+ q_pass, q_rot = torch.split(q_states, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1)
+
+ compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
+ k_pass, k_rot = torch.split(compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1)
+
+ k_pass = self.kv_b_proj(self.kv_a_layernorm(k_pass)).view(key_shape).transpose(1, 2)
+ k_pass, value_states = torch.split(k_pass, [self.qk_nope_head_dim, self.v_head_dim], dim=-1)
+
+ k_rot = k_rot.view(batch_size, 1, seq_length, self.qk_rope_head_dim)
+
+ cos, sin = position_embeddings
+ if self.config.rope_interleave: # support using interleaved weights for efficiency
+ q_rot, k_rot = apply_rotary_pos_emb_interleave(q_rot, k_rot, cos, sin)
+ else:
+ q_rot, k_rot = apply_rotary_pos_emb(q_rot, k_rot, cos, sin)
+ k_rot = k_rot.expand(*k_pass.shape[:-1], -1)
+
+ query_states = torch.cat((q_pass, q_rot), dim=-1)
+ key_states = torch.cat((k_pass, k_rot), dim=-1)
+
+ if past_key_values is not None:
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
+
+ if is_flash_attention_requested(self.config) and self.qk_head_dim != self.v_head_dim:
+ value_states = F.pad(value_states, [0, self.qk_head_dim - self.v_head_dim])
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_states,
+ key_states,
+ value_states,
+ attention_mask,
+ dropout=0.0 if not self.training else self.attention_dropout,
+ scaling=self.scaling,
+ **kwargs,
+ )
+
+ if is_flash_attention_requested(self.config) and self.qk_head_dim != self.v_head_dim:
+ attn_output = attn_output[:, :, :, : self.v_head_dim]
+
+ attn_output = attn_output.reshape(batch_size, seq_length, -1).contiguous()
+ attn_output = self.o_proj(attn_output)
+ return attn_output, attn_weights
+
+
+class DeepseekV3DecoderLayer(GradientCheckpointingLayer):
+ def __init__(self, config: DeepseekV3Config, layer_idx: int):
+ super().__init__()
+ self.hidden_size = config.hidden_size
+
+ self.self_attn = DeepseekV3Attention(config=config, layer_idx=layer_idx)
+
+ if layer_idx >= config.first_k_dense_replace:
+ self.mlp = DeepseekV3MoE(config)
+ else:
+ self.mlp = DeepseekV3MLP(config)
+
+ self.input_layernorm = DeepseekV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.post_attention_layernorm = DeepseekV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ use_cache: bool | None = False,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.Tensor:
+ residual = hidden_states
+ hidden_states = self.input_layernorm(hidden_states)
+ # Self Attention
+ hidden_states, _ = self.self_attn(
+ hidden_states=hidden_states,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ position_embeddings=position_embeddings,
+ **kwargs,
+ )
+ hidden_states = residual + hidden_states
+
+ # Fully Connected
+ residual = hidden_states
+ hidden_states = self.post_attention_layernorm(hidden_states)
+ hidden_states = self.mlp(hidden_states)
+ hidden_states = residual + hidden_states
+ return hidden_states
+
+
+@auto_docstring
+class DeepseekV3PreTrainedModel(PreTrainedModel):
+ config: DeepseekV3Config
+ base_model_prefix = "model"
+ supports_gradient_checkpointing = True
+ _no_split_modules = ["DeepseekV3DecoderLayer"]
+ _skip_keys_device_placement = ["past_key_values"]
+ _supports_flash_attn = True
+ _supports_sdpa = True
+ _supports_flex_attn = True
+
+ _can_compile_fullgraph = True
+ _supports_attention_backend = True
+ _can_record_outputs = {
+ "hidden_states": DeepseekV3DecoderLayer,
+ "attentions": DeepseekV3Attention,
+ }
+ _keep_in_fp32_modules_strict = ["e_score_correction_bias"]
+ _keys_to_ignore_on_load_unexpected = [r"model\.layers\.61.*"]
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ super()._init_weights(module)
+ if isinstance(module, DeepseekV3TopkRouter):
+ init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
+ init.zeros_(module.e_score_correction_bias)
+ elif isinstance(module, DeepseekV3NaiveMoe):
+ init.normal_(module.gate_up_proj, mean=0.0, std=self.config.initializer_range)
+ init.normal_(module.down_proj, mean=0.0, std=self.config.initializer_range)
+
+
+@auto_docstring
+class DeepseekV3Model(DeepseekV3PreTrainedModel):
+ def __init__(self, config: DeepseekV3Config):
+ super().__init__(config)
+ self.padding_idx = config.pad_token_id
+ self.vocab_size = config.vocab_size
+
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
+ self.layers = nn.ModuleList(
+ [DeepseekV3DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
+ )
+ self.norm = DeepseekV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.rotary_emb = DeepseekV3RotaryEmbedding(config=config)
+ self.gradient_checkpointing = False
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @merge_with_config_defaults
+ @capture_outputs
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ use_cache: bool | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> BaseModelOutputWithPast:
+ if (input_ids is None) ^ (inputs_embeds is not None):
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
+
+ if inputs_embeds is None:
+ inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)
+
+ if use_cache and past_key_values is None:
+ past_key_values = DynamicCache(config=self.config)
+
+ if position_ids is None:
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
+ position_ids = position_ids.unsqueeze(0)
+
+ causal_mask = create_causal_mask(
+ config=self.config,
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ position_ids=position_ids,
+ )
+
+ hidden_states = inputs_embeds
+ position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
+
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
+ hidden_states = decoder_layer(
+ hidden_states,
+ attention_mask=causal_mask,
+ position_embeddings=position_embeddings,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ **kwargs,
+ )
+
+ hidden_states = self.norm(hidden_states)
+ return BaseModelOutputWithPast(
+ last_hidden_state=hidden_states,
+ past_key_values=past_key_values,
+ )
+
+
+@auto_docstring
+class DeepseekV3ForCausalLM(DeepseekV3PreTrainedModel, GenerationMixin):
+ _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
+ _tp_plan = {"lm_head": "colwise_gather_output"}
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
+
+ def __init__(self, config):
+ super().__init__(config)
+ self.model = DeepseekV3Model(config)
+ self.vocab_size = config.vocab_size
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ use_cache: bool | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> CausalLMOutputWithPast:
+ r"""
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, DeepseekV3ForCausalLM
+
+ >>> model = DeepseekV3ForCausalLM.from_pretrained("meta-deepseek_v3/DeepseekV3-2-7b-hf")
+ >>> tokenizer = AutoTokenizer.from_pretrained("meta-deepseek_v3/DeepseekV3-2-7b-hf")
+
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
+
+ >>> # Generate
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
+ ```"""
+ outputs: BaseModelOutputWithPast = self.model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ **kwargs,
+ )
+
+ hidden_states = outputs.last_hidden_state
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
+
+ return CausalLMOutputWithPast(
+ loss=loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+class DeepseekV3ForSequenceClassification(GenericForSequenceClassification, DeepseekV3PreTrainedModel):
+ pass
+
+
+class DeepseekV3ForTokenClassification(GenericForTokenClassification, DeepseekV3PreTrainedModel):
+ pass
+
+
+__all__ = [
+ "DeepseekV3PreTrainedModel",
+ "DeepseekV3Model",
+ "DeepseekV3ForCausalLM",
+ "DeepseekV3ForSequenceClassification",
+ "DeepseekV3ForTokenClassification",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/deepseek_v3/modular_deepseek_v3.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/deepseek_v3/modular_deepseek_v3.py
new file mode 100644
index 0000000000000000000000000000000000000000..2bf7d347e85d27bad36ff7867b9942c2a95e1d3d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/deepseek_v3/modular_deepseek_v3.py
@@ -0,0 +1,340 @@
+import math
+from collections.abc import Callable
+
+import torch
+import torch.nn.functional as F
+from torch import nn
+
+from ... import initialization as init
+from ...cache_utils import Cache
+from ...modeling_flash_attention_utils import FlashAttentionKwargs
+from ...modeling_layers import GenericForSequenceClassification, GenericForTokenClassification
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import logging
+from ...utils.generic import is_flash_attention_requested
+from ..llama.modeling_llama import (
+ LlamaDecoderLayer,
+ LlamaForCausalLM,
+ LlamaModel,
+ LlamaPreTrainedModel,
+ LlamaRMSNorm,
+ LlamaRotaryEmbedding,
+ apply_rotary_pos_emb,
+ eager_attention_forward,
+ rotate_half,
+)
+from ..mixtral.modeling_mixtral import MixtralExperts
+from ..qwen2_moe.modeling_qwen2_moe import Qwen2MoeMLP
+from .configuration_deepseek_v3 import DeepseekV3Config
+
+
+logger = logging.get_logger(__name__)
+
+
+class DeepseekV3RMSNorm(LlamaRMSNorm):
+ pass
+
+
+class DeepseekV3RotaryEmbedding(LlamaRotaryEmbedding):
+ pass
+
+
+class DeepseekV3MLP(Qwen2MoeMLP):
+ pass
+
+
+def apply_rotary_pos_emb_interleave(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
+ r"""
+ TODO let's just use the original freqcis computation to not have the view
+ transpose + reshape! This is not optimized!
+ Applies Rotary Position Embedding to the query and key tensors.
+
+ Args:
+ q (`torch.Tensor`): The query tensor.
+ k (`torch.Tensor`): The key tensor.
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
+ position_ids (`torch.Tensor`):
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
+ used to pass offsetted position ids when working with a KV-cache.
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
+ Returns:
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
+ """
+ cos = cos.unsqueeze(unsqueeze_dim)
+ sin = sin.unsqueeze(unsqueeze_dim)
+
+ b, h, s, d = q.shape
+ q = q.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
+
+ b, h, s, d = k.shape
+ k = k.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
+
+ q_embed = (q * cos) + (rotate_half(q) * sin)
+ k_embed = (k * cos) + (rotate_half(k) * sin)
+ return q_embed, k_embed
+
+
+def yarn_get_mscale(scale=1, mscale=1):
+ if scale <= 1:
+ return 1.0
+ return 0.1 * mscale * math.log(scale) + 1.0
+
+
+class DeepseekV3TopkRouter(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.n_routed_experts = config.n_routed_experts
+
+ self.weight = nn.Parameter(torch.empty((self.n_routed_experts, config.hidden_size)))
+ self.register_buffer("e_score_correction_bias", torch.zeros(self.n_routed_experts))
+
+ def forward(self, hidden_states):
+ hidden_states = hidden_states.view(-1, self.config.hidden_size)
+ router_logits = F.linear(hidden_states.type(torch.float32), self.weight.type(torch.float32))
+ return router_logits
+
+
+class DeepseekV3NaiveMoe(MixtralExperts):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_experts = config.num_local_experts
+ self.intermediate_dim = config.moe_intermediate_size
+
+
+class DeepseekV3MoE(nn.Module):
+ """
+ A mixed expert module containing shared experts.
+ """
+
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.experts = DeepseekV3NaiveMoe(config)
+ self.gate = DeepseekV3TopkRouter(config)
+ self.shared_experts = DeepseekV3MLP(
+ config=config, intermediate_size=config.moe_intermediate_size * config.n_shared_experts
+ )
+ self.n_routed_experts = config.n_routed_experts
+ self.n_group = config.n_group
+ self.topk_group = config.topk_group
+ self.norm_topk_prob = config.norm_topk_prob
+ self.routed_scaling_factor = config.routed_scaling_factor
+ self.top_k = config.num_experts_per_tok
+
+ def route_tokens_to_experts(self, router_logits):
+ router_logits = router_logits.sigmoid()
+ router_logits_for_choice = router_logits + self.gate.e_score_correction_bias
+ group_scores = (
+ router_logits_for_choice.view(-1, self.n_group, self.n_routed_experts // self.n_group)
+ .topk(2, dim=-1)[0]
+ .sum(dim=-1)
+ )
+ group_idx = torch.topk(group_scores, k=self.topk_group, dim=-1, sorted=False)[1]
+ group_mask = torch.zeros_like(group_scores)
+ group_mask.scatter_(1, group_idx, 1)
+ score_mask = (
+ group_mask.unsqueeze(-1)
+ .expand(-1, self.n_group, self.n_routed_experts // self.n_group)
+ .reshape(-1, self.n_routed_experts)
+ )
+ scores_for_choice = router_logits_for_choice.masked_fill(~score_mask.bool(), float("-inf"))
+ topk_indices = torch.topk(scores_for_choice, k=self.top_k, dim=-1, sorted=False)[1]
+ topk_weights = router_logits.gather(1, topk_indices)
+ if self.norm_topk_prob:
+ denominator = topk_weights.sum(dim=-1, keepdim=True) + 1e-20
+ topk_weights /= denominator
+ topk_weights = topk_weights * self.routed_scaling_factor
+ return topk_indices, topk_weights
+
+ def forward(self, hidden_states):
+ residuals = hidden_states
+ orig_shape = hidden_states.shape
+ router_logits = self.gate(hidden_states)
+ topk_indices, topk_weights = self.route_tokens_to_experts(router_logits)
+ hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
+ hidden_states = self.experts(hidden_states, topk_indices, topk_weights).view(*orig_shape)
+ hidden_states = hidden_states + self.shared_experts(residuals)
+ return hidden_states
+
+
+class DeepseekV3Attention(nn.Module):
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
+
+ def __init__(self, config: DeepseekV3Config, layer_idx: int):
+ super().__init__()
+ self.config = config
+ self.layer_idx = layer_idx
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
+ self.attention_dropout = config.attention_dropout
+ self.num_heads = config.num_attention_heads
+
+ self.q_lora_rank = config.q_lora_rank
+ self.qk_rope_head_dim = config.qk_rope_head_dim
+ self.kv_lora_rank = config.kv_lora_rank
+ self.v_head_dim = config.v_head_dim
+ self.qk_nope_head_dim = config.qk_nope_head_dim
+ self.qk_head_dim = config.qk_head_dim
+
+ self.is_causal = True
+ if self.q_lora_rank is None:
+ self.q_proj = nn.Linear(config.hidden_size, self.num_heads * self.qk_head_dim, bias=False)
+ else:
+ self.q_a_proj = nn.Linear(config.hidden_size, config.q_lora_rank, bias=config.attention_bias)
+ self.q_a_layernorm = DeepseekV3RMSNorm(config.q_lora_rank)
+ self.q_b_proj = nn.Linear(config.q_lora_rank, self.num_heads * self.qk_head_dim, bias=False)
+
+ self.kv_a_proj_with_mqa = nn.Linear(
+ config.hidden_size,
+ self.kv_lora_rank + self.qk_rope_head_dim,
+ bias=config.attention_bias,
+ )
+ self.kv_a_layernorm = DeepseekV3RMSNorm(self.kv_lora_rank)
+ self.kv_b_proj = nn.Linear(
+ self.kv_lora_rank,
+ self.num_heads * (self.qk_nope_head_dim + self.v_head_dim),
+ bias=False,
+ )
+
+ self.o_proj = nn.Linear(
+ self.num_heads * self.v_head_dim,
+ config.hidden_size,
+ bias=config.attention_bias,
+ )
+
+ self.scaling = self.qk_head_dim ** (-0.5)
+ if self.config.rope_parameters.get("rope_type", "default") != "default":
+ mscale_all_dim = self.config.rope_parameters.get("mscale_all_dim", 0)
+ scaling_factor = self.config.rope_parameters["factor"]
+ if mscale_all_dim:
+ mscale = yarn_get_mscale(scaling_factor, mscale_all_dim)
+ self.scaling = self.scaling * mscale * mscale
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
+ attention_mask: torch.Tensor | None,
+ past_key_values: Cache | None = None,
+ **kwargs: Unpack[FlashAttentionKwargs],
+ ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
+ batch_size, seq_length = hidden_states.shape[:-1]
+ query_shape = (batch_size, seq_length, -1, self.qk_head_dim)
+ key_shape = (batch_size, seq_length, -1, self.qk_nope_head_dim + self.v_head_dim)
+
+ if self.q_lora_rank is None:
+ q_states = self.q_proj(hidden_states)
+ else:
+ q_states = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
+ q_states = q_states.view(query_shape).transpose(1, 2)
+ q_pass, q_rot = torch.split(q_states, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1)
+
+ compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
+ k_pass, k_rot = torch.split(compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1)
+
+ k_pass = self.kv_b_proj(self.kv_a_layernorm(k_pass)).view(key_shape).transpose(1, 2)
+ k_pass, value_states = torch.split(k_pass, [self.qk_nope_head_dim, self.v_head_dim], dim=-1)
+
+ k_rot = k_rot.view(batch_size, 1, seq_length, self.qk_rope_head_dim)
+
+ cos, sin = position_embeddings
+ if self.config.rope_interleave: # support using interleaved weights for efficiency
+ q_rot, k_rot = apply_rotary_pos_emb_interleave(q_rot, k_rot, cos, sin)
+ else:
+ q_rot, k_rot = apply_rotary_pos_emb(q_rot, k_rot, cos, sin)
+ k_rot = k_rot.expand(*k_pass.shape[:-1], -1)
+
+ query_states = torch.cat((q_pass, q_rot), dim=-1)
+ key_states = torch.cat((k_pass, k_rot), dim=-1)
+
+ if past_key_values is not None:
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
+
+ if is_flash_attention_requested(self.config) and self.qk_head_dim != self.v_head_dim:
+ value_states = F.pad(value_states, [0, self.qk_head_dim - self.v_head_dim])
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_states,
+ key_states,
+ value_states,
+ attention_mask,
+ dropout=0.0 if not self.training else self.attention_dropout,
+ scaling=self.scaling,
+ **kwargs,
+ )
+
+ if is_flash_attention_requested(self.config) and self.qk_head_dim != self.v_head_dim:
+ attn_output = attn_output[:, :, :, : self.v_head_dim]
+
+ attn_output = attn_output.reshape(batch_size, seq_length, -1).contiguous()
+ attn_output = self.o_proj(attn_output)
+ return attn_output, attn_weights
+
+
+class DeepseekV3DecoderLayer(LlamaDecoderLayer):
+ def __init__(self, config: DeepseekV3Config, layer_idx: int):
+ nn.Module.__init__(self)
+ self.hidden_size = config.hidden_size
+
+ self.self_attn = DeepseekV3Attention(config=config, layer_idx=layer_idx)
+
+ if layer_idx >= config.first_k_dense_replace:
+ self.mlp = DeepseekV3MoE(config)
+ else:
+ self.mlp = DeepseekV3MLP(config)
+
+ self.input_layernorm = DeepseekV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.post_attention_layernorm = DeepseekV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+
+
+class DeepseekV3PreTrainedModel(LlamaPreTrainedModel):
+ _keep_in_fp32_modules_strict = ["e_score_correction_bias"]
+ _keys_to_ignore_on_load_unexpected = [r"model\.layers\.61.*"]
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ PreTrainedModel._init_weights(self, module)
+ if isinstance(module, DeepseekV3TopkRouter):
+ init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
+ init.zeros_(module.e_score_correction_bias)
+ elif isinstance(module, DeepseekV3NaiveMoe):
+ init.normal_(module.gate_up_proj, mean=0.0, std=self.config.initializer_range)
+ init.normal_(module.down_proj, mean=0.0, std=self.config.initializer_range)
+
+
+class DeepseekV3Model(LlamaModel):
+ pass
+
+
+class DeepseekV3ForCausalLM(LlamaForCausalLM):
+ pass
+
+
+class DeepseekV3ForSequenceClassification(GenericForSequenceClassification, DeepseekV3PreTrainedModel):
+ pass
+
+
+class DeepseekV3ForTokenClassification(GenericForTokenClassification, DeepseekV3PreTrainedModel):
+ pass
+
+
+__all__ = [
+ "DeepseekV3PreTrainedModel",
+ "DeepseekV3Model",
+ "DeepseekV3ForCausalLM",
+ "DeepseekV3ForSequenceClassification",
+ "DeepseekV3ForTokenClassification",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/deepseek_v4/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/deepseek_v4/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..fe0228917078af929bc7599feb6c64c30253b842
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/deepseek_v4/__init__.py
@@ -0,0 +1,27 @@
+# Copyright 2026 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_deepseek_v4 import *
+ from .modeling_deepseek_v4 import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/deepseek_v4/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/deepseek_v4/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..893b25d77bd2f4c96a3e4178524c72ed0700133a
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/deepseek_v4/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/deepseek_v4/__pycache__/configuration_deepseek_v4.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/deepseek_v4/__pycache__/configuration_deepseek_v4.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e48b8e73d60fdbf4324ea599ae807491d7605176
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/deepseek_v4/__pycache__/configuration_deepseek_v4.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/deepseek_v4/__pycache__/modeling_deepseek_v4.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/deepseek_v4/__pycache__/modeling_deepseek_v4.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..608441207dfd739e796513a3009fade8b6803ea4
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/deepseek_v4/__pycache__/modeling_deepseek_v4.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/deepseek_v4/__pycache__/modular_deepseek_v4.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/deepseek_v4/__pycache__/modular_deepseek_v4.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fa624ba3cbcbe67e0e021af9e4e190aab4a2995c
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/deepseek_v4/__pycache__/modular_deepseek_v4.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/deepseek_v4/configuration_deepseek_v4.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/deepseek_v4/configuration_deepseek_v4.py
new file mode 100644
index 0000000000000000000000000000000000000000..8f8d818d8cedc8052fefed3e8dc0811d887c43b2
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/deepseek_v4/configuration_deepseek_v4.py
@@ -0,0 +1,313 @@
+# Copyright 2026 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...modeling_rope_utils import RopeParameters
+from ...utils import auto_docstring
+
+
+DEEPSEEK_V4_LAYER_TYPES = (
+ "sliding_attention",
+ "compressed_sparse_attention",
+ "heavily_compressed_attention",
+)
+
+
+_COMPRESS_RATIO_TO_LAYER_TYPE = {
+ 0: "sliding_attention",
+ 4: "compressed_sparse_attention",
+ 128: "heavily_compressed_attention",
+}
+
+
+DEEPSEEK_V4_MLP_LAYER_TYPES = ("hash_moe", "moe")
+
+
+@auto_docstring(checkpoint="deepseek-ai/DeepSeek-V4-Flash-Base")
+@strict
+class DeepseekV4Config(PreTrainedConfig):
+ r"""
+ scoring_func (`str`):
+ Router activation — `sqrtsoftplus`, `softmax`, or `sigmoid`.
+ rope_theta (`float`):
+ RoPE base for the main self-attention rotary.
+ layer_types (`list[str]`):
+ Per-layer attention schedule with values from
+ `{"compressed_sparse_attention", "heavily_compressed_attention"}`.
+ V4-Pro default: 2× HCA bootstrap + interleaved CSA / HCA.
+ compress_rates (`dict[str, int]`):
+ Per-layer-type compression rate. Default
+ `{"compressed_sparse_attention": 4, "heavily_compressed_attention": 128}`
+ (m=4 for CSA, m'=128 for HCA, paper §2.3.1 / §2.3.2). BC: configs that ship
+ `compress_rate_csa` / `compress_rate_hca` as top-level kwargs are folded
+ in at `__post_init__` time.
+ compress_rope_theta (`float`):
+ RoPE base for the compressed branches (paired with
+ `rope_scaling` for YaRN).
+ hc_mult (`int`):
+ Manifold-Constrained Hyper-Connection (mHC) expansion factor n_hc
+ (always active; Section 2.2).
+ hc_sinkhorn_iters (`int`):
+ Sinkhorn-Knopp iterations t_max for the mHC residual
+ mapping projection onto doubly-stochastic matrices.
+ hc_eps (`float`):
+ Numerical floor for the Sinkhorn-Knopp normalization.
+ mlp_layer_types (`list[str]`):
+ Per-layer MoE schedule with values from
+ `{"hash_moe", "moe"}`. `hash_moe` routes via a frozen
+ `tid2eid[input_ids]` lookup (paper §2.1, "Hash-MoE bootstrap"); `moe`
+ is the standard top-k routed MoE. Default: 3× `hash_moe` then `moe`
+ for the rest. BC: legacy configs that ship `num_hash_layers` as a
+ top-level kwarg are folded in at `__post_init__` time.
+ swiglu_limit (`float`):
+ Clip routed experts' gate/up pre-activations.
+ sliding_window (`int`):
+ Local window size n_win used in every attention block's
+ sliding-window branch.
+ o_groups (`int`):
+ Number of head-groups g in the grouped output projection
+ (paper §2.3.1, "Grouped Output Projection").
+ o_lora_rank (`int`):
+ Per-group intermediate dim d_g in the grouped output projection.
+ index_n_heads (`int`):
+ Number of indexer query heads n_h^I (paper §2.3.1, eq. 14).
+ index_head_dim (`int`):
+ Indexer head dim c^I (paper §2.3.1).
+ index_topk (`int`):
+ Number of compressed entries per query the Lightning Indexer
+ keeps via top-k (paper §2.3.1, eq. 17).
+ num_nextn_predict_layers (`int`):
+ MTP layer count in the upstream checkpoint
+ (not instantiated here).
+ partial_rotary_factor (`float`, *optional*):
+ Fraction of head_dim that gets RoPE.
+ Defaults to `qk_rope_head_dim / head_dim` so cos/sin sizes to `qk_rope_head_dim`.
+ """
+
+ model_type = "deepseek_v4"
+ keys_to_ignore_at_inference = ["past_key_values"]
+ # `num_local_experts` is the standard MoE attr name (read by FP8 / TP integrations);
+ # `intermediate_size` is what :class:`LlamaMLP` reads for the shared expert width
+ # — V4 only ships `moe_intermediate_size` so we route the read through.
+ attribute_map = {
+ "num_local_experts": "n_routed_experts",
+ "intermediate_size": "moe_intermediate_size",
+ }
+
+ base_model_pp_plan = {
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
+ "norm": (["hidden_states"], ["hidden_states"]),
+ }
+ base_model_ep_plan = {
+ # EP-only by default, same shape as gpt-oss: route on the gate, run the
+ # routed experts as a grouped-GEMM kernel sharded along the expert axis,
+ # and wrap the experts module with `moe_tp_experts` so its output gets
+ # all-reduced across ranks. Attention stays replicated (V4 is shared-KV
+ # MQA + a CSA / HCA compressor branch — both broadcast a single KV head
+ # across all attention heads via `repeat_kv`, so colwise-sharding
+ # `q_b_proj` would leave KV replicated and `repeat_kv` would no longer
+ # match the rank-local query head count). The shared MLP also stays
+ # replicated — it's small and not worth TP-ing. There's deliberately
+ # no `base_model_tp_plan` for V4: we don't ship a pure-TP plan, only EP.
+ "layers.*.mlp.gate": "ep_router",
+ "layers.*.mlp.experts.gate_up_proj": "grouped_gemm",
+ "layers.*.mlp.experts.down_proj": "grouped_gemm",
+ "layers.*.mlp.experts": "moe_tp_experts",
+ }
+
+ vocab_size: int = 129280
+ hidden_size: int = 4096
+ moe_intermediate_size: int = 2048
+ num_hidden_layers: int = 43
+ num_attention_heads: int = 64
+ num_key_value_heads: int = 1
+ head_dim: int = 512
+ q_lora_rank: int = 1024
+ default_partial_rotary_factor = 64 / 512 # `qk_rope_head_dim` (64) / `head_dim` (512)
+ num_experts_per_tok: int = 6
+ n_routed_experts: int = 256
+ n_shared_experts: int = 1
+ scoring_func: str = "sqrtsoftplus"
+ norm_topk_prob: bool = True
+ routed_scaling_factor: float = 1.5
+ max_position_embeddings: int = 1048576
+ rope_theta: float | int = 10000.0
+
+ layer_types: list[str] | None = None
+ compress_rates: dict | None = None
+ default_compress_rates = {"compressed_sparse_attention": 4, "heavily_compressed_attention": 128}
+ compress_rope_theta: float | int = 160000.0
+ hc_mult: int = 4
+ hc_sinkhorn_iters: int = 20
+ hc_eps: float = 1.0e-6
+ mlp_layer_types: list[str] | None = None
+ default_num_hash_layers = 3
+ swiglu_limit: float = 10.0
+ sliding_window: int = 128
+ o_groups: int = 8
+ o_lora_rank: int = 1024
+ index_n_heads: int = 64
+ index_head_dim: int = 128
+ index_topk: int = 512
+ num_nextn_predict_layers: int = 1
+
+ output_router_logits: bool = False
+ router_aux_loss_coef: float = 0.001
+ router_jitter_noise: float = 0.0
+
+ hidden_act: str = "silu"
+ initializer_range: float = 0.02
+ rms_norm_eps: float = 1.0e-6
+ use_cache: bool = True
+ pad_token_id: int | None = None
+ bos_token_id: int | None = 0
+ eos_token_id: int | list[int] | None = 1
+ tie_word_embeddings: bool = False
+ rope_parameters: RopeParameters | dict | None = None
+ partial_rotary_factor: float | None = None
+ attention_bias: bool = False
+ mlp_bias: bool = False
+ attention_dropout: float = 0.0
+
+ # V4's `rope_parameters` is keyed by *rope-type* labels (`main` / `compress`) — not
+ # by `layer_types`. The base `validate_rope` checks `keys ⊆ layer_types` and falls
+ # back to wrapping the whole dict as a single set of params when the subset check
+ # fails, which then warns about `main` / `compress` as unrecognized keys. Override
+ # to iterate the rope-type-keyed sub-dicts directly.
+ _rope_type_labels = ("main", "compress")
+
+ def validate_rope(self):
+ rope_parameters_dict = getattr(self, "rope_parameters", None) or {}
+ ignore_keys = self.ignore_keys_at_rope_validation
+ # The yarn / longrope / llama3 validators in
+ # :class:`RotaryEmbeddingConfigMixin` read `self.rope_parameters[]`
+ # directly (e.g. `original_max_position_embeddings`). With V4's
+ # rope-type-keyed nesting, the top-level dict only has `main` / `compress`,
+ # so those reads fail. Temporarily point `self.rope_parameters` at the
+ # rope-type-specific sub-dict for the duration of the validation call,
+ # then restore it.
+ for rope_type_label in self._rope_type_labels:
+ rope_parameters = rope_parameters_dict.get(rope_type_label)
+ if not isinstance(rope_parameters, dict):
+ continue
+ rope_type = rope_parameters.get("rope_type", rope_parameters.get("type", "default"))
+ rope_parameters["rope_type"] = rope_type
+ validation_fn = getattr(self, f"_validate_{rope_type}_rope_parameters", None)
+ if validation_fn is None:
+ continue
+ self.rope_parameters = rope_parameters
+ try:
+ validation_fn(rope_parameters, ignore_keys=ignore_keys)
+ finally:
+ self.rope_parameters = rope_parameters_dict
+
+ def validate_layer_type(self):
+ """V4 narrows the global `ALLOWED_LAYER_TYPES` to the three attention-block
+ types and two MLP-block types it actually ships with, on top of the standard
+ length / type-membership checks.
+ """
+ if self.num_hidden_layers is None:
+ return
+ for name, types, allowed in (
+ ("layer_types", self.layer_types, DEEPSEEK_V4_LAYER_TYPES),
+ ("mlp_layer_types", self.mlp_layer_types, DEEPSEEK_V4_MLP_LAYER_TYPES),
+ ):
+ if types is None:
+ continue
+ if len(types) != self.num_hidden_layers:
+ raise ValueError(
+ f"`num_hidden_layers` ({self.num_hidden_layers}) must equal `len({name})` ({len(types)})."
+ )
+ bad = [t for t in types if t not in allowed]
+ if bad:
+ raise ValueError(f"`{name}` entries must be one of {allowed} for DeepSeek-V4; got {bad}.")
+
+ def __post_init__(self, **kwargs):
+ # Strip legacy V4 kwargs (V3-flavoured names that older checkpoints still ship)
+ # before the parent's strict-validated init sees them, then fold each into the
+ # modern field below.
+ legacy_compress_ratios = kwargs.pop("compress_ratios", None)
+ legacy_compress_rate_csa = kwargs.pop("compress_rate_csa", None)
+ legacy_compress_rate_hca = kwargs.pop("compress_rate_hca", None)
+ legacy_num_hash_layers = kwargs.pop("num_hash_layers", None)
+ legacy_qk_rope_head_dim = kwargs.pop("qk_rope_head_dim", None)
+ PreTrainedConfig.__post_init__(self, **kwargs)
+ n = self.num_hidden_layers
+
+ # `compress_rates`: dict, default per attention type. Legacy scalar overrides fold in.
+ if self.compress_rates is None:
+ self.compress_rates = dict(self.default_compress_rates)
+ if legacy_compress_rate_csa is not None:
+ self.compress_rates["compressed_sparse_attention"] = legacy_compress_rate_csa
+ if legacy_compress_rate_hca is not None:
+ self.compress_rates["heavily_compressed_attention"] = legacy_compress_rate_hca
+
+ # `layer_types`: explicit > legacy `compress_ratios` per-layer ints (0/4/128) >
+ # V4-Pro default (2× HCA bootstrap + CSA/HCA interleave).
+ if self.layer_types is None and legacy_compress_ratios is not None:
+ self.layer_types = [_COMPRESS_RATIO_TO_LAYER_TYPE[r] for r in legacy_compress_ratios]
+ if self.layer_types is None:
+ interleave = [
+ "compressed_sparse_attention" if i % 2 else "heavily_compressed_attention"
+ for i in range(max(n - 2, 0))
+ ]
+ self.layer_types = ["heavily_compressed_attention"] * min(n, 2) + interleave
+ self.layer_types = list(self.layer_types[:n])
+
+ # `mlp_layer_types`: first `num_hash_layers` hash_moe, rest moe.
+ if self.mlp_layer_types is None:
+ n_hash = legacy_num_hash_layers if legacy_num_hash_layers is not None else self.default_num_hash_layers
+ self.mlp_layer_types = ["hash_moe"] * min(n, n_hash) + ["moe"] * max(0, n - n_hash)
+ self.mlp_layer_types = list(self.mlp_layer_types[:n])
+
+ # `partial_rotary_factor` = legacy `qk_rope_head_dim / head_dim` if given, else default.
+ # `qk_rope_head_dim` is a runtime-only attr (never a dataclass field).
+ if self.partial_rotary_factor is None:
+ self.partial_rotary_factor = (
+ legacy_qk_rope_head_dim / self.head_dim
+ if legacy_qk_rope_head_dim is not None
+ else self.default_partial_rotary_factor
+ )
+ self.qk_rope_head_dim = int(self.head_dim * self.partial_rotary_factor)
+
+ # yarn is applied ONLY to layers with a
+ # compressor (CSA/HCA); pure sliding-window layers use plain RoPE with
+ # `theta=rope_theta` (10000) and no scaling. Compress layers use
+ # `theta=compress_rope_theta` (160000) with yarn factor=16, and the reference
+ # does NOT multiply cos/sin by the yarn mscale — force `attention_factor=1.0`
+ # so transformers' `_compute_yarn_parameters` doesn't apply `0.1·log(16)+1`.
+ rp = self.rope_parameters or {}
+ if isinstance(rp.get("main"), dict) and isinstance(rp.get("compress"), dict):
+ # Already nested — drop any leftover top-level keys.
+ self.rope_parameters = {"main": rp["main"], "compress": rp["compress"]}
+ else:
+ yarn = {k: v for k, v in rp.items() if k not in ("main", "compress")}
+ main = {
+ "rope_type": "default",
+ "rope_theta": self.rope_theta,
+ "partial_rotary_factor": self.partial_rotary_factor,
+ }
+ compress = {
+ **yarn,
+ "rope_theta": self.compress_rope_theta,
+ "partial_rotary_factor": self.partial_rotary_factor,
+ "attention_factor": 1.0,
+ }
+ compress.setdefault("rope_type", "default")
+ self.rope_parameters = {"main": main, "compress": compress}
+
+
+__all__ = ["DeepseekV4Config"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/deepseek_v4/modeling_deepseek_v4.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/deepseek_v4/modeling_deepseek_v4.py
new file mode 100644
index 0000000000000000000000000000000000000000..163a0cee77a3f2aa2ea4a0b19637d34b494727b9
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/deepseek_v4/modeling_deepseek_v4.py
@@ -0,0 +1,1498 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/deepseek_v4/modular_deepseek_v4.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_deepseek_v4.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2026 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from collections.abc import Callable
+from typing import Optional
+
+import torch
+import torch.nn.functional as F
+from torch import nn
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...cache_utils import Cache, DynamicCache, DynamicSlidingWindowLayer
+from ...generation import GenerationMixin
+from ...integrations import use_experts_implementation, use_kernel_forward_from_hub
+from ...masking_utils import create_sliding_window_causal_mask
+from ...modeling_flash_attention_utils import FlashAttentionKwargs
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import MoeCausalLMOutputWithPast, MoeModelOutputWithPast
+from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import TransformersKwargs, auto_docstring, can_return_tuple
+from ...utils.generic import maybe_autocast, merge_with_config_defaults
+from ...utils.output_capturing import OutputRecorder, capture_outputs
+from .configuration_deepseek_v4 import DeepseekV4Config
+
+
+@use_kernel_forward_from_hub("RMSNorm")
+class DeepseekV4RMSNorm(nn.Module):
+ def __init__(self, hidden_size, eps: float = 1e-6) -> None:
+ """
+ DeepseekV4RMSNorm is equivalent to T5LayerNorm
+ """
+ super().__init__()
+ self.weight = nn.Parameter(torch.ones(hidden_size))
+ self.variance_epsilon = eps
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ input_dtype = hidden_states.dtype
+ hidden_states = hidden_states.to(torch.float32)
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
+ return self.weight * hidden_states.to(input_dtype)
+
+ def extra_repr(self):
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
+
+
+class DeepseekV4UnweightedRMSNorm(nn.Module):
+ def __init__(self, eps: float = 1.0e-6):
+ super().__init__()
+ self.eps = eps
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ return x * torch.rsqrt(x.float().square().mean(-1, keepdim=True) + self.eps).to(x.dtype)
+
+
+class DeepseekV4RotaryEmbedding(nn.Module):
+ """
+ Multi-layer-type rotary embedding (Laguna pattern: partial rotary on top of
+ Gemma3's per-layer-type buffers), specialised for V4's *interleaved* RoPE.
+ Interleaved RoPE: one `θ_i` per pair (`rope_head_dim // 2` entries),
+ DIFF no end-to-end duplication. Same shape as `inv_freq @ position_ids`.
+
+ V4 deliberately decouples its architecture `layer_types`
+ (`sliding_attention` / `compressed_sparse_attention` /
+ `heavily_compressed_attention`) from its rope-type labels (`main` /
+ `compress`) — the latter live as keys in `config.rope_parameters` and
+ only differ in their `rope_theta` base. So this override replaces
+ Laguna's `set(config.layer_types)` iteration with `rope_parameters.keys()`
+ when building the per-type inv_freq buffers.
+ """
+
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
+
+ def __init__(self, config: DeepseekV4Config):
+ super().__init__()
+ self.max_seq_len_cached = config.max_position_embeddings
+ self.original_max_seq_len = config.max_position_embeddings
+ self.config = config
+ # Only the nested per-rope-type sub-dicts are real layer types — the top-level
+ # `rope_type` key that ``convert_rope_params_to_dict`` may leave on
+ # ``config.rope_parameters`` is a flat-shape leftover, not a layer.
+ self.layer_types = [k for k, v in config.rope_parameters.items() if isinstance(v, dict)]
+ self.rope_type = {}
+ for layer_type in self.layer_types:
+ rope_params = config.rope_parameters[layer_type]
+ self.rope_type[layer_type] = rope_params["rope_type"]
+ rope_init_fn = self.compute_default_rope_parameters
+ if self.rope_type[layer_type] != "default":
+ rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type[layer_type]]
+ inv_freq, attention_scaling = rope_init_fn(config, layer_type=layer_type)
+ self.register_buffer(f"{layer_type}_inv_freq", inv_freq, persistent=False)
+ self.register_buffer(f"{layer_type}_original_inv_freq", inv_freq.clone(), persistent=False)
+ setattr(self, f"{layer_type}_attention_scaling", attention_scaling)
+
+ @staticmethod
+ def compute_default_rope_parameters(
+ config: DeepseekV4Config | None = None,
+ device: Optional["torch.device"] = None,
+ seq_len: int | None = None,
+ layer_type: str | None = None,
+ ) -> tuple["torch.Tensor", float]:
+ """
+ Computes the inverse frequencies according to the original RoPE implementation
+ Args:
+ config ([`~transformers.PreTrainedConfig`]):
+ The model configuration.
+ device (`torch.device`):
+ The device to use for initialization of the inverse frequencies.
+ seq_len (`int`, *optional*):
+ The current sequence length. Unused for this type of RoPE.
+ layer_type (`str`, *optional*):
+ The current layer type if the model has different RoPE parameters per type.
+ Should not be used unless `config.layer_types is not None`
+ Returns:
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
+ """
+ base = config.rope_parameters[layer_type]["rope_theta"]
+ # key difference to gemma3: partial rope
+ partial_rotary_factor = config.rope_parameters[layer_type].get("partial_rotary_factor", 1.0)
+ head_dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
+ dim = int(head_dim * partial_rotary_factor)
+
+ attention_factor = 1.0 # Unused in this type of RoPE
+
+ # Compute the inverse frequencies
+ inv_freq = 1.0 / (
+ base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
+ )
+ return inv_freq, attention_factor
+
+ @torch.no_grad()
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
+ def forward(self, x, position_ids, layer_type=None):
+ # Key difference vs Laguna's forward: no `torch.cat([freqs, freqs], dim=-1)`
+ # duplication. V4's interleaved RoPE pairs consecutive channels, so we only need
+ # `rope_head_dim // 2` unique θ entries — the `apply_rotary_pos_emb` helper does
+ # the `repeat_interleave(2)` next to the rotation math, where the link between
+ # the doubled dim and `rotate_half` is local and obvious.
+ inv_freq = getattr(self, f"{layer_type}_inv_freq")
+ attention_scaling = getattr(self, f"{layer_type}_attention_scaling")
+ inv_freq_expanded = inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
+ position_ids_expanded = position_ids[:, None, :].float()
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
+ with maybe_autocast(device_type=device_type, enabled=False):
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
+ cos = freqs.cos() * attention_scaling
+ sin = freqs.sin() * attention_scaling
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
+
+
+class DeepseekV4HCACache(DynamicSlidingWindowLayer):
+ r"""Cache layer for HCA blocks (paper §2.3.2). Holds the long-range compressor's
+ buffer / running compressed entries / count on top of the sliding-window K=V
+ branch. HCA uses *non-overlapping* windows, so there is *no* overlap state,
+ and HCA has *no* indexer either.
+
+ State is dict-keyed by entry name — HCA only uses `"compressor"`, but
+ :class:`DeepseekV4CSACache` adds `"indexer"` to the same dicts so a single
+ set of methods (`store_compression_weights` / `update_compressor_states`)
+ serves both:
+
+ * `compressed_kv[name]` — the running list of compressed KV entries
+ emitted so far (one every `compress_rate` source tokens; the long-range
+ KVs the attention concatenates onto its sliding-window keys / values).
+ * `buffer_kv[name]` / `buffer_gate[name]` — source tokens that arrived
+ between two full windows; once the buffer hits `compress_rate` tokens
+ the compressor closes a window, emits one entry, and drains the buffer.
+ * `entry_count[name]` — number of compressed entries emitted so far, so
+ `entry_count[name] * compress_rate` is the absolute position of the
+ *next* window's first source token. Tracked separately from
+ `position_ids` so prefill -> decode -> prefill stays consistent.
+ """
+
+ layer_type = "heavily_compressed_attention"
+
+ def __init__(self, config: "DeepseekV4Config"):
+ super().__init__(config)
+ self.compress_rate = config.compress_rates["heavily_compressed_attention"]
+ self.buffer_kv: dict[str, torch.Tensor | None] = {"compressor": None}
+ self.buffer_gate: dict[str, torch.Tensor | None] = {"compressor": None}
+ self.compressed_kv: dict[str, torch.Tensor | None] = {"compressor": None}
+ self.entry_count: dict[str, int] = {"compressor": 0}
+
+ def update(self, key_states: torch.Tensor, value_states: torch.Tensor, *args, **kwargs):
+ """
+ Shared sliding-window K=V update body. V4 uses shared-KV MQA, so `keys` and
+ `values` point to the same storage on every layer.
+ """
+ if not self.is_initialized:
+ self.lazy_initialization(key_states, value_states)
+ self.values = self.keys
+ self.cumulative_length += key_states.shape[-2]
+ full = torch.cat([self.keys, key_states], dim=-2)
+ self.keys = full[:, :, -self.sliding_window + 1 :, :]
+ self.values = self.keys
+ return full, full
+
+ def store_compression_weights(
+ self, name: str, kv: torch.Tensor, gate: torch.Tensor
+ ) -> tuple[torch.Tensor, torch.Tensor, int]:
+ r"""
+ Concatenate the new projected `(kv, gate)` (paper §2.3.2 eqs. 20–21:
+ `C = H·W^{KV}`, `Z = H·W^Z`) for entry `name` with what's already in
+ the buffer, peel off the longest window-aligned prefix (the chunk
+ ready to compress), keep the leftover in the buffer for next call,
+ and return `(chunk_kv, chunk_gate, first_window_position)`. The
+ returned chunk is softmax-aggregated by the compressor with
+ `position_bias` to emit one compressed entry per window of
+ `compress_rate` tokens.
+ """
+ first_window_position = self.entry_count[name] * self.compress_rate
+ buffered_kv, buffered_gate = self.buffer_kv[name], self.buffer_gate[name]
+ if buffered_kv is not None and buffered_kv.shape[1]:
+ kv = torch.cat([buffered_kv, kv], dim=1)
+ gate = torch.cat([buffered_gate, gate], dim=1)
+ # only return the longest prefix that's a multiple of compress_rate; the rest stays in the buffer for next time
+ usable = (kv.shape[1] // self.compress_rate) * self.compress_rate
+ self.buffer_kv[name], self.buffer_gate[name] = kv[:, usable:], gate[:, usable:]
+ return kv[:, :usable], gate[:, :usable], first_window_position
+
+ def update_compressor_states(self, name: str, compressed: torch.Tensor) -> torch.Tensor:
+ r"""
+ Append freshly emitted compressed entries to `compressed_kv[name]`
+ (`C^{Comp}`, paper §2.3.2 eq. 23), bump `entry_count[name]`, and
+ return the running `compressed_kv[name]`.
+ """
+ if self.compressed_kv[name] is None:
+ self.compressed_kv[name] = compressed
+ elif compressed.shape[1] > 0:
+ self.compressed_kv[name] = torch.cat([self.compressed_kv[name], compressed], dim=1)
+ self.entry_count[name] += compressed.shape[1]
+ return self.compressed_kv[name]
+
+
+class DeepseekV4CSACache(DeepseekV4HCACache):
+ r"""Cache layer for CSA blocks (paper §2.3.1). Extends :class:`DeepseekV4HCACache`
+ by adding an `"indexer"` entry to the inherited `buffer_kv` / `buffer_gate` /
+ `compressed_kv` / `entry_count` dicts, plus per-name *overlap* state for the
+ two-series window scheme.
+
+ What "overlap" means here: the CSA `kv_proj` / `gate_proj` produce `2 * head_dim`
+ features per source token — two independent compressed series Ca and Cb stored
+ in one tensor. Ca occupies `[..., :head_dim]`, Cb occupies `[..., head_dim:]`.
+ Pooled entry `w` is the softmax-gated convex combination of window `w-1`'s Ca
+ slice with window `w`'s Cb slice — effective width `2 * compress_rate_csa`,
+ stride `compress_rate_csa` (paper §2.3.1).
+
+ Because adjacent windows share state only through *the previous window's Ca
+ slice*, the only thing we need to carry across a forward boundary is
+ `chunk[:, -1, :, :head_dim]` (Ca) of the last full window — Cb is never read
+ again. That's what `overlap_kv[name]` / `overlap_gate[name]` persist.
+ """
+
+ layer_type = "compressed_sparse_attention"
+
+ def __init__(self, config: "DeepseekV4Config"):
+ super().__init__(config)
+ self.compress_rate = config.compress_rates["compressed_sparse_attention"]
+ self.buffer_kv["indexer"] = None
+ self.buffer_gate["indexer"] = None
+ self.compressed_kv["indexer"] = None
+ self.entry_count["indexer"] = 0
+ self.overlap_kv: dict[str, torch.Tensor | None] = {"compressor": None, "indexer": None}
+ self.overlap_gate: dict[str, torch.Tensor | None] = {"compressor": None, "indexer": None}
+
+ def update_overlap_state(
+ self, name: str, chunk_kv: torch.Tensor, chunk_gate: torch.Tensor, head_dim: int
+ ) -> tuple[torch.Tensor | None, torch.Tensor | None]:
+ r"""
+ Read the `name` entry's prior window's Ca slice (saved on the previous
+ forward call) and persist the *current* call's last-window Ca slice for
+ the next call. Only the `:head_dim` slice (Ca) is ever consumed
+ downstream — Cb has already been folded into the previous window's
+ emitted compressed entry — so we store half what `chunk[:, -1]` holds.
+ Returns `(prior_kv, prior_gate)` — both `None` on the very first call.
+ """
+ prior_kv, prior_gate = self.overlap_kv[name], self.overlap_gate[name]
+ self.overlap_kv[name] = chunk_kv[:, -1, :, :head_dim].clone()
+ self.overlap_gate[name] = chunk_gate[:, -1, :, :head_dim].clone()
+ return prior_kv, prior_gate
+
+
+class DeepseekV4GroupedLinear(nn.Linear):
+ """Block-diagonal grouped linear used by the grouped output projection
+ The core attention's stacked output is `num_attention_heads* head_dim`-dim,
+ which is *very* large (V4-Flash: 32768; V4-Pro: 65536). A direct
+ `num_attention_heads*head_dim → hidden_size` projection would dominate the per-token cost.
+
+ The paper sidesteps that by splitting the heads into `g` groups, projecting
+ each `num_attention_heads * head_dim/g`-dim group independently to a `d_g`-dim intermediate output
+ (with `d_g < num_attention_heads * head_dim/g`), and then mixing the resulting `g·d_g` vector to
+ `hidden_size` through a single follow-up linear (`self_attn.o_b_proj`). This
+ module owns the per-group block (`self_attn.o_a_proj`).
+
+ For V4-Flash (num_attention_heads=64, head_dim=512, o_groups=8, o_lora_rank=1024,
+ hidden_size=4096), g=8 groups of 4096-dim each are projected to 1024-dim, then
+ mixed to 4096-dim; for V4-Pro (num_attention_heads=128, head_dim=512, o_groups=16,
+ o_lora_rank=1024, hidden_size=7168), g=16 groups of 4096-dim each are projected
+ to 1024-dim, then mixed to 7168-dim.
+ """
+
+ def __init__(self, in_features_per_group: int, out_features: int, n_groups: int, bias: bool = False):
+ super().__init__(in_features_per_group, out_features, bias=bias)
+ self.n_groups = n_groups
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ input_shape = x.shape[:-2]
+ hidden_dim = x.shape[-1]
+ w = self.weight.view(self.n_groups, -1, hidden_dim).transpose(1, 2)
+ x = x.reshape(-1, self.n_groups, hidden_dim).transpose(0, 1)
+ y = torch.bmm(x, w).transpose(0, 1)
+ return y.reshape(*input_shape, self.n_groups, -1)
+
+
+def rotate_half(x):
+ """Rotates half the hidden dims of the input."""
+ x1 = x[..., 0::2]
+ x2 = x[..., 1::2]
+ return torch.stack((-x2, x1), dim=-1).flatten(-2)
+
+
+def apply_rotary_pos_emb(
+ x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, unsqueeze_dim: int = 1
+) -> torch.Tensor:
+ """V4 interleaved RoPE applied to the *trailing* rope slice of `x`.
+
+ `cos` / `sin` come in half-sized (one entry per interleaved pair, from
+ `DeepseekV4RotaryEmbedding`); we expand them to the full rope dim with
+ `repeat_interleave`, then rotate the last `2 * cos.shape[-1]` channels of `x`
+ with the standard `x*cos + rotate_half(x)*sin` formula in fp32 and leave the
+ leading nope channels untouched. V4-Flash lays each head out as `[nope | rope]`,
+ matching the reference's `x[..., -rd:]` indexing.
+ """
+ cos = cos.repeat_interleave(2, dim=-1).unsqueeze(unsqueeze_dim)
+ sin = sin.repeat_interleave(2, dim=-1).unsqueeze(unsqueeze_dim)
+ rope_dim = cos.shape[-1]
+ nope, rope = x[..., :-rope_dim], x[..., -rope_dim:]
+ rotated = ((rope.float() * cos) + (rotate_half(rope).float() * sin)).to(x.dtype)
+ return torch.cat([nope, rotated], dim=-1)
+
+
+class DeepseekV4HCACompressor(nn.Module):
+ """
+ Heavily Compressed Attention compressor (paper §2.3.2, eqs. 20–23). compresses
+ every `compress_rate_hca` (m'=128) source tokens into a single compressed KV
+ entry.
+
+ Each closed window of m' tokens produces one compressed entry:
+ `C^{Comp}_i = Σ_{j∈window} softmax(Z_j + B)_j ⊙ C_j`. RoPE on the trailing
+ `rope_head_dim` slice is applied at the deterministic absolute position
+ `i * compress_rate_hca + first_window_position` so cross-call concatenation
+ stays causality-correct. Returns the running list of *all* compressed
+ entries emitted so far (shape `[B, 1, T, head_dim]` with
+ `T = entry_count["compressor"]`), so the attention can attend over the
+ full long-range history.
+
+ When `past_key_values is None` runs in stateless single-shot mode: compress
+ every complete window from `hidden_states` and discard the remainder
+ (instead of caching it).
+ """
+
+ rope_layer_type = "compress"
+
+ def __init__(self, config: DeepseekV4Config):
+ super().__init__()
+ self.compress_rate = config.compress_rates["heavily_compressed_attention"]
+ self.head_dim = config.head_dim
+ self.kv_proj = nn.Linear(config.hidden_size, self.head_dim, bias=False)
+ self.gate_proj = nn.Linear(config.hidden_size, self.head_dim, bias=False)
+ self.position_bias = nn.Parameter(torch.empty(self.compress_rate, self.head_dim))
+ self.kv_norm = DeepseekV4RMSNorm(self.head_dim, eps=config.rms_norm_eps)
+ self.rotary_emb = DeepseekV4RotaryEmbedding(config)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ q_residual: torch.Tensor,
+ position_ids: torch.Tensor,
+ past_key_values: Cache | None,
+ layer_idx: int,
+ ) -> tuple[torch.Tensor, torch.Tensor]:
+ batch, _, _ = hidden_states.shape
+ cache_layer: DeepseekV4HCACache = past_key_values.layers[layer_idx] if past_key_values is not None else None
+ kv = self.kv_proj(hidden_states)
+ gate = self.gate_proj(hidden_states)
+ if cache_layer is None:
+ usable = (kv.shape[1] // self.compress_rate) * self.compress_rate
+ chunk_kv, chunk_gate, first_window_position = kv[:, :usable], gate[:, :usable], 0
+ else:
+ chunk_kv, chunk_gate, first_window_position = cache_layer.store_compression_weights("compressor", kv, gate)
+
+ if chunk_kv.shape[1] > 0: # there were at least self.compress_rate tokens
+ n_windows = chunk_kv.shape[1] // self.compress_rate
+ chunk_kv = chunk_kv.view(batch, n_windows, self.compress_rate, -1)
+ chunk_gate = chunk_gate.view(batch, n_windows, self.compress_rate, -1) + self.position_bias.to(
+ chunk_gate.dtype
+ )
+ compressed = self.kv_norm(
+ (chunk_kv * chunk_gate.softmax(dim=2, dtype=torch.float32).to(chunk_kv.dtype)).sum(dim=2)
+ )
+ positions = torch.arange(n_windows, device=compressed.device)
+ positions = (positions * self.compress_rate + first_window_position).unsqueeze(0).expand(batch, -1)
+ cos, sin = self.rotary_emb(compressed, position_ids=positions, layer_type=self.rope_layer_type)
+ compressed = apply_rotary_pos_emb(compressed.unsqueeze(1), cos, sin).squeeze(1)
+ else:
+ compressed = chunk_kv.new_zeros((batch, 0, self.head_dim))
+
+ if cache_layer is not None:
+ compressed = cache_layer.update_compressor_states("compressor", compressed)
+ compressed_kv = compressed.unsqueeze(1)
+
+ compressed_len = compressed_kv.shape[2]
+ seq_len = position_ids.shape[1]
+ if seq_len == 1 or compressed_len == 0:
+ return compressed_kv, None
+
+ # query `t` may only see cache entries at pos `w` t > w * compress_rate (ex: t=7, w=2 t does not attend to it).
+ entry_indices = torch.arange(compressed_len, device=compressed_kv.device)
+ causal_threshold = (position_ids + 1) // self.compress_rate # [B, S]
+ block_bias = compressed_kv.new_zeros((batch, 1, seq_len, compressed_len))
+ block_bias = block_bias.masked_fill(
+ entry_indices.view(1, 1, 1, -1) >= causal_threshold.unsqueeze(1).unsqueeze(-1),
+ float("-inf"),
+ )
+ return compressed_kv, block_bias
+
+
+class DeepseekV4Indexer(nn.Module):
+ r"""Lightning Indexer (paper §2.3.1, eqs. 13–17). Used by Compressed Sparse
+ Attention (CSA) to pick the top-`k` compressed KV blocks per query, with
+ `k = config.index_topk`. Each query then attends only to those `k` of the
+ `seq_len / compress_rate_csa` compressed entries — reduction factor
+ `(seq_len / compress_rate_csa) / index_topk` over full attention against
+ the entire compressed sequence.
+
+ The indexer runs its own scaled-down compressor at `index_head_dim` over
+ the same windows as the outer CSA compressor, then scores queries against
+ the compressed keys with `∑_h w_{t,h} · ReLU(q_{t,h} · K^IComp_s)` and
+ keeps the top `index_topk` indices.
+
+ The indexer has its own rotary because it applies RoPE to two sets of
+ tensors:
+
+ * *compressed keys* at deterministic positions
+ `i * compress_rate + first_window_position`,
+ * *queries* at the model's current `position_ids` (variable per forward).
+
+ Both must use the same theta as the outer compressor
+ (`compress_rope_theta`) so query/key inner products are
+ translation-invariant — if they used different thetas, `q · k` would carry
+ a residual position-dependent skew. We can't precompute cos/sin once at
+ init because the query positions vary per call, so the indexer owns its
+ own rotary and calls it twice per forward (once for compressed keys, once
+ for queries) with `layer_type=self.rope_layer_type` (always `"compress"`).
+ """
+
+ rope_layer_type = "compress"
+
+ def __init__(self, config: DeepseekV4Config):
+ super().__init__()
+ self.compress_rate = config.compress_rates["compressed_sparse_attention"]
+ self.num_heads = config.index_n_heads
+ self.head_dim = config.index_head_dim
+ self.index_topk = config.index_topk
+ self.softmax_scale = self.head_dim**-0.5
+ self.weights_scaling = self.num_heads**-0.5
+ self.kv_proj = nn.Linear(config.hidden_size, 2 * self.head_dim, bias=False)
+ self.gate_proj = nn.Linear(config.hidden_size, 2 * self.head_dim, bias=False)
+ self.position_bias = nn.Parameter(torch.empty(self.compress_rate, 2 * self.head_dim))
+ self.kv_norm = DeepseekV4RMSNorm(self.head_dim, eps=config.rms_norm_eps)
+ self.q_b_proj = nn.Linear(config.q_lora_rank, self.num_heads * self.head_dim, bias=False)
+ self.weights_proj = nn.Linear(config.hidden_size, self.num_heads, bias=False)
+ self.rotary_emb = DeepseekV4RotaryEmbedding(config)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ q_residual: torch.Tensor,
+ position_ids: torch.Tensor,
+ past_key_values: Cache | None,
+ layer_idx: int,
+ ) -> torch.LongTensor:
+ batch, seq_len, _ = hidden_states.shape
+ cache_layer: DeepseekV4CSACache = past_key_values.layers[layer_idx] if past_key_values is not None else None
+ kv = self.kv_proj(hidden_states)
+ gate = self.gate_proj(hidden_states)
+
+ if cache_layer is None:
+ usable = (kv.shape[1] // self.compress_rate) * self.compress_rate
+ chunk_kv, chunk_gate, first_window_position = kv[:, :usable], gate[:, :usable], 0
+ else:
+ chunk_kv, chunk_gate, first_window_position = cache_layer.store_compression_weights("indexer", kv, gate)
+
+ if chunk_kv.shape[1] > 0:
+ n_windows = chunk_kv.shape[1] // self.compress_rate
+ ratio = self.compress_rate
+ chunk_kv = chunk_kv.view(batch, n_windows, ratio, -1)
+ chunk_gate = chunk_gate.view(batch, n_windows, ratio, -1) + self.position_bias.to(chunk_gate.dtype)
+
+ # Same Ca / Cb overlap layout as the outer CSA compressor, at index_head_dim.
+ new_kv = chunk_kv.new_zeros((batch, n_windows, 2 * ratio, self.head_dim))
+ new_gate = chunk_gate.new_full((batch, n_windows, 2 * ratio, self.head_dim), float("-inf"))
+ new_kv[:, :, ratio:] = chunk_kv[..., self.head_dim :]
+ new_gate[:, :, ratio:] = chunk_gate[..., self.head_dim :]
+ if n_windows > 1:
+ new_kv[:, 1:, :ratio] = chunk_kv[:, :-1, :, : self.head_dim]
+ new_gate[:, 1:, :ratio] = chunk_gate[:, :-1, :, : self.head_dim]
+ if cache_layer is not None:
+ prior_kv, prior_gate = cache_layer.update_overlap_state("indexer", chunk_kv, chunk_gate, self.head_dim)
+ if prior_kv is not None:
+ new_kv[:, 0, :ratio] = prior_kv.to(new_kv.dtype)
+ new_gate[:, 0, :ratio] = prior_gate.to(new_gate.dtype)
+
+ compressed = self.kv_norm(
+ (new_kv * new_gate.softmax(dim=2, dtype=torch.float32).to(new_kv.dtype)).sum(dim=2)
+ )
+ positions = torch.arange(n_windows, device=compressed.device)
+ positions = positions * self.compress_rate + first_window_position
+ positions = positions.unsqueeze(0).expand(batch, -1)
+ cos, sin = self.rotary_emb(compressed, position_ids=positions, layer_type=self.rope_layer_type)
+ compressed = apply_rotary_pos_emb(compressed.unsqueeze(1), cos, sin).squeeze(1)
+ else:
+ compressed = chunk_kv.new_zeros((batch, 0, self.head_dim))
+
+ compressed_kv = (
+ compressed if cache_layer is None else cache_layer.update_compressor_states("indexer", compressed)
+ )
+
+ cos_q, sin_q = self.rotary_emb(hidden_states, position_ids=position_ids, layer_type=self.rope_layer_type)
+ q = self.q_b_proj(q_residual).view(batch, seq_len, -1, self.head_dim).transpose(1, 2)
+ q = apply_rotary_pos_emb(q, cos_q, sin_q).transpose(1, 2)
+
+ # ReLU(q·kᵀ) * weights, then top-k
+ scores = torch.matmul(q.float(), compressed_kv.transpose(-1, -2).float().unsqueeze(1)) # [B, S, H, T]
+ scores = F.relu(scores) * self.softmax_scale
+ weights = self.weights_proj(hidden_states).float() * self.weights_scaling # [B, S, H]
+ index_scores = (scores * weights.unsqueeze(-1)).sum(dim=2) # [B, S, T]
+ compressed_len = compressed_kv.shape[1]
+ top_k = min(self.index_topk, compressed_len)
+
+ # not all queries can attend to the compressed entries. If a query's position
+ # is small than the relative position of the key (say m=4, query 2 cannot attend
+ # to compressed key at position 4, because it compressed info for states at position
+ # 12 to 16. Thus we need to make sure that top_k does not land in that range.
+ # Picks that still point past `causal_threshold` (early queries with too few ready
+ # blocks) are replaced with a `-1` sentinel that the compresser treats as invalid.
+ if compressed_len > 0:
+ causal_threshold = (position_ids + 1) // self.compress_rate # [B, S]
+ entry_indices = torch.arange(compressed_len, device=index_scores.device)
+ future_mask = entry_indices.view(1, 1, -1) >= causal_threshold.unsqueeze(-1) # [B, S, T]
+ index_scores = index_scores.masked_fill(future_mask, float("-inf"))
+ top_k_indices = index_scores.topk(top_k, dim=-1).indices # [B, S, k]
+ invalid = top_k_indices >= causal_threshold.unsqueeze(-1)
+ return torch.where(invalid, torch.full_like(top_k_indices, -1), top_k_indices)
+
+ return index_scores.topk(top_k, dim=-1).indices
+
+
+class DeepseekV4CSACompressor(nn.Module):
+ """Compressed Sparse Attention compressor (paper §2.3.1, eqs. 9–17). Compresses
+ every `compress_rate_csa` (m=4) source tokens and runs a Lightning Indexer on
+ top of the compressed KV that scores queries with
+ `∑_h w_{t,h} · ReLU(q_{t,h} · K^{IComp}_s)` to gather the top `index_topk`
+ entries per query before they reach core attention.
+
+ `kv_proj` / `gate_proj` / `position_bias` project to `2 * head_dim`: each
+ token contributes two independent compressed series Ca and Cb stored in
+ one tensor. Ca = `[..., :head_dim]` (its contribution to the *next*
+ window's compressed entry), Cb = `[..., head_dim:]` (its contribution to
+ the *current* window's compressed entry). Compressed entry `w` is the
+ softmax-gated convex combination of window `w-1`'s Ca slice with window
+ `w`'s Cb slice over `2 * compress_rate_csa` slots — width
+ `2 * compress_rate_csa`, stride `compress_rate_csa`. For `w = 0` we need
+ the previous window's Ca slice from the *previous forward call*; the
+ cache holds it in `overlap_kv` and hands it back here. On the very first
+ call (or when there is no cache) that slot stays zero-kv / `-inf`-gate,
+ which gives it softmax weight 0.
+ """
+
+ rope_layer_type = "compress"
+
+ def __init__(self, config: DeepseekV4Config):
+ super().__init__()
+ self.compress_rate = config.compress_rates["compressed_sparse_attention"]
+ self.head_dim = config.head_dim
+ self.kv_proj = nn.Linear(config.hidden_size, 2 * self.head_dim, bias=False)
+ self.gate_proj = nn.Linear(config.hidden_size, 2 * self.head_dim, bias=False)
+ self.position_bias = nn.Parameter(torch.empty(self.compress_rate, 2 * self.head_dim))
+ self.kv_norm = DeepseekV4RMSNorm(self.head_dim, eps=config.rms_norm_eps)
+ self.rotary_emb = DeepseekV4RotaryEmbedding(config)
+ self.indexer = DeepseekV4Indexer(config)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ q_residual: torch.Tensor,
+ position_ids: torch.Tensor,
+ past_key_values: Cache | None,
+ layer_idx: int,
+ ) -> torch.Tensor:
+ batch, seq_len, _ = hidden_states.shape
+ cache_layer: DeepseekV4CSACache = past_key_values.layers[layer_idx] if past_key_values is not None else None
+ kv = self.kv_proj(hidden_states)
+ gate = self.gate_proj(hidden_states)
+
+ if cache_layer is None:
+ usable = (kv.shape[1] // self.compress_rate) * self.compress_rate
+ chunk_kv, chunk_gate, first_window_position = kv[:, :usable], gate[:, :usable], 0
+ else:
+ chunk_kv, chunk_gate, first_window_position = cache_layer.store_compression_weights("compressor", kv, gate)
+
+ if chunk_kv.shape[1] > 0:
+ n_windows = chunk_kv.shape[1] // self.compress_rate
+ ratio = self.compress_rate
+ chunk_kv = chunk_kv.view(batch, n_windows, ratio, -1)
+ chunk_gate = chunk_gate.view(batch, n_windows, ratio, -1) + self.position_bias.to(chunk_gate.dtype)
+
+ # Lay out the two series in [B, n_win, 2*ratio, head_dim]: Cb
+ # (`[..., head_dim:]`) goes in the second half (current window),
+ # Ca of the previous window (`[..., :head_dim]`) goes in the
+ # first half. Window 0's first half stays zero-kv / -inf-gate
+ # (softmax weight 0) on the very first forward call; on later
+ # calls the cache fills it with the saved Ca slice.
+ new_kv = chunk_kv.new_zeros((batch, n_windows, 2 * ratio, self.head_dim))
+ new_gate = chunk_gate.new_full((batch, n_windows, 2 * ratio, self.head_dim), float("-inf"))
+ new_kv[:, :, ratio:] = chunk_kv[..., self.head_dim :]
+ new_gate[:, :, ratio:] = chunk_gate[..., self.head_dim :]
+ if n_windows > 1:
+ new_kv[:, 1:, :ratio] = chunk_kv[:, :-1, :, : self.head_dim]
+ new_gate[:, 1:, :ratio] = chunk_gate[:, :-1, :, : self.head_dim]
+ if cache_layer is not None:
+ prior_kv, prior_gate = cache_layer.update_overlap_state(
+ "compressor", chunk_kv, chunk_gate, self.head_dim
+ )
+ if prior_kv is not None:
+ new_kv[:, 0, :ratio] = prior_kv.to(new_kv.dtype)
+ new_gate[:, 0, :ratio] = prior_gate.to(new_gate.dtype)
+
+ # Softmax in fp32 for stability (logits in bf16/fp16 can collapse pairs that
+ # only differ by a small amount, especially with large window widths).
+ compressed = self.kv_norm(
+ (new_kv * new_gate.softmax(dim=2, dtype=torch.float32).to(new_kv.dtype)).sum(dim=2)
+ )
+ positions = torch.arange(n_windows, device=compressed.device)
+ positions = positions * self.compress_rate + first_window_position
+ positions = positions.unsqueeze(0).expand(batch, -1)
+ cos, sin = self.rotary_emb(compressed, position_ids=positions, layer_type=self.rope_layer_type)
+ compressed = apply_rotary_pos_emb(compressed.unsqueeze(1), cos, sin).squeeze(1)
+ else:
+ compressed = chunk_kv.new_zeros((batch, 0, self.head_dim))
+
+ if cache_layer is not None:
+ compressed = cache_layer.update_compressor_states("compressor", compressed)
+ compressed_kv = compressed.unsqueeze(1)
+
+ # Lightning Indexer: gather top-`index_topk` compressed entries per query.
+ # in some cases, the output index can return top-k positions that should not be attended to.
+ # Ex: for query at index 5, m=4, and `index_topk=1024`, 1024 index are return but only 2 should be
+ # attended to. The indexer marks the rest with `-1`; we clamp before the gather and keep the `valid`
+ # to drop them from the per-query block mask afterwards.
+ top_k_indices = self.indexer(hidden_states, q_residual, position_ids, past_key_values, layer_idx) # [B, S, k]
+ compressed_len = compressed_kv.shape[2]
+ valid = top_k_indices >= 0 # [B, S, k]
+ # Per-query block bias: query `t` may only see the cache entries that are <= `seq_len // m`
+ # and in these, only the ones marked valid by the indexer. Everything else is `-inf`.
+ # While the above negated the indexer, here we apply the "causal" masking.
+ safe_indices = torch.where(valid, top_k_indices, torch.full_like(top_k_indices, compressed_len))
+ block_bias = compressed_kv.new_full((batch, 1, seq_len, compressed_len + 1), float("-inf"))
+ block_bias.scatter_(-1, safe_indices.unsqueeze(1), 0.0)
+ return compressed_kv, block_bias[..., :compressed_len]
+
+
+def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
+ """
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
+ """
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
+ if n_rep == 1:
+ return hidden_states
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
+
+
+def eager_attention_forward(
+ module: nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: torch.Tensor | None,
+ scaling: float,
+ dropout: float | int = 0.0,
+ **kwargs,
+):
+ key_states = repeat_kv(key, module.num_key_value_groups)
+ value_states = repeat_kv(value, module.num_key_value_groups)
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
+ if attention_mask is not None:
+ attn_weights = attn_weights + attention_mask
+
+ sinks = module.sinks.reshape(1, -1, 1, 1).expand(query.shape[0], -1, query.shape[-2], -1)
+ combined_logits = torch.cat([attn_weights, sinks], dim=-1)
+
+ # This was not in the original implementation and slightly affect results; it prevents overflow in BF16/FP16
+ # when training with bsz>1 we clamp max values.
+
+ combined_logits = combined_logits - combined_logits.max(dim=-1, keepdim=True).values
+ probs = F.softmax(combined_logits, dim=-1, dtype=combined_logits.dtype)
+ scores = probs[..., :-1] # we drop the sink here
+ attn_weights = nn.functional.dropout(scores, p=dropout, training=module.training).to(value_states.dtype)
+ attn_output = torch.matmul(attn_weights, value_states)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+ return attn_output, attn_weights
+
+
+COMPRESSOR_CLASSES = {
+ "sliding_attention": None,
+ "compressed_sparse_attention": DeepseekV4CSACompressor,
+ "heavily_compressed_attention": DeepseekV4HCACompressor,
+}
+
+
+class DeepseekV4Attention(nn.Module):
+ r"""
+ Diff with classic attentions:
+ * Shared-KV Multi-Query Attention: `num_key_value_heads = 1`; `kv_proj` projects
+ directly to that single KV head and the same tensor is read as both key and
+ value.
+ * Partial RoPE on the first `rope_head_dim` of each head ("Partial Rotary
+ Positional Embedding"). RoPE is also applied with position `-i` to the
+ attention output's rope slice, so the contribution of each KV entry stays a
+ function of the *relative* distance to the query.
+ * Per-head learnable attention sink like gpt OSS.
+ * Grouped low-rank output projection for perfs.
+ * 3 different cache mechanisms, sliding, sliding+CSA, sliding+HCA.
+ """
+
+ def __init__(self, config: DeepseekV4Config, layer_idx: int):
+ super().__init__()
+ self.config = config
+ self.layer_idx = layer_idx
+ self.layer_type = config.layer_types[layer_idx]
+ # Sliding-only layers use the "main" (plain θ=10000) rope; CSA/HCA layers
+ # share the same yarn-scaled "compress" rope as their compressor.
+ self.rope_layer_type = "main" if self.layer_type == "sliding_attention" else "compress"
+ self.num_heads = config.num_attention_heads
+ self.num_key_value_groups = config.num_attention_heads # single KV head, broadcast to all
+ self.head_dim = config.head_dim
+ self.sliding_window = config.sliding_window
+ self.attention_dropout = config.attention_dropout
+ self.is_causal = True
+ self.scaling = self.head_dim**-0.5
+
+ self.q_a_proj = nn.Linear(config.hidden_size, config.q_lora_rank, bias=False)
+ self.q_a_norm = DeepseekV4RMSNorm(config.q_lora_rank, eps=config.rms_norm_eps)
+ self.q_b_proj = nn.Linear(config.q_lora_rank, self.num_heads * self.head_dim, bias=False)
+ self.q_b_norm = DeepseekV4UnweightedRMSNorm(eps=config.rms_norm_eps)
+ self.kv_proj = nn.Linear(config.hidden_size, self.head_dim, bias=False)
+ self.kv_norm = DeepseekV4RMSNorm(self.head_dim, eps=config.rms_norm_eps)
+ self.o_a_proj = DeepseekV4GroupedLinear(
+ self.num_heads * self.head_dim // config.o_groups, config.o_groups * config.o_lora_rank, config.o_groups
+ )
+ self.o_b_proj = nn.Linear(config.o_groups * config.o_lora_rank, config.hidden_size, bias=False)
+ self.sinks = nn.Parameter(torch.empty(self.num_heads))
+ self.compressor = (
+ COMPRESSOR_CLASSES[self.layer_type](config) if self.layer_type != "sliding_attention" else None
+ )
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ position_embeddings: dict[str, tuple[torch.Tensor, torch.Tensor]] | tuple[torch.Tensor, torch.Tensor],
+ position_ids: torch.Tensor,
+ attention_mask: torch.Tensor | None,
+ past_key_values: Cache | None = None,
+ **kwargs: Unpack[FlashAttentionKwargs],
+ ) -> tuple[torch.Tensor, torch.Tensor | None]:
+ input_shape = hidden_states.shape[:-1]
+ hidden_shape = (*input_shape, -1, self.head_dim)
+ # position_embeddings is a {"main", "compress"} dict from the model; pick the
+ # one that matches this layer's rope type (sliding → main, CSA/HCA → compress).
+ cos, sin = position_embeddings[self.rope_layer_type]
+
+ q_residual = self.q_a_norm(self.q_a_proj(hidden_states))
+ q = self.q_b_proj(q_residual).view(*hidden_shape).transpose(1, 2)
+ q = self.q_b_norm(q)
+ q = apply_rotary_pos_emb(q, cos, sin)
+
+ kv = self.kv_norm(self.kv_proj(hidden_states)).view(*hidden_shape).transpose(1, 2)
+ kv = apply_rotary_pos_emb(kv, cos, sin)
+
+ if past_key_values is not None: # sliding where K==V
+ kv = past_key_values.update(kv, kv, self.layer_idx)[0]
+
+ block_bias = None
+ if self.compressor is not None: # Compressed KV (CSA or HCA)
+ compressed_kv, block_bias = self.compressor(
+ hidden_states, q_residual, position_ids, past_key_values, self.layer_idx
+ )
+ kv = torch.cat([kv, compressed_kv], dim=2)
+
+ # The compressor path concatenates extra entries onto the KV axis after the
+ # standard sliding-window cache update, so a tensor `attention_mask` (built
+ # for the pre-concat KV length) needs to be extended to cover them. The
+ # compressor returns a `block_bias` carrying per-query causality + indexer
+ # validity over those new slots — cat it in instead of zero-padding (which
+ # would let every query see every compressed slot).
+ if isinstance(attention_mask, torch.Tensor) and kv.shape[2] > attention_mask.shape[-1]:
+ if block_bias is not None:
+ attention_mask = torch.cat([attention_mask, block_bias.to(attention_mask.dtype)], dim=-1)
+ else:
+ attention_mask = F.pad(attention_mask, (0, kv.shape[2] - attention_mask.shape[-1]), value=0.0)
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+ attn_output, attn_weights = attention_interface(
+ self,
+ q,
+ kv,
+ kv,
+ attention_mask,
+ dropout=0.0 if not self.training else self.attention_dropout,
+ scaling=self.scaling,
+ sliding_window=self.sliding_window,
+ s_aux=self.sinks,
+ **kwargs,
+ )
+
+ # K=V in V4, so V picked up rope on its trailing rope slice. Apply the conjugate
+ # rotation (`-sin`) at the query position to undo it on the rope slice of the
+ # output before the grouped output projection mixes heads. The transpose pair is
+ # just a layout fix-up: apply_rotary_pos_emb expects `[B, S, H, D]` (its
+ # `unsqueeze_dim=1` adds a head-broadcast dim to cos/sin); attention gave us
+ # `[B, H, S, D]`.
+ attn_output = apply_rotary_pos_emb(attn_output.transpose(1, 2), cos, -sin).transpose(1, 2)
+
+ grouped = attn_output.reshape(*input_shape, self.config.o_groups, -1)
+ grouped = self.o_a_proj(grouped).flatten(2)
+ output = self.o_b_proj(grouped)
+ return output, attn_weights
+
+
+class DeepseekV4HyperConnection(nn.Module):
+ r"""
+ Manifold-Constrained Hyper-Connections
+ (mHC) (Xie et al., 2026) to strengthen the conventional residual connections between adjacent
+ Transformer blocks
+
+ Owns the learned (`fn`, `base`, `scale`)
+ parameters that turn the incoming `hc_mult` residual streams into collapse / expand
+ weights. The decoder layer instantiates two of these (one for the attention site,
+ one for the mlp site).
+
+ ASCII shape guide — `B` = batch, `S` = seq, `H` = hc_mult, `D` = hidden_size::
+
+ hidden_streams flatten(2) RMSNorm-rescale + F.linear(fn)
+ [B, S, H, D] ──────────► [B, S, H*D] ─────────────────────────────────►
+ mix-logits
+ [B, S, (2+H)*H]
+ │
+ ┌───────────────────────────────────────┴──────────────────────────────┐
+ ▼ ▼ ▼
+ pre logits post logits comb logits
+ [B, S, H] [B, S, H] [B, S, H, H]
+ × scale[0] × scale[1] × scale[2]
+ + base[:H] + base[H:2H] + base[2H:]
+ σ() + eps σ() + eps σ() + eps
+ │ │ │
+ pre post Sinkhorn(iters)
+ (stream collapse weights) (block-output placement) row/col normalise
+ │
+ comb
+ (stream mixer)
+ """
+
+ def __init__(self, config: DeepseekV4Config):
+ super().__init__()
+ self.hc_mult = config.hc_mult
+ self.hc_sinkhorn_iters = config.hc_sinkhorn_iters
+ self.hc_eps = config.hc_eps
+ self.input_norm = DeepseekV4UnweightedRMSNorm(eps=config.rms_norm_eps)
+ mix = (2 + self.hc_mult) * self.hc_mult
+ self.fn = nn.Parameter(torch.empty(mix, self.hc_mult * config.hidden_size))
+ self.base = nn.Parameter(torch.empty(mix))
+ # 3 = number of outputs from the mHC mapping: `pre` (input projection
+ # weights), `post` (sublayer output projection weights), `comb` (the
+ # H×H residual combine matrix that gets Sinkhorn-projected onto the
+ # doubly-stochastic manifold). Each output gets its own learned scale.
+ self.scale = nn.Parameter(torch.empty(3))
+
+ def forward(self, hidden_streams: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ r"""
+ Compute `pre`, `post`, `comb` from the mHC mapping (paper §2.2 eq. 8).
+ `comb` is projected onto the doubly-stochastic manifold via Sinkhorn-
+ Knopp: starting from the sigmoid-positive matrix, alternate row and
+ column normalisation for `hc_sinkhorn_iters` steps. `pre` then collapses
+ the `hc_mult` parallel streams into a single sequence (input projection
+ into the sublayer); `post` and `comb` are returned for the caller to
+ apply on the sublayer output.
+ """
+ hc = self.hc_mult
+ flat = self.input_norm(hidden_streams.flatten(start_dim=2).float())
+ pre_w, post_w, comb_w = F.linear(flat, self.fn.float()).split([hc, hc, hc * hc], dim=-1)
+ pre_b, post_b, comb_b = self.base.split([hc, hc, hc * hc])
+ pre_scale, post_scale, comb_scale = self.scale.unbind(0)
+
+ pre = torch.sigmoid(pre_w * pre_scale + pre_b) + self.hc_eps
+ post = 2 * torch.sigmoid(post_w * post_scale + post_b)
+ comb_logits = comb_w.view(*comb_w.shape[:-1], hc, hc) * comb_scale + comb_b.view(hc, hc)
+ comb = torch.softmax(comb_logits, dim=-1) + self.hc_eps
+ comb = comb / (comb.sum(dim=-2, keepdim=True) + self.hc_eps)
+ for _ in range(self.hc_sinkhorn_iters - 1):
+ comb = comb / (comb.sum(dim=-1, keepdim=True) + self.hc_eps)
+ comb = comb / (comb.sum(dim=-2, keepdim=True) + self.hc_eps)
+ # Collapse the `hc_mult` parallel streams down to a single sequence using
+ # the `pre` weights: one weighted sum across the stream axis, ready for
+ # the sublayer (attn / MLP).
+ collapsed = (pre.unsqueeze(-1) * hidden_streams).sum(dim=2).to(hidden_streams.dtype)
+ return post, comb, collapsed
+
+
+class DeepseekV4HyperHead(nn.Module):
+ """Final HC-stream collapse; used by `DeepseekV4Model` before the shared RMSNorm."""
+
+ def __init__(self, config: DeepseekV4Config):
+ super().__init__()
+ self.hc_mult = config.hc_mult
+ self.input_norm = DeepseekV4UnweightedRMSNorm(eps=config.rms_norm_eps)
+ self.eps = config.hc_eps
+ self.hc_fn = nn.Parameter(torch.empty(self.hc_mult, self.hc_mult * config.hidden_size))
+ self.hc_base = nn.Parameter(torch.empty(self.hc_mult))
+ self.hc_scale = nn.Parameter(torch.empty(1))
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ flat = self.input_norm(x.flatten(2).float())
+ mixes = F.linear(flat, self.hc_fn.float())
+ pre = torch.sigmoid(mixes * self.hc_scale.float() + self.hc_base.float()) + self.eps
+ return (pre.unsqueeze(-1) * x).sum(dim=2).to(x.dtype)
+
+
+class DeepseekV4MLP(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.hidden_size = config.hidden_size
+ self.intermediate_size = config.intermediate_size
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
+ self.act_fn = ACT2FN[config.hidden_act]
+
+ def forward(self, x):
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
+ return down_proj
+
+
+@use_experts_implementation
+class DeepseekV4Experts(nn.Module):
+ """Collection of expert weights stored as 3D tensors."""
+
+ def __init__(self, config: DeepseekV4Config):
+ super().__init__()
+ self.num_experts = config.num_local_experts
+ self.hidden_dim = config.hidden_size
+ self.intermediate_dim = config.intermediate_size
+ self.gate_up_proj = nn.Parameter(torch.empty(self.num_experts, 2 * self.intermediate_dim, self.hidden_dim))
+ self.down_proj = nn.Parameter(torch.empty(self.num_experts, self.hidden_dim, self.intermediate_dim))
+ self.act_fn = ACT2FN[config.hidden_act]
+ self.limit = config.swiglu_limit
+
+ def forward(
+ self, hidden_states: torch.Tensor, top_k_index: torch.Tensor, top_k_weights: torch.Tensor
+ ) -> torch.Tensor:
+ final = torch.zeros_like(hidden_states)
+ with torch.no_grad():
+ mask = F.one_hot(top_k_index, num_classes=self.num_experts).permute(2, 1, 0)
+ hit = torch.greater(mask.sum(dim=(-1, -2)), 0).nonzero()
+ for expert_idx in hit:
+ expert_idx = expert_idx[0]
+ if expert_idx == self.num_experts:
+ continue
+ top_k_pos, token_idx = torch.where(mask[expert_idx])
+ current = self._apply_gate(F.linear(hidden_states[token_idx], self.gate_up_proj[expert_idx]))
+ current = F.linear(current, self.down_proj[expert_idx]) * top_k_weights[token_idx, top_k_pos, None]
+ final.index_add_(0, token_idx, current.to(final.dtype))
+ return final
+
+ def _apply_gate(self, gate_up: torch.Tensor) -> torch.Tensor:
+ # Lives on the class (like gpt-oss's _apply_gate) so the grouped_mm / batched_mm
+ # backends swapped in by `@use_experts_implementation` apply the same clamp +
+ # SiLU on top of their packed gate_up output instead of bypassing it.
+ gate, up = gate_up.chunk(2, dim=-1)
+ gate = gate.clamp(max=self.limit)
+ up = up.clamp(min=-self.limit, max=self.limit)
+ return self.act_fn(gate) * up
+
+
+class DeepseekV4TopKRouter(nn.Module):
+ def __init__(self, config: DeepseekV4Config):
+ super().__init__()
+ self.top_k = config.num_experts_per_tok
+ self.num_experts = config.num_local_experts
+ self.hidden_dim = config.hidden_size
+ self.weight = nn.Parameter(torch.empty(self.num_experts, self.hidden_dim))
+ self.score_fn = ACT2FN[config.scoring_func]
+ self.routed_scaling_factor = config.routed_scaling_factor
+ self.register_buffer("e_score_correction_bias", torch.zeros(self.num_experts), persistent=True)
+
+ def forward(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ flat = hidden_states.reshape(-1, self.hidden_dim)
+ logits = F.linear(flat, self.weight)
+ scores = self.score_fn(logits)
+ indices = torch.topk(scores + self.e_score_correction_bias, self.top_k, dim=-1, sorted=False).indices
+ weights = scores.gather(1, indices)
+ weights = weights / (weights.sum(dim=-1, keepdim=True) + 1e-20)
+ return logits, weights * self.routed_scaling_factor, indices
+
+
+class DeepseekV4HashRouter(nn.Module):
+ r"""
+ Hash routing for the first `mlp_layer_types == "hash_moe"` MoE layers (paper
+ §2.1). Expert selection is determined by a fixed `tid2eid[input_ids]` lookup —
+ a frozen token-id → expert-id table — instead of a learned argmax. The learned
+ gate `weight` still produces the per-expert scores that weight the selected
+ experts' activations; only the *which-experts* selection is static.
+ """
+
+ def __init__(self, config: DeepseekV4Config):
+ super().__init__()
+ self.top_k = config.num_experts_per_tok
+ self.num_experts = config.num_local_experts
+ self.hidden_dim = config.hidden_size
+ self.weight = nn.Parameter(torch.empty(self.num_experts, self.hidden_dim))
+ self.score_fn = ACT2FN[config.scoring_func]
+ self.routed_scaling_factor = config.routed_scaling_factor
+ self.register_buffer("tid2eid", torch.zeros(config.vocab_size, self.top_k, dtype=torch.long), persistent=True)
+
+ def forward(
+ self, hidden_states: torch.Tensor, input_ids: torch.Tensor
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ flat = hidden_states.reshape(-1, self.hidden_dim)
+ logits = F.linear(flat, self.weight)
+ scores = self.score_fn(logits)
+ indices = self.tid2eid[input_ids.reshape(-1)].long()
+ weights = scores.gather(1, indices)
+ weights = weights / (weights.sum(dim=-1, keepdim=True) + 1e-20)
+ return logits, weights * self.routed_scaling_factor, indices
+
+
+class DeepseekV4SparseMoeBlock(nn.Module):
+ def __init__(self, config: DeepseekV4Config, layer_idx: int):
+ super().__init__()
+ self.is_hash = config.mlp_layer_types[layer_idx] == "hash_moe"
+ self.gate = DeepseekV4HashRouter(config) if self.is_hash else DeepseekV4TopKRouter(config)
+ self.experts = DeepseekV4Experts(config)
+ self.shared_experts = DeepseekV4MLP(config)
+
+ def forward(self, hidden_states: torch.Tensor, input_ids: torch.Tensor | None = None) -> torch.Tensor:
+ batch, seq_len, hidden_dim = hidden_states.shape
+ residual = hidden_states
+ flat = hidden_states.view(-1, hidden_dim)
+ if self.is_hash:
+ _, weights, indices = self.gate(hidden_states, input_ids)
+ else:
+ _, weights, indices = self.gate(hidden_states)
+ routed = self.experts(flat, indices, weights).view(batch, seq_len, hidden_dim)
+ return routed + self.shared_experts(residual)
+
+
+class DeepseekV4DecoderLayer(GradientCheckpointingLayer):
+ r"""DeepSeek-V4 decoder block (paper §2). Differs from a classic residual block in
+ two places:
+
+ The residual is a stack of `hc_mult` parallel streams kept in shape
+ `[B, S, hc_mult, D]` throughout the block, mixed in and out via two
+ :class:`DeepseekV4HyperConnection` modules (Manifold-Constrained Hyper-
+ Connections / mHC, paper §2.2; Xie et al., 2026). The mHC mappings constrain
+ the residual transform to the manifold of doubly-stochastic matrices via the
+ Sinkhorn-Knopp projection — making signal propagation non-expansive across
+ deep stacks.
+
+ """
+
+ def __init__(self, config: DeepseekV4Config, layer_idx: int):
+ super().__init__()
+ self.layer_idx = layer_idx
+ self.self_attn = DeepseekV4Attention(config, layer_idx)
+ self.mlp = DeepseekV4SparseMoeBlock(config, layer_idx)
+ self.input_layernorm = DeepseekV4RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.post_attention_layernorm = DeepseekV4RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.attn_hc = DeepseekV4HyperConnection(config)
+ self.ffn_hc = DeepseekV4HyperConnection(config)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ input_ids: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.Tensor:
+ # hidden_states throughout: [B, S, hc_mult, hidden].
+ # `post` / `comb` come out of the HC modules in fp32 (Sinkhorn projection runs
+ # in float); the .to(dtype) puts everything back to the input dtype before mixing
+ # so both sites stay consistent with `hidden_states`'s entry dtype.
+ # comb is consumed transposed: indexed as sum_j comb[j, k] * residual[j, d]
+ # (sum over the FIRST hc axis), equivalent to comb.T @ residual. Sinkhorn
+ # produces a doubly-stochastic but non-symmetric matrix, so the direction matters.
+ dtype = hidden_states.dtype
+ post, comb, collapsed = self.attn_hc(hidden_states)
+ attn_output, _ = self.self_attn(self.input_layernorm(collapsed), **kwargs)
+ hidden_states = post.to(dtype).unsqueeze(-1) * attn_output.unsqueeze(-2) + torch.matmul(
+ comb.to(dtype).transpose(-1, -2), hidden_states
+ )
+
+ post, comb, collapsed = self.ffn_hc(hidden_states)
+ mlp_output = self.mlp(self.post_attention_layernorm(collapsed), input_ids=input_ids)
+ return post.to(dtype).unsqueeze(-1) * mlp_output.unsqueeze(-2) + torch.matmul(
+ comb.to(dtype).transpose(-1, -2), hidden_states
+ )
+
+
+@auto_docstring
+class DeepseekV4PreTrainedModel(PreTrainedModel):
+ config: DeepseekV4Config
+ base_model_prefix = "model"
+ supports_gradient_checkpointing = True
+ _no_split_modules = ["DeepseekV4DecoderLayer"]
+ _skip_keys_device_placement = ["past_key_values"]
+ # V4 ships eager-only. The non-eager backends are off for the following reasons:
+ #
+ # * FlashAttention 2 / 3 cap the head dim at 256; V4's `head_dim=512`
+ # (V4-Flash and V4-Pro both) is structurally incompatible — `flash_attention_2`
+ # and the `kernels-community/vllm-flash-attn3` kernel both fail with
+ # `RuntimeError: FlashAttention forward only supports head dimension at most
+ # 256`. FA4 has the same 256 cap, so it's off too.
+ # * SDPA: torch's SDPA kernel doesn't carry the per-head learnable sink term V4
+ # inherits from gpt-oss-style attention.
+ # * FlexAttention: V4 attention concatenates compressor entries onto the KV
+ # axis *inside* the attention block, after the model-level mask was built,
+ # so the resulting KV length doesn't match the BlockMask's `kv_len`.
+ # BlockMask has no runtime resize, and rebuilding it per-block would require
+ # teaching the compressor's variable output count to a `mask_mod` — not
+ # worth it for a path the compressor already owns its own causality
+ # bookkeeping for.
+ _supports_flash_attn = False
+ _supports_sdpa = False
+ _supports_flex_attn = False
+ # The compressor's rolling-window buffer / compressed-entries / overlap state
+ # lives on the per-layer cache (:class:`DeepseekV4HCACache` /
+ # :class:`DeepseekV4CSACache`) and isn't compatible with :class:`StaticCache`
+ # — that path would hand the compressor a :class:`StaticSlidingWindowLayer`
+ # with no `store_compression_weights` method. Disabling fullgraph compile
+ # keeps generation tests on the dynamic cache build that does dispatch to
+ # V4's own cache layers.
+ _can_compile_fullgraph = False
+ _supports_attention_backend = True
+ _can_record_outputs = {
+ "router_logits": OutputRecorder(DeepseekV4TopKRouter, index=0),
+ "hidden_states": DeepseekV4DecoderLayer,
+ "attentions": DeepseekV4Attention,
+ }
+ config_class = DeepseekV4Config
+ _keep_in_fp32_modules_strict = [
+ "attn_hc",
+ "ffn_hc",
+ "e_score_correction_bias",
+ "q_a_norm",
+ "kv_norm",
+ "input_layernorm",
+ "post_attention_layernorm",
+ "norm",
+ ]
+ _keys_to_ignore_on_load_unexpected = [r"(^|\.)mtp\..*"]
+ # ``_is_stateful`` opts out of generation modes that need to roll the cache
+ # back across drafts (assisted generation, prompt lookup, contrastive search).
+ # The compressor's running-window state isn't rewindable, so `generate`
+ # raises a clear error early instead of failing deep in the compressor with
+ # a missing-method `AttributeError`.
+ _is_stateful = True
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ super()._init_weights(module)
+ std = self.config.initializer_range
+ if isinstance(module, (DeepseekV4TopKRouter, DeepseekV4HashRouter)):
+ init.normal_(module.weight, mean=0.0, std=std)
+ if isinstance(module, DeepseekV4TopKRouter):
+ init.zeros_(module.e_score_correction_bias) # buffer
+ if isinstance(module, DeepseekV4HashRouter):
+ init.zeros_(module.tid2eid) # buffer; real values come from the checkpoint
+ elif isinstance(module, DeepseekV4Experts):
+ init.normal_(module.gate_up_proj, mean=0.0, std=std)
+ init.normal_(module.down_proj, mean=0.0, std=std)
+ elif isinstance(module, DeepseekV4Attention):
+ init.zeros_(module.sinks)
+ elif isinstance(module, DeepseekV4HyperConnection):
+ init.normal_(module.fn, mean=0.0, std=std)
+ init.zeros_(module.base)
+ init.ones_(module.scale)
+ elif isinstance(module, DeepseekV4HyperHead):
+ init.normal_(module.hc_fn, mean=0.0, std=std)
+ init.zeros_(module.hc_base)
+ init.ones_(module.hc_scale)
+ elif isinstance(module, (DeepseekV4HCACompressor, DeepseekV4CSACompressor, DeepseekV4Indexer)):
+ init.zeros_(module.position_bias)
+ elif isinstance(module, DeepseekV4RotaryEmbedding):
+ for layer_type in module.layer_types:
+ rope_init_fn = module.compute_default_rope_parameters
+ if module.rope_type[layer_type] != "default":
+ rope_init_fn = ROPE_INIT_FUNCTIONS[module.rope_type[layer_type]]
+ curr_inv_freq, _ = rope_init_fn(module.config, layer_type=layer_type)
+ init.copy_(getattr(module, f"{layer_type}_inv_freq"), curr_inv_freq)
+ init.copy_(getattr(module, f"{layer_type}_original_inv_freq"), curr_inv_freq)
+
+
+@auto_docstring
+class DeepseekV4Model(DeepseekV4PreTrainedModel):
+ def __init__(self, config: DeepseekV4Config):
+ super().__init__(config)
+ self.padding_idx = config.pad_token_id
+ self.vocab_size = config.vocab_size
+
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
+ self.layers = nn.ModuleList(
+ [DeepseekV4DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
+ )
+ self.norm = DeepseekV4RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.rotary_emb = DeepseekV4RotaryEmbedding(config)
+ self.gradient_checkpointing = False
+ self.hc_head = DeepseekV4HyperHead(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @merge_with_config_defaults
+ @capture_outputs
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ use_cache: bool | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> MoeModelOutputWithPast:
+ if (input_ids is None) ^ (inputs_embeds is not None):
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
+ return_cache = past_key_values if use_cache else None
+ if past_key_values is None:
+ past_key_values = DynamicCache(config=self.config)
+ if inputs_embeds is None:
+ inputs_embeds = self.embed_tokens(input_ids)
+ if position_ids is None:
+ past_seen = past_key_values.get_seq_length()
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen
+ position_ids = position_ids.unsqueeze(0)
+ # `generate()` may pass a per-layer-type mask dict already built by
+ # `create_masks_for_generate`; all V4 layer types use the same sliding-window
+ # mask, so use the prebuilt one directly. Otherwise build it here.
+ if isinstance(attention_mask, dict):
+ causal_mask = next(iter(attention_mask.values()))
+ else:
+ causal_mask = create_sliding_window_causal_mask(
+ config=self.config,
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ position_ids=position_ids,
+ )
+ hidden_states = inputs_embeds.unsqueeze(2).expand(-1, -1, self.config.hc_mult, -1).contiguous()
+ position_embeddings = {
+ "main": self.rotary_emb(inputs_embeds, position_ids=position_ids, layer_type="main"),
+ "compress": self.rotary_emb(inputs_embeds, position_ids=position_ids, layer_type="compress"),
+ }
+
+ for layer in self.layers:
+ hidden_states = layer(
+ hidden_states,
+ position_embeddings=position_embeddings,
+ position_ids=position_ids,
+ attention_mask=causal_mask,
+ input_ids=input_ids,
+ past_key_values=past_key_values,
+ **kwargs,
+ )
+
+ hidden_states = self.norm(self.hc_head(hidden_states))
+ return MoeModelOutputWithPast(last_hidden_state=hidden_states, past_key_values=return_cache)
+
+
+def load_balancing_loss_func(
+ gate_logits: torch.Tensor | tuple[torch.Tensor] | None,
+ num_experts: int | None = None,
+ top_k=2,
+ attention_mask: torch.Tensor | None = None,
+) -> torch.Tensor | int:
+ r"""
+ Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
+
+ See Switch Transformer (https://huggingface.co/papers/2101.03961) for more details. This function implements the loss
+ function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
+ experts is too unbalanced.
+
+ Args:
+ gate_logits:
+ Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of
+ shape [batch_size X sequence_length, num_experts].
+ num_experts:
+ Number of experts
+ top_k:
+ The number of experts to route per-token, can be also interpreted as the `top-k` routing
+ parameter.
+ attention_mask (`torch.Tensor`, *optional*):
+ The attention_mask used in forward function
+ shape [batch_size X sequence_length] if not None.
+
+ Returns:
+ The auxiliary loss.
+ """
+ if gate_logits is None or not isinstance(gate_logits, tuple):
+ return 0
+
+ if isinstance(gate_logits, tuple):
+ compute_device = gate_logits[0].device
+ concatenated_gate_logits = torch.cat([layer_gate.to(compute_device) for layer_gate in gate_logits], dim=0)
+
+ routing_weights = torch.nn.functional.softmax(concatenated_gate_logits, dim=-1)
+
+ _, selected_experts = torch.topk(routing_weights, top_k, dim=-1)
+
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_experts)
+
+ if attention_mask is None:
+ # Compute the percentage of tokens routed to each experts
+ tokens_per_expert = torch.mean(expert_mask.float(), dim=0)
+
+ # Compute the average probability of routing to these experts
+ router_prob_per_expert = torch.mean(routing_weights, dim=0)
+ else:
+ batch_size, sequence_length = attention_mask.shape
+ num_hidden_layers = concatenated_gate_logits.shape[0] // (batch_size * sequence_length)
+
+ # Compute the mask that masks all padding tokens as 0 with the same shape of expert_mask
+ expert_attention_mask = (
+ attention_mask[None, :, :, None, None]
+ .expand((num_hidden_layers, batch_size, sequence_length, top_k, num_experts))
+ .reshape(-1, top_k, num_experts)
+ .to(compute_device)
+ )
+
+ # Compute the percentage of tokens routed to each experts
+ tokens_per_expert = torch.sum(expert_mask.float() * expert_attention_mask, dim=0) / torch.sum(
+ expert_attention_mask, dim=0
+ )
+
+ # Compute the mask that masks all padding tokens as 0 with the same shape of tokens_per_expert
+ router_per_expert_attention_mask = (
+ attention_mask[None, :, :, None]
+ .expand((num_hidden_layers, batch_size, sequence_length, num_experts))
+ .reshape(-1, num_experts)
+ .to(compute_device)
+ )
+
+ # Compute the average probability of routing to these experts
+ router_prob_per_expert = torch.sum(routing_weights * router_per_expert_attention_mask, dim=0) / torch.sum(
+ router_per_expert_attention_mask, dim=0
+ )
+
+ overall_loss = torch.sum(tokens_per_expert * router_prob_per_expert.unsqueeze(0))
+ return overall_loss * num_experts
+
+
+@auto_docstring
+class DeepseekV4ForCausalLM(DeepseekV4PreTrainedModel, GenerationMixin):
+ _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
+ _tp_plan = {"lm_head": "colwise_gather_output"}
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
+
+ def __init__(self, config):
+ super().__init__(config)
+ self.model = DeepseekV4Model(config)
+ self.vocab_size = config.vocab_size
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
+ self.router_aux_loss_coef = config.router_aux_loss_coef
+ self.num_experts = config.num_local_experts
+ self.num_experts_per_tok = config.num_experts_per_tok
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ use_cache: bool | None = None,
+ output_router_logits: bool | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> MoeCausalLMOutputWithPast:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
+
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, DeepseekV4ForCausalLM
+
+ >>> model = DeepseekV4ForCausalLM.from_pretrained("mistralai/DeepseekV4-8x7B-v0.1")
+ >>> tokenizer = AutoTokenizer.from_pretrained("mistralai/DeepseekV4-8x7B-v0.1")
+
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
+
+ >>> # Generate
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
+ ```"""
+
+ output_router_logits = (
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
+ )
+
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
+ outputs: MoeModelOutputWithPast = self.model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ output_router_logits=output_router_logits,
+ **kwargs,
+ )
+
+ hidden_states = outputs.last_hidden_state
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
+
+ aux_loss = None
+ if output_router_logits:
+ aux_loss = load_balancing_loss_func(
+ outputs.router_logits,
+ self.num_experts,
+ self.num_experts_per_tok,
+ attention_mask,
+ )
+ if labels is not None:
+ loss += self.router_aux_loss_coef * aux_loss.to(loss.device) # make sure to reside in the same device
+
+ return MoeCausalLMOutputWithPast(
+ loss=loss,
+ aux_loss=aux_loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ router_logits=outputs.router_logits,
+ )
+
+
+__all__ = ["DeepseekV4PreTrainedModel", "DeepseekV4Model", "DeepseekV4ForCausalLM"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/deepseek_v4/modular_deepseek_v4.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/deepseek_v4/modular_deepseek_v4.py
new file mode 100644
index 0000000000000000000000000000000000000000..5f121b99b30fe4116d7bf866733c2f4be177412d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/deepseek_v4/modular_deepseek_v4.py
@@ -0,0 +1,1175 @@
+# Copyright 2026 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from collections.abc import Callable
+
+import torch
+import torch.nn.functional as F
+from torch import nn
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...cache_utils import Cache, DynamicCache, DynamicSlidingWindowLayer
+from ...integrations import use_experts_implementation
+from ...masking_utils import create_sliding_window_causal_mask
+from ...modeling_flash_attention_utils import FlashAttentionKwargs
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import MoeModelOutputWithPast
+from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import TransformersKwargs, auto_docstring, logging
+from ...utils.generic import maybe_autocast, merge_with_config_defaults
+from ...utils.output_capturing import OutputRecorder, capture_outputs
+from ..deepseek_v3.modeling_deepseek_v3 import DeepseekV3RMSNorm
+from ..glm.modeling_glm import rotate_half
+from ..gpt_oss.modeling_gpt_oss import eager_attention_forward
+from ..laguna.modeling_laguna import LagunaRotaryEmbedding
+from ..llama.modeling_llama import LlamaMLP, LlamaModel
+from ..mixtral.modeling_mixtral import MixtralExperts, MixtralForCausalLM, MixtralPreTrainedModel, MixtralTopKRouter
+from .configuration_deepseek_v4 import DeepseekV4Config
+
+
+logger = logging.get_logger(__name__)
+
+
+def apply_rotary_pos_emb(
+ x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, unsqueeze_dim: int = 1
+) -> torch.Tensor:
+ """V4 interleaved RoPE applied to the *trailing* rope slice of `x`.
+
+ `cos` / `sin` come in half-sized (one entry per interleaved pair, from
+ `DeepseekV4RotaryEmbedding`); we expand them to the full rope dim with
+ `repeat_interleave`, then rotate the last `2 * cos.shape[-1]` channels of `x`
+ with the standard `x*cos + rotate_half(x)*sin` formula in fp32 and leave the
+ leading nope channels untouched. V4-Flash lays each head out as `[nope | rope]`,
+ matching the reference's `x[..., -rd:]` indexing.
+ """
+ cos = cos.repeat_interleave(2, dim=-1).unsqueeze(unsqueeze_dim)
+ sin = sin.repeat_interleave(2, dim=-1).unsqueeze(unsqueeze_dim)
+ rope_dim = cos.shape[-1]
+ nope, rope = x[..., :-rope_dim], x[..., -rope_dim:]
+ rotated = ((rope.float() * cos) + (rotate_half(rope).float() * sin)).to(x.dtype)
+ return torch.cat([nope, rotated], dim=-1)
+
+
+class DeepseekV4RMSNorm(DeepseekV3RMSNorm):
+ pass
+
+
+class DeepseekV4UnweightedRMSNorm(nn.Module):
+ def __init__(self, eps: float = 1.0e-6):
+ super().__init__()
+ self.eps = eps
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ return x * torch.rsqrt(x.float().square().mean(-1, keepdim=True) + self.eps).to(x.dtype)
+
+
+class DeepseekV4RotaryEmbedding(LagunaRotaryEmbedding):
+ """
+ Multi-layer-type rotary embedding (Laguna pattern: partial rotary on top of
+ Gemma3's per-layer-type buffers), specialised for V4's *interleaved* RoPE.
+ Interleaved RoPE: one `θ_i` per pair (`rope_head_dim // 2` entries),
+ DIFF no end-to-end duplication. Same shape as `inv_freq @ position_ids`.
+
+ V4 deliberately decouples its architecture `layer_types`
+ (`sliding_attention` / `compressed_sparse_attention` /
+ `heavily_compressed_attention`) from its rope-type labels (`main` /
+ `compress`) — the latter live as keys in `config.rope_parameters` and
+ only differ in their `rope_theta` base. So this override replaces
+ Laguna's `set(config.layer_types)` iteration with `rope_parameters.keys()`
+ when building the per-type inv_freq buffers.
+ """
+
+ def __init__(self, config: DeepseekV4Config):
+ nn.Module.__init__(self)
+ self.max_seq_len_cached = config.max_position_embeddings
+ self.original_max_seq_len = config.max_position_embeddings
+ self.config = config
+ # Only the nested per-rope-type sub-dicts are real layer types — the top-level
+ # `rope_type` key that ``convert_rope_params_to_dict`` may leave on
+ # ``config.rope_parameters`` is a flat-shape leftover, not a layer.
+ self.layer_types = [k for k, v in config.rope_parameters.items() if isinstance(v, dict)]
+ self.rope_type = {}
+ for layer_type in self.layer_types:
+ rope_params = config.rope_parameters[layer_type]
+ self.rope_type[layer_type] = rope_params["rope_type"]
+ rope_init_fn = self.compute_default_rope_parameters
+ if self.rope_type[layer_type] != "default":
+ rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type[layer_type]]
+ inv_freq, attention_scaling = rope_init_fn(config, layer_type=layer_type)
+ self.register_buffer(f"{layer_type}_inv_freq", inv_freq, persistent=False)
+ self.register_buffer(f"{layer_type}_original_inv_freq", inv_freq.clone(), persistent=False)
+ setattr(self, f"{layer_type}_attention_scaling", attention_scaling)
+
+ def forward(self, x, position_ids, layer_type=None):
+ # Key difference vs Laguna's forward: no `torch.cat([freqs, freqs], dim=-1)`
+ # duplication. V4's interleaved RoPE pairs consecutive channels, so we only need
+ # `rope_head_dim // 2` unique θ entries — the `apply_rotary_pos_emb` helper does
+ # the `repeat_interleave(2)` next to the rotation math, where the link between
+ # the doubled dim and `rotate_half` is local and obvious.
+ inv_freq = getattr(self, f"{layer_type}_inv_freq")
+ attention_scaling = getattr(self, f"{layer_type}_attention_scaling")
+ inv_freq_expanded = inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
+ position_ids_expanded = position_ids[:, None, :].float()
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
+ with maybe_autocast(device_type=device_type, enabled=False):
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
+ cos = freqs.cos() * attention_scaling
+ sin = freqs.sin() * attention_scaling
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
+
+
+class DeepseekV4HCACache(DynamicSlidingWindowLayer):
+ r"""Cache layer for HCA blocks (paper §2.3.2). Holds the long-range compressor's
+ buffer / running compressed entries / count on top of the sliding-window K=V
+ branch. HCA uses *non-overlapping* windows, so there is *no* overlap state,
+ and HCA has *no* indexer either.
+
+ State is dict-keyed by entry name — HCA only uses `"compressor"`, but
+ :class:`DeepseekV4CSACache` adds `"indexer"` to the same dicts so a single
+ set of methods (`store_compression_weights` / `update_compressor_states`)
+ serves both:
+
+ * `compressed_kv[name]` — the running list of compressed KV entries
+ emitted so far (one every `compress_rate` source tokens; the long-range
+ KVs the attention concatenates onto its sliding-window keys / values).
+ * `buffer_kv[name]` / `buffer_gate[name]` — source tokens that arrived
+ between two full windows; once the buffer hits `compress_rate` tokens
+ the compressor closes a window, emits one entry, and drains the buffer.
+ * `entry_count[name]` — number of compressed entries emitted so far, so
+ `entry_count[name] * compress_rate` is the absolute position of the
+ *next* window's first source token. Tracked separately from
+ `position_ids` so prefill -> decode -> prefill stays consistent.
+ """
+
+ layer_type = "heavily_compressed_attention"
+
+ def __init__(self, config: "DeepseekV4Config"):
+ super().__init__(config)
+ self.compress_rate = config.compress_rates["heavily_compressed_attention"]
+ self.buffer_kv: dict[str, torch.Tensor | None] = {"compressor": None}
+ self.buffer_gate: dict[str, torch.Tensor | None] = {"compressor": None}
+ self.compressed_kv: dict[str, torch.Tensor | None] = {"compressor": None}
+ self.entry_count: dict[str, int] = {"compressor": 0}
+
+ def update(self, key_states: torch.Tensor, value_states: torch.Tensor, *args, **kwargs):
+ """
+ Shared sliding-window K=V update body. V4 uses shared-KV MQA, so `keys` and
+ `values` point to the same storage on every layer.
+ """
+ if not self.is_initialized:
+ self.lazy_initialization(key_states, value_states)
+ self.values = self.keys
+ self.cumulative_length += key_states.shape[-2]
+ full = torch.cat([self.keys, key_states], dim=-2)
+ self.keys = full[:, :, -self.sliding_window + 1 :, :]
+ self.values = self.keys
+ return full, full
+
+ def store_compression_weights(
+ self, name: str, kv: torch.Tensor, gate: torch.Tensor
+ ) -> tuple[torch.Tensor, torch.Tensor, int]:
+ r"""
+ Concatenate the new projected `(kv, gate)` (paper §2.3.2 eqs. 20–21:
+ `C = H·W^{KV}`, `Z = H·W^Z`) for entry `name` with what's already in
+ the buffer, peel off the longest window-aligned prefix (the chunk
+ ready to compress), keep the leftover in the buffer for next call,
+ and return `(chunk_kv, chunk_gate, first_window_position)`. The
+ returned chunk is softmax-aggregated by the compressor with
+ `position_bias` to emit one compressed entry per window of
+ `compress_rate` tokens.
+ """
+ first_window_position = self.entry_count[name] * self.compress_rate
+ buffered_kv, buffered_gate = self.buffer_kv[name], self.buffer_gate[name]
+ if buffered_kv is not None and buffered_kv.shape[1]:
+ kv = torch.cat([buffered_kv, kv], dim=1)
+ gate = torch.cat([buffered_gate, gate], dim=1)
+ # only return the longest prefix that's a multiple of compress_rate; the rest stays in the buffer for next time
+ usable = (kv.shape[1] // self.compress_rate) * self.compress_rate
+ self.buffer_kv[name], self.buffer_gate[name] = kv[:, usable:], gate[:, usable:]
+ return kv[:, :usable], gate[:, :usable], first_window_position
+
+ def update_compressor_states(self, name: str, compressed: torch.Tensor) -> torch.Tensor:
+ r"""
+ Append freshly emitted compressed entries to `compressed_kv[name]`
+ (`C^{Comp}`, paper §2.3.2 eq. 23), bump `entry_count[name]`, and
+ return the running `compressed_kv[name]`.
+ """
+ if self.compressed_kv[name] is None:
+ self.compressed_kv[name] = compressed
+ elif compressed.shape[1] > 0:
+ self.compressed_kv[name] = torch.cat([self.compressed_kv[name], compressed], dim=1)
+ self.entry_count[name] += compressed.shape[1]
+ return self.compressed_kv[name]
+
+
+class DeepseekV4CSACache(DeepseekV4HCACache):
+ r"""Cache layer for CSA blocks (paper §2.3.1). Extends :class:`DeepseekV4HCACache`
+ by adding an `"indexer"` entry to the inherited `buffer_kv` / `buffer_gate` /
+ `compressed_kv` / `entry_count` dicts, plus per-name *overlap* state for the
+ two-series window scheme.
+
+ What "overlap" means here: the CSA `kv_proj` / `gate_proj` produce `2 * head_dim`
+ features per source token — two independent compressed series Ca and Cb stored
+ in one tensor. Ca occupies `[..., :head_dim]`, Cb occupies `[..., head_dim:]`.
+ Pooled entry `w` is the softmax-gated convex combination of window `w-1`'s Ca
+ slice with window `w`'s Cb slice — effective width `2 * compress_rate_csa`,
+ stride `compress_rate_csa` (paper §2.3.1).
+
+ Because adjacent windows share state only through *the previous window's Ca
+ slice*, the only thing we need to carry across a forward boundary is
+ `chunk[:, -1, :, :head_dim]` (Ca) of the last full window — Cb is never read
+ again. That's what `overlap_kv[name]` / `overlap_gate[name]` persist.
+ """
+
+ layer_type = "compressed_sparse_attention"
+
+ def __init__(self, config: "DeepseekV4Config"):
+ super().__init__(config)
+ self.compress_rate = config.compress_rates["compressed_sparse_attention"]
+ self.buffer_kv["indexer"] = None
+ self.buffer_gate["indexer"] = None
+ self.compressed_kv["indexer"] = None
+ self.entry_count["indexer"] = 0
+ self.overlap_kv: dict[str, torch.Tensor | None] = {"compressor": None, "indexer": None}
+ self.overlap_gate: dict[str, torch.Tensor | None] = {"compressor": None, "indexer": None}
+
+ def update_overlap_state(
+ self, name: str, chunk_kv: torch.Tensor, chunk_gate: torch.Tensor, head_dim: int
+ ) -> tuple[torch.Tensor | None, torch.Tensor | None]:
+ r"""
+ Read the `name` entry's prior window's Ca slice (saved on the previous
+ forward call) and persist the *current* call's last-window Ca slice for
+ the next call. Only the `:head_dim` slice (Ca) is ever consumed
+ downstream — Cb has already been folded into the previous window's
+ emitted compressed entry — so we store half what `chunk[:, -1]` holds.
+ Returns `(prior_kv, prior_gate)` — both `None` on the very first call.
+ """
+ prior_kv, prior_gate = self.overlap_kv[name], self.overlap_gate[name]
+ self.overlap_kv[name] = chunk_kv[:, -1, :, :head_dim].clone()
+ self.overlap_gate[name] = chunk_gate[:, -1, :, :head_dim].clone()
+ return prior_kv, prior_gate
+
+
+class DeepseekV4GroupedLinear(nn.Linear):
+ """Block-diagonal grouped linear used by the grouped output projection
+ The core attention's stacked output is `num_attention_heads* head_dim`-dim,
+ which is *very* large (V4-Flash: 32768; V4-Pro: 65536). A direct
+ `num_attention_heads*head_dim → hidden_size` projection would dominate the per-token cost.
+
+ The paper sidesteps that by splitting the heads into `g` groups, projecting
+ each `num_attention_heads * head_dim/g`-dim group independently to a `d_g`-dim intermediate output
+ (with `d_g < num_attention_heads * head_dim/g`), and then mixing the resulting `g·d_g` vector to
+ `hidden_size` through a single follow-up linear (`self_attn.o_b_proj`). This
+ module owns the per-group block (`self_attn.o_a_proj`).
+
+ For V4-Flash (num_attention_heads=64, head_dim=512, o_groups=8, o_lora_rank=1024,
+ hidden_size=4096), g=8 groups of 4096-dim each are projected to 1024-dim, then
+ mixed to 4096-dim; for V4-Pro (num_attention_heads=128, head_dim=512, o_groups=16,
+ o_lora_rank=1024, hidden_size=7168), g=16 groups of 4096-dim each are projected
+ to 1024-dim, then mixed to 7168-dim.
+ """
+
+ def __init__(self, in_features_per_group: int, out_features: int, n_groups: int, bias: bool = False):
+ super().__init__(in_features_per_group, out_features, bias=bias)
+ self.n_groups = n_groups
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ input_shape = x.shape[:-2]
+ hidden_dim = x.shape[-1]
+ w = self.weight.view(self.n_groups, -1, hidden_dim).transpose(1, 2)
+ x = x.reshape(-1, self.n_groups, hidden_dim).transpose(0, 1)
+ y = torch.bmm(x, w).transpose(0, 1)
+ return y.reshape(*input_shape, self.n_groups, -1)
+
+
+class DeepseekV4HCACompressor(nn.Module):
+ """
+ Heavily Compressed Attention compressor (paper §2.3.2, eqs. 20–23). compresses
+ every `compress_rate_hca` (m'=128) source tokens into a single compressed KV
+ entry.
+
+ Each closed window of m' tokens produces one compressed entry:
+ `C^{Comp}_i = Σ_{j∈window} softmax(Z_j + B)_j ⊙ C_j`. RoPE on the trailing
+ `rope_head_dim` slice is applied at the deterministic absolute position
+ `i * compress_rate_hca + first_window_position` so cross-call concatenation
+ stays causality-correct. Returns the running list of *all* compressed
+ entries emitted so far (shape `[B, 1, T, head_dim]` with
+ `T = entry_count["compressor"]`), so the attention can attend over the
+ full long-range history.
+
+ When `past_key_values is None` runs in stateless single-shot mode: compress
+ every complete window from `hidden_states` and discard the remainder
+ (instead of caching it).
+ """
+
+ rope_layer_type = "compress"
+
+ def __init__(self, config: DeepseekV4Config):
+ super().__init__()
+ self.compress_rate = config.compress_rates["heavily_compressed_attention"]
+ self.head_dim = config.head_dim
+ self.kv_proj = nn.Linear(config.hidden_size, self.head_dim, bias=False)
+ self.gate_proj = nn.Linear(config.hidden_size, self.head_dim, bias=False)
+ self.position_bias = nn.Parameter(torch.empty(self.compress_rate, self.head_dim))
+ self.kv_norm = DeepseekV4RMSNorm(self.head_dim, eps=config.rms_norm_eps)
+ self.rotary_emb = DeepseekV4RotaryEmbedding(config)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ q_residual: torch.Tensor,
+ position_ids: torch.Tensor,
+ past_key_values: Cache | None,
+ layer_idx: int,
+ ) -> tuple[torch.Tensor, torch.Tensor]:
+ batch, _, _ = hidden_states.shape
+ cache_layer: DeepseekV4HCACache = past_key_values.layers[layer_idx] if past_key_values is not None else None
+ kv = self.kv_proj(hidden_states)
+ gate = self.gate_proj(hidden_states)
+ if cache_layer is None:
+ usable = (kv.shape[1] // self.compress_rate) * self.compress_rate
+ chunk_kv, chunk_gate, first_window_position = kv[:, :usable], gate[:, :usable], 0
+ else:
+ chunk_kv, chunk_gate, first_window_position = cache_layer.store_compression_weights("compressor", kv, gate)
+
+ if chunk_kv.shape[1] > 0: # there were at least self.compress_rate tokens
+ n_windows = chunk_kv.shape[1] // self.compress_rate
+ chunk_kv = chunk_kv.view(batch, n_windows, self.compress_rate, -1)
+ chunk_gate = chunk_gate.view(batch, n_windows, self.compress_rate, -1) + self.position_bias.to(
+ chunk_gate.dtype
+ )
+ compressed = self.kv_norm(
+ (chunk_kv * chunk_gate.softmax(dim=2, dtype=torch.float32).to(chunk_kv.dtype)).sum(dim=2)
+ )
+ positions = torch.arange(n_windows, device=compressed.device)
+ positions = (positions * self.compress_rate + first_window_position).unsqueeze(0).expand(batch, -1)
+ cos, sin = self.rotary_emb(compressed, position_ids=positions, layer_type=self.rope_layer_type)
+ compressed = apply_rotary_pos_emb(compressed.unsqueeze(1), cos, sin).squeeze(1)
+ else:
+ compressed = chunk_kv.new_zeros((batch, 0, self.head_dim))
+
+ if cache_layer is not None:
+ compressed = cache_layer.update_compressor_states("compressor", compressed)
+ compressed_kv = compressed.unsqueeze(1)
+
+ compressed_len = compressed_kv.shape[2]
+ seq_len = position_ids.shape[1]
+ if seq_len == 1 or compressed_len == 0:
+ return compressed_kv, None
+
+ # query `t` may only see cache entries at pos `w` t > w * compress_rate (ex: t=7, w=2 t does not attend to it).
+ entry_indices = torch.arange(compressed_len, device=compressed_kv.device)
+ causal_threshold = (position_ids + 1) // self.compress_rate # [B, S]
+ block_bias = compressed_kv.new_zeros((batch, 1, seq_len, compressed_len))
+ block_bias = block_bias.masked_fill(
+ entry_indices.view(1, 1, 1, -1) >= causal_threshold.unsqueeze(1).unsqueeze(-1),
+ float("-inf"),
+ )
+ return compressed_kv, block_bias
+
+
+class DeepseekV4Indexer(nn.Module):
+ r"""Lightning Indexer (paper §2.3.1, eqs. 13–17). Used by Compressed Sparse
+ Attention (CSA) to pick the top-`k` compressed KV blocks per query, with
+ `k = config.index_topk`. Each query then attends only to those `k` of the
+ `seq_len / compress_rate_csa` compressed entries — reduction factor
+ `(seq_len / compress_rate_csa) / index_topk` over full attention against
+ the entire compressed sequence.
+
+ The indexer runs its own scaled-down compressor at `index_head_dim` over
+ the same windows as the outer CSA compressor, then scores queries against
+ the compressed keys with `∑_h w_{t,h} · ReLU(q_{t,h} · K^IComp_s)` and
+ keeps the top `index_topk` indices.
+
+ The indexer has its own rotary because it applies RoPE to two sets of
+ tensors:
+
+ * *compressed keys* at deterministic positions
+ `i * compress_rate + first_window_position`,
+ * *queries* at the model's current `position_ids` (variable per forward).
+
+ Both must use the same theta as the outer compressor
+ (`compress_rope_theta`) so query/key inner products are
+ translation-invariant — if they used different thetas, `q · k` would carry
+ a residual position-dependent skew. We can't precompute cos/sin once at
+ init because the query positions vary per call, so the indexer owns its
+ own rotary and calls it twice per forward (once for compressed keys, once
+ for queries) with `layer_type=self.rope_layer_type` (always `"compress"`).
+ """
+
+ rope_layer_type = "compress"
+
+ def __init__(self, config: DeepseekV4Config):
+ super().__init__()
+ self.compress_rate = config.compress_rates["compressed_sparse_attention"]
+ self.num_heads = config.index_n_heads
+ self.head_dim = config.index_head_dim
+ self.index_topk = config.index_topk
+ self.softmax_scale = self.head_dim**-0.5
+ self.weights_scaling = self.num_heads**-0.5
+ self.kv_proj = nn.Linear(config.hidden_size, 2 * self.head_dim, bias=False)
+ self.gate_proj = nn.Linear(config.hidden_size, 2 * self.head_dim, bias=False)
+ self.position_bias = nn.Parameter(torch.empty(self.compress_rate, 2 * self.head_dim))
+ self.kv_norm = DeepseekV4RMSNorm(self.head_dim, eps=config.rms_norm_eps)
+ self.q_b_proj = nn.Linear(config.q_lora_rank, self.num_heads * self.head_dim, bias=False)
+ self.weights_proj = nn.Linear(config.hidden_size, self.num_heads, bias=False)
+ self.rotary_emb = DeepseekV4RotaryEmbedding(config)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ q_residual: torch.Tensor,
+ position_ids: torch.Tensor,
+ past_key_values: Cache | None,
+ layer_idx: int,
+ ) -> torch.LongTensor:
+ batch, seq_len, _ = hidden_states.shape
+ cache_layer: DeepseekV4CSACache = past_key_values.layers[layer_idx] if past_key_values is not None else None
+ kv = self.kv_proj(hidden_states)
+ gate = self.gate_proj(hidden_states)
+
+ if cache_layer is None:
+ usable = (kv.shape[1] // self.compress_rate) * self.compress_rate
+ chunk_kv, chunk_gate, first_window_position = kv[:, :usable], gate[:, :usable], 0
+ else:
+ chunk_kv, chunk_gate, first_window_position = cache_layer.store_compression_weights("indexer", kv, gate)
+
+ if chunk_kv.shape[1] > 0:
+ n_windows = chunk_kv.shape[1] // self.compress_rate
+ ratio = self.compress_rate
+ chunk_kv = chunk_kv.view(batch, n_windows, ratio, -1)
+ chunk_gate = chunk_gate.view(batch, n_windows, ratio, -1) + self.position_bias.to(chunk_gate.dtype)
+
+ # Same Ca / Cb overlap layout as the outer CSA compressor, at index_head_dim.
+ new_kv = chunk_kv.new_zeros((batch, n_windows, 2 * ratio, self.head_dim))
+ new_gate = chunk_gate.new_full((batch, n_windows, 2 * ratio, self.head_dim), float("-inf"))
+ new_kv[:, :, ratio:] = chunk_kv[..., self.head_dim :]
+ new_gate[:, :, ratio:] = chunk_gate[..., self.head_dim :]
+ if n_windows > 1:
+ new_kv[:, 1:, :ratio] = chunk_kv[:, :-1, :, : self.head_dim]
+ new_gate[:, 1:, :ratio] = chunk_gate[:, :-1, :, : self.head_dim]
+ if cache_layer is not None:
+ prior_kv, prior_gate = cache_layer.update_overlap_state("indexer", chunk_kv, chunk_gate, self.head_dim)
+ if prior_kv is not None:
+ new_kv[:, 0, :ratio] = prior_kv.to(new_kv.dtype)
+ new_gate[:, 0, :ratio] = prior_gate.to(new_gate.dtype)
+
+ compressed = self.kv_norm(
+ (new_kv * new_gate.softmax(dim=2, dtype=torch.float32).to(new_kv.dtype)).sum(dim=2)
+ )
+ positions = torch.arange(n_windows, device=compressed.device)
+ positions = positions * self.compress_rate + first_window_position
+ positions = positions.unsqueeze(0).expand(batch, -1)
+ cos, sin = self.rotary_emb(compressed, position_ids=positions, layer_type=self.rope_layer_type)
+ compressed = apply_rotary_pos_emb(compressed.unsqueeze(1), cos, sin).squeeze(1)
+ else:
+ compressed = chunk_kv.new_zeros((batch, 0, self.head_dim))
+
+ compressed_kv = (
+ compressed if cache_layer is None else cache_layer.update_compressor_states("indexer", compressed)
+ )
+
+ cos_q, sin_q = self.rotary_emb(hidden_states, position_ids=position_ids, layer_type=self.rope_layer_type)
+ q = self.q_b_proj(q_residual).view(batch, seq_len, -1, self.head_dim).transpose(1, 2)
+ q = apply_rotary_pos_emb(q, cos_q, sin_q).transpose(1, 2)
+
+ # ReLU(q·kᵀ) * weights, then top-k
+ scores = torch.matmul(q.float(), compressed_kv.transpose(-1, -2).float().unsqueeze(1)) # [B, S, H, T]
+ scores = F.relu(scores) * self.softmax_scale
+ weights = self.weights_proj(hidden_states).float() * self.weights_scaling # [B, S, H]
+ index_scores = (scores * weights.unsqueeze(-1)).sum(dim=2) # [B, S, T]
+ compressed_len = compressed_kv.shape[1]
+ top_k = min(self.index_topk, compressed_len)
+
+ # not all queries can attend to the compressed entries. If a query's position
+ # is small than the relative position of the key (say m=4, query 2 cannot attend
+ # to compressed key at position 4, because it compressed info for states at position
+ # 12 to 16. Thus we need to make sure that top_k does not land in that range.
+ # Picks that still point past `causal_threshold` (early queries with too few ready
+ # blocks) are replaced with a `-1` sentinel that the compresser treats as invalid.
+ if compressed_len > 0:
+ causal_threshold = (position_ids + 1) // self.compress_rate # [B, S]
+ entry_indices = torch.arange(compressed_len, device=index_scores.device)
+ future_mask = entry_indices.view(1, 1, -1) >= causal_threshold.unsqueeze(-1) # [B, S, T]
+ index_scores = index_scores.masked_fill(future_mask, float("-inf"))
+ top_k_indices = index_scores.topk(top_k, dim=-1).indices # [B, S, k]
+ invalid = top_k_indices >= causal_threshold.unsqueeze(-1)
+ return torch.where(invalid, torch.full_like(top_k_indices, -1), top_k_indices)
+
+ return index_scores.topk(top_k, dim=-1).indices
+
+
+class DeepseekV4CSACompressor(nn.Module):
+ """Compressed Sparse Attention compressor (paper §2.3.1, eqs. 9–17). Compresses
+ every `compress_rate_csa` (m=4) source tokens and runs a Lightning Indexer on
+ top of the compressed KV that scores queries with
+ `∑_h w_{t,h} · ReLU(q_{t,h} · K^{IComp}_s)` to gather the top `index_topk`
+ entries per query before they reach core attention.
+
+ `kv_proj` / `gate_proj` / `position_bias` project to `2 * head_dim`: each
+ token contributes two independent compressed series Ca and Cb stored in
+ one tensor. Ca = `[..., :head_dim]` (its contribution to the *next*
+ window's compressed entry), Cb = `[..., head_dim:]` (its contribution to
+ the *current* window's compressed entry). Compressed entry `w` is the
+ softmax-gated convex combination of window `w-1`'s Ca slice with window
+ `w`'s Cb slice over `2 * compress_rate_csa` slots — width
+ `2 * compress_rate_csa`, stride `compress_rate_csa`. For `w = 0` we need
+ the previous window's Ca slice from the *previous forward call*; the
+ cache holds it in `overlap_kv` and hands it back here. On the very first
+ call (or when there is no cache) that slot stays zero-kv / `-inf`-gate,
+ which gives it softmax weight 0.
+ """
+
+ rope_layer_type = "compress"
+
+ def __init__(self, config: DeepseekV4Config):
+ super().__init__()
+ self.compress_rate = config.compress_rates["compressed_sparse_attention"]
+ self.head_dim = config.head_dim
+ self.kv_proj = nn.Linear(config.hidden_size, 2 * self.head_dim, bias=False)
+ self.gate_proj = nn.Linear(config.hidden_size, 2 * self.head_dim, bias=False)
+ self.position_bias = nn.Parameter(torch.empty(self.compress_rate, 2 * self.head_dim))
+ self.kv_norm = DeepseekV4RMSNorm(self.head_dim, eps=config.rms_norm_eps)
+ self.rotary_emb = DeepseekV4RotaryEmbedding(config)
+ self.indexer = DeepseekV4Indexer(config)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ q_residual: torch.Tensor,
+ position_ids: torch.Tensor,
+ past_key_values: Cache | None,
+ layer_idx: int,
+ ) -> torch.Tensor:
+ batch, seq_len, _ = hidden_states.shape
+ cache_layer: DeepseekV4CSACache = past_key_values.layers[layer_idx] if past_key_values is not None else None
+ kv = self.kv_proj(hidden_states)
+ gate = self.gate_proj(hidden_states)
+
+ if cache_layer is None:
+ usable = (kv.shape[1] // self.compress_rate) * self.compress_rate
+ chunk_kv, chunk_gate, first_window_position = kv[:, :usable], gate[:, :usable], 0
+ else:
+ chunk_kv, chunk_gate, first_window_position = cache_layer.store_compression_weights("compressor", kv, gate)
+
+ if chunk_kv.shape[1] > 0:
+ n_windows = chunk_kv.shape[1] // self.compress_rate
+ ratio = self.compress_rate
+ chunk_kv = chunk_kv.view(batch, n_windows, ratio, -1)
+ chunk_gate = chunk_gate.view(batch, n_windows, ratio, -1) + self.position_bias.to(chunk_gate.dtype)
+
+ # Lay out the two series in [B, n_win, 2*ratio, head_dim]: Cb
+ # (`[..., head_dim:]`) goes in the second half (current window),
+ # Ca of the previous window (`[..., :head_dim]`) goes in the
+ # first half. Window 0's first half stays zero-kv / -inf-gate
+ # (softmax weight 0) on the very first forward call; on later
+ # calls the cache fills it with the saved Ca slice.
+ new_kv = chunk_kv.new_zeros((batch, n_windows, 2 * ratio, self.head_dim))
+ new_gate = chunk_gate.new_full((batch, n_windows, 2 * ratio, self.head_dim), float("-inf"))
+ new_kv[:, :, ratio:] = chunk_kv[..., self.head_dim :]
+ new_gate[:, :, ratio:] = chunk_gate[..., self.head_dim :]
+ if n_windows > 1:
+ new_kv[:, 1:, :ratio] = chunk_kv[:, :-1, :, : self.head_dim]
+ new_gate[:, 1:, :ratio] = chunk_gate[:, :-1, :, : self.head_dim]
+ if cache_layer is not None:
+ prior_kv, prior_gate = cache_layer.update_overlap_state(
+ "compressor", chunk_kv, chunk_gate, self.head_dim
+ )
+ if prior_kv is not None:
+ new_kv[:, 0, :ratio] = prior_kv.to(new_kv.dtype)
+ new_gate[:, 0, :ratio] = prior_gate.to(new_gate.dtype)
+
+ # Softmax in fp32 for stability (logits in bf16/fp16 can collapse pairs that
+ # only differ by a small amount, especially with large window widths).
+ compressed = self.kv_norm(
+ (new_kv * new_gate.softmax(dim=2, dtype=torch.float32).to(new_kv.dtype)).sum(dim=2)
+ )
+ positions = torch.arange(n_windows, device=compressed.device)
+ positions = positions * self.compress_rate + first_window_position
+ positions = positions.unsqueeze(0).expand(batch, -1)
+ cos, sin = self.rotary_emb(compressed, position_ids=positions, layer_type=self.rope_layer_type)
+ compressed = apply_rotary_pos_emb(compressed.unsqueeze(1), cos, sin).squeeze(1)
+ else:
+ compressed = chunk_kv.new_zeros((batch, 0, self.head_dim))
+
+ if cache_layer is not None:
+ compressed = cache_layer.update_compressor_states("compressor", compressed)
+ compressed_kv = compressed.unsqueeze(1)
+
+ # Lightning Indexer: gather top-`index_topk` compressed entries per query.
+ # in some cases, the output index can return top-k positions that should not be attended to.
+ # Ex: for query at index 5, m=4, and `index_topk=1024`, 1024 index are return but only 2 should be
+ # attended to. The indexer marks the rest with `-1`; we clamp before the gather and keep the `valid`
+ # to drop them from the per-query block mask afterwards.
+ top_k_indices = self.indexer(hidden_states, q_residual, position_ids, past_key_values, layer_idx) # [B, S, k]
+ compressed_len = compressed_kv.shape[2]
+ valid = top_k_indices >= 0 # [B, S, k]
+ # Per-query block bias: query `t` may only see the cache entries that are <= `seq_len // m`
+ # and in these, only the ones marked valid by the indexer. Everything else is `-inf`.
+ # While the above negated the indexer, here we apply the "causal" masking.
+ safe_indices = torch.where(valid, top_k_indices, torch.full_like(top_k_indices, compressed_len))
+ block_bias = compressed_kv.new_full((batch, 1, seq_len, compressed_len + 1), float("-inf"))
+ block_bias.scatter_(-1, safe_indices.unsqueeze(1), 0.0)
+ return compressed_kv, block_bias[..., :compressed_len]
+
+
+COMPRESSOR_CLASSES = {
+ "sliding_attention": None,
+ "compressed_sparse_attention": DeepseekV4CSACompressor,
+ "heavily_compressed_attention": DeepseekV4HCACompressor,
+}
+
+
+class DeepseekV4Attention(nn.Module):
+ r"""
+ Diff with classic attentions:
+ * Shared-KV Multi-Query Attention: `num_key_value_heads = 1`; `kv_proj` projects
+ directly to that single KV head and the same tensor is read as both key and
+ value.
+ * Partial RoPE on the first `rope_head_dim` of each head ("Partial Rotary
+ Positional Embedding"). RoPE is also applied with position `-i` to the
+ attention output's rope slice, so the contribution of each KV entry stays a
+ function of the *relative* distance to the query.
+ * Per-head learnable attention sink like gpt OSS.
+ * Grouped low-rank output projection for perfs.
+ * 3 different cache mechanisms, sliding, sliding+CSA, sliding+HCA.
+ """
+
+ def __init__(self, config: DeepseekV4Config, layer_idx: int):
+ super().__init__()
+ self.config = config
+ self.layer_idx = layer_idx
+ self.layer_type = config.layer_types[layer_idx]
+ # Sliding-only layers use the "main" (plain θ=10000) rope; CSA/HCA layers
+ # share the same yarn-scaled "compress" rope as their compressor.
+ self.rope_layer_type = "main" if self.layer_type == "sliding_attention" else "compress"
+ self.num_heads = config.num_attention_heads
+ self.num_key_value_groups = config.num_attention_heads # single KV head, broadcast to all
+ self.head_dim = config.head_dim
+ self.sliding_window = config.sliding_window
+ self.attention_dropout = config.attention_dropout
+ self.is_causal = True
+ self.scaling = self.head_dim**-0.5
+
+ self.q_a_proj = nn.Linear(config.hidden_size, config.q_lora_rank, bias=False)
+ self.q_a_norm = DeepseekV4RMSNorm(config.q_lora_rank, eps=config.rms_norm_eps)
+ self.q_b_proj = nn.Linear(config.q_lora_rank, self.num_heads * self.head_dim, bias=False)
+ self.q_b_norm = DeepseekV4UnweightedRMSNorm(eps=config.rms_norm_eps)
+ self.kv_proj = nn.Linear(config.hidden_size, self.head_dim, bias=False)
+ self.kv_norm = DeepseekV4RMSNorm(self.head_dim, eps=config.rms_norm_eps)
+ self.o_a_proj = DeepseekV4GroupedLinear(
+ self.num_heads * self.head_dim // config.o_groups, config.o_groups * config.o_lora_rank, config.o_groups
+ )
+ self.o_b_proj = nn.Linear(config.o_groups * config.o_lora_rank, config.hidden_size, bias=False)
+ self.sinks = nn.Parameter(torch.empty(self.num_heads))
+ self.compressor = (
+ COMPRESSOR_CLASSES[self.layer_type](config) if self.layer_type != "sliding_attention" else None
+ )
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ position_embeddings: dict[str, tuple[torch.Tensor, torch.Tensor]] | tuple[torch.Tensor, torch.Tensor],
+ position_ids: torch.Tensor,
+ attention_mask: torch.Tensor | None,
+ past_key_values: Cache | None = None,
+ **kwargs: Unpack[FlashAttentionKwargs],
+ ) -> tuple[torch.Tensor, torch.Tensor | None]:
+ input_shape = hidden_states.shape[:-1]
+ hidden_shape = (*input_shape, -1, self.head_dim)
+ # position_embeddings is a {"main", "compress"} dict from the model; pick the
+ # one that matches this layer's rope type (sliding → main, CSA/HCA → compress).
+ cos, sin = position_embeddings[self.rope_layer_type]
+
+ q_residual = self.q_a_norm(self.q_a_proj(hidden_states))
+ q = self.q_b_proj(q_residual).view(*hidden_shape).transpose(1, 2)
+ q = self.q_b_norm(q)
+ q = apply_rotary_pos_emb(q, cos, sin)
+
+ kv = self.kv_norm(self.kv_proj(hidden_states)).view(*hidden_shape).transpose(1, 2)
+ kv = apply_rotary_pos_emb(kv, cos, sin)
+
+ if past_key_values is not None: # sliding where K==V
+ kv = past_key_values.update(kv, kv, self.layer_idx)[0]
+
+ block_bias = None
+ if self.compressor is not None: # Compressed KV (CSA or HCA)
+ compressed_kv, block_bias = self.compressor(
+ hidden_states, q_residual, position_ids, past_key_values, self.layer_idx
+ )
+ kv = torch.cat([kv, compressed_kv], dim=2)
+
+ # The compressor path concatenates extra entries onto the KV axis after the
+ # standard sliding-window cache update, so a tensor `attention_mask` (built
+ # for the pre-concat KV length) needs to be extended to cover them. The
+ # compressor returns a `block_bias` carrying per-query causality + indexer
+ # validity over those new slots — cat it in instead of zero-padding (which
+ # would let every query see every compressed slot).
+ if isinstance(attention_mask, torch.Tensor) and kv.shape[2] > attention_mask.shape[-1]:
+ if block_bias is not None:
+ attention_mask = torch.cat([attention_mask, block_bias.to(attention_mask.dtype)], dim=-1)
+ else:
+ attention_mask = F.pad(attention_mask, (0, kv.shape[2] - attention_mask.shape[-1]), value=0.0)
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+ attn_output, attn_weights = attention_interface(
+ self,
+ q,
+ kv,
+ kv,
+ attention_mask,
+ dropout=0.0 if not self.training else self.attention_dropout,
+ scaling=self.scaling,
+ sliding_window=self.sliding_window,
+ s_aux=self.sinks,
+ **kwargs,
+ )
+
+ # K=V in V4, so V picked up rope on its trailing rope slice. Apply the conjugate
+ # rotation (`-sin`) at the query position to undo it on the rope slice of the
+ # output before the grouped output projection mixes heads. The transpose pair is
+ # just a layout fix-up: apply_rotary_pos_emb expects `[B, S, H, D]` (its
+ # `unsqueeze_dim=1` adds a head-broadcast dim to cos/sin); attention gave us
+ # `[B, H, S, D]`.
+ attn_output = apply_rotary_pos_emb(attn_output.transpose(1, 2), cos, -sin).transpose(1, 2)
+
+ grouped = attn_output.reshape(*input_shape, self.config.o_groups, -1)
+ grouped = self.o_a_proj(grouped).flatten(2)
+ output = self.o_b_proj(grouped)
+ return output, attn_weights
+
+
+class DeepseekV4HyperConnection(nn.Module):
+ r"""
+ Manifold-Constrained Hyper-Connections
+ (mHC) (Xie et al., 2026) to strengthen the conventional residual connections between adjacent
+ Transformer blocks
+
+ Owns the learned (`fn`, `base`, `scale`)
+ parameters that turn the incoming `hc_mult` residual streams into collapse / expand
+ weights. The decoder layer instantiates two of these (one for the attention site,
+ one for the mlp site).
+
+ ASCII shape guide — `B` = batch, `S` = seq, `H` = hc_mult, `D` = hidden_size::
+
+ hidden_streams flatten(2) RMSNorm-rescale + F.linear(fn)
+ [B, S, H, D] ──────────► [B, S, H*D] ─────────────────────────────────►
+ mix-logits
+ [B, S, (2+H)*H]
+ │
+ ┌───────────────────────────────────────┴──────────────────────────────┐
+ ▼ ▼ ▼
+ pre logits post logits comb logits
+ [B, S, H] [B, S, H] [B, S, H, H]
+ × scale[0] × scale[1] × scale[2]
+ + base[:H] + base[H:2H] + base[2H:]
+ σ() + eps σ() + eps σ() + eps
+ │ │ │
+ pre post Sinkhorn(iters)
+ (stream collapse weights) (block-output placement) row/col normalise
+ │
+ comb
+ (stream mixer)
+ """
+
+ def __init__(self, config: DeepseekV4Config):
+ super().__init__()
+ self.hc_mult = config.hc_mult
+ self.hc_sinkhorn_iters = config.hc_sinkhorn_iters
+ self.hc_eps = config.hc_eps
+ self.input_norm = DeepseekV4UnweightedRMSNorm(eps=config.rms_norm_eps)
+ mix = (2 + self.hc_mult) * self.hc_mult
+ self.fn = nn.Parameter(torch.empty(mix, self.hc_mult * config.hidden_size))
+ self.base = nn.Parameter(torch.empty(mix))
+ # 3 = number of outputs from the mHC mapping: `pre` (input projection
+ # weights), `post` (sublayer output projection weights), `comb` (the
+ # H×H residual combine matrix that gets Sinkhorn-projected onto the
+ # doubly-stochastic manifold). Each output gets its own learned scale.
+ self.scale = nn.Parameter(torch.empty(3))
+
+ def forward(self, hidden_streams: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ r"""
+ Compute `pre`, `post`, `comb` from the mHC mapping (paper §2.2 eq. 8).
+ `comb` is projected onto the doubly-stochastic manifold via Sinkhorn-
+ Knopp: starting from the sigmoid-positive matrix, alternate row and
+ column normalisation for `hc_sinkhorn_iters` steps. `pre` then collapses
+ the `hc_mult` parallel streams into a single sequence (input projection
+ into the sublayer); `post` and `comb` are returned for the caller to
+ apply on the sublayer output.
+ """
+ hc = self.hc_mult
+ flat = self.input_norm(hidden_streams.flatten(start_dim=2).float())
+ pre_w, post_w, comb_w = F.linear(flat, self.fn.float()).split([hc, hc, hc * hc], dim=-1)
+ pre_b, post_b, comb_b = self.base.split([hc, hc, hc * hc])
+ pre_scale, post_scale, comb_scale = self.scale.unbind(0)
+
+ pre = torch.sigmoid(pre_w * pre_scale + pre_b) + self.hc_eps
+ post = 2 * torch.sigmoid(post_w * post_scale + post_b)
+ comb_logits = comb_w.view(*comb_w.shape[:-1], hc, hc) * comb_scale + comb_b.view(hc, hc)
+ comb = torch.softmax(comb_logits, dim=-1) + self.hc_eps
+ comb = comb / (comb.sum(dim=-2, keepdim=True) + self.hc_eps)
+ for _ in range(self.hc_sinkhorn_iters - 1):
+ comb = comb / (comb.sum(dim=-1, keepdim=True) + self.hc_eps)
+ comb = comb / (comb.sum(dim=-2, keepdim=True) + self.hc_eps)
+ # Collapse the `hc_mult` parallel streams down to a single sequence using
+ # the `pre` weights: one weighted sum across the stream axis, ready for
+ # the sublayer (attn / MLP).
+ collapsed = (pre.unsqueeze(-1) * hidden_streams).sum(dim=2).to(hidden_streams.dtype)
+ return post, comb, collapsed
+
+
+class DeepseekV4HyperHead(nn.Module):
+ """Final HC-stream collapse; used by `DeepseekV4Model` before the shared RMSNorm."""
+
+ def __init__(self, config: DeepseekV4Config):
+ super().__init__()
+ self.hc_mult = config.hc_mult
+ self.input_norm = DeepseekV4UnweightedRMSNorm(eps=config.rms_norm_eps)
+ self.eps = config.hc_eps
+ self.hc_fn = nn.Parameter(torch.empty(self.hc_mult, self.hc_mult * config.hidden_size))
+ self.hc_base = nn.Parameter(torch.empty(self.hc_mult))
+ self.hc_scale = nn.Parameter(torch.empty(1))
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ flat = self.input_norm(x.flatten(2).float())
+ mixes = F.linear(flat, self.hc_fn.float())
+ pre = torch.sigmoid(mixes * self.hc_scale.float() + self.hc_base.float()) + self.eps
+ return (pre.unsqueeze(-1) * x).sum(dim=2).to(x.dtype)
+
+
+class DeepseekV4MLP(LlamaMLP):
+ pass
+
+
+@use_experts_implementation
+class DeepseekV4Experts(MixtralExperts):
+ # GPT OSS style, no bias
+
+ def __init__(self, config: DeepseekV4Config):
+ super().__init__(config)
+ self.limit = config.swiglu_limit
+
+ def _apply_gate(self, gate_up: torch.Tensor) -> torch.Tensor:
+ # Lives on the class (like gpt-oss's _apply_gate) so the grouped_mm / batched_mm
+ # backends swapped in by `@use_experts_implementation` apply the same clamp +
+ # SiLU on top of their packed gate_up output instead of bypassing it.
+ gate, up = gate_up.chunk(2, dim=-1)
+ gate = gate.clamp(max=self.limit)
+ up = up.clamp(min=-self.limit, max=self.limit)
+ return self.act_fn(gate) * up
+
+ def forward(
+ self, hidden_states: torch.Tensor, top_k_index: torch.Tensor, top_k_weights: torch.Tensor
+ ) -> torch.Tensor:
+ final = torch.zeros_like(hidden_states)
+ with torch.no_grad():
+ mask = F.one_hot(top_k_index, num_classes=self.num_experts).permute(2, 1, 0)
+ hit = torch.greater(mask.sum(dim=(-1, -2)), 0).nonzero()
+ for expert_idx in hit:
+ expert_idx = expert_idx[0]
+ if expert_idx == self.num_experts:
+ continue
+ top_k_pos, token_idx = torch.where(mask[expert_idx])
+ current = self._apply_gate(F.linear(hidden_states[token_idx], self.gate_up_proj[expert_idx]))
+ current = F.linear(current, self.down_proj[expert_idx]) * top_k_weights[token_idx, top_k_pos, None]
+ final.index_add_(0, token_idx, current.to(final.dtype))
+ return final
+
+
+class DeepseekV4TopKRouter(MixtralTopKRouter):
+ def __init__(self, config: DeepseekV4Config):
+ super().__init__(config)
+ self.score_fn = ACT2FN[config.scoring_func]
+ self.routed_scaling_factor = config.routed_scaling_factor
+ self.register_buffer("e_score_correction_bias", torch.zeros(self.num_experts), persistent=True)
+
+ def forward(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ flat = hidden_states.reshape(-1, self.hidden_dim)
+ logits = F.linear(flat, self.weight)
+ scores = self.score_fn(logits)
+ indices = torch.topk(scores + self.e_score_correction_bias, self.top_k, dim=-1, sorted=False).indices
+ weights = scores.gather(1, indices)
+ weights = weights / (weights.sum(dim=-1, keepdim=True) + 1e-20)
+ return logits, weights * self.routed_scaling_factor, indices
+
+
+class DeepseekV4HashRouter(MixtralTopKRouter):
+ r"""
+ Hash routing for the first `mlp_layer_types == "hash_moe"` MoE layers (paper
+ §2.1). Expert selection is determined by a fixed `tid2eid[input_ids]` lookup —
+ a frozen token-id → expert-id table — instead of a learned argmax. The learned
+ gate `weight` still produces the per-expert scores that weight the selected
+ experts' activations; only the *which-experts* selection is static.
+ """
+
+ def __init__(self, config: DeepseekV4Config):
+ super().__init__(config)
+ self.score_fn = ACT2FN[config.scoring_func]
+ self.routed_scaling_factor = config.routed_scaling_factor
+ self.register_buffer("tid2eid", torch.zeros(config.vocab_size, self.top_k, dtype=torch.long), persistent=True)
+
+ def forward(
+ self, hidden_states: torch.Tensor, input_ids: torch.Tensor
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ flat = hidden_states.reshape(-1, self.hidden_dim)
+ logits = F.linear(flat, self.weight)
+ scores = self.score_fn(logits)
+ indices = self.tid2eid[input_ids.reshape(-1)].long()
+ weights = scores.gather(1, indices)
+ weights = weights / (weights.sum(dim=-1, keepdim=True) + 1e-20)
+ return logits, weights * self.routed_scaling_factor, indices
+
+
+class DeepseekV4SparseMoeBlock(nn.Module):
+ def __init__(self, config: DeepseekV4Config, layer_idx: int):
+ super().__init__()
+ self.is_hash = config.mlp_layer_types[layer_idx] == "hash_moe"
+ self.gate = DeepseekV4HashRouter(config) if self.is_hash else DeepseekV4TopKRouter(config)
+ self.experts = DeepseekV4Experts(config)
+ self.shared_experts = DeepseekV4MLP(config)
+
+ def forward(self, hidden_states: torch.Tensor, input_ids: torch.Tensor | None = None) -> torch.Tensor:
+ batch, seq_len, hidden_dim = hidden_states.shape
+ residual = hidden_states
+ flat = hidden_states.view(-1, hidden_dim)
+ if self.is_hash:
+ _, weights, indices = self.gate(hidden_states, input_ids)
+ else:
+ _, weights, indices = self.gate(hidden_states)
+ routed = self.experts(flat, indices, weights).view(batch, seq_len, hidden_dim)
+ return routed + self.shared_experts(residual)
+
+
+class DeepseekV4DecoderLayer(GradientCheckpointingLayer):
+ r"""DeepSeek-V4 decoder block (paper §2). Differs from a classic residual block in
+ two places:
+
+ The residual is a stack of `hc_mult` parallel streams kept in shape
+ `[B, S, hc_mult, D]` throughout the block, mixed in and out via two
+ :class:`DeepseekV4HyperConnection` modules (Manifold-Constrained Hyper-
+ Connections / mHC, paper §2.2; Xie et al., 2026). The mHC mappings constrain
+ the residual transform to the manifold of doubly-stochastic matrices via the
+ Sinkhorn-Knopp projection — making signal propagation non-expansive across
+ deep stacks.
+
+ """
+
+ def __init__(self, config: DeepseekV4Config, layer_idx: int):
+ super().__init__()
+ self.layer_idx = layer_idx
+ self.self_attn = DeepseekV4Attention(config, layer_idx)
+ self.mlp = DeepseekV4SparseMoeBlock(config, layer_idx)
+ self.input_layernorm = DeepseekV4RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.post_attention_layernorm = DeepseekV4RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.attn_hc = DeepseekV4HyperConnection(config)
+ self.ffn_hc = DeepseekV4HyperConnection(config)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ input_ids: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.Tensor:
+ # hidden_states throughout: [B, S, hc_mult, hidden].
+ # `post` / `comb` come out of the HC modules in fp32 (Sinkhorn projection runs
+ # in float); the .to(dtype) puts everything back to the input dtype before mixing
+ # so both sites stay consistent with `hidden_states`'s entry dtype.
+ # comb is consumed transposed: indexed as sum_j comb[j, k] * residual[j, d]
+ # (sum over the FIRST hc axis), equivalent to comb.T @ residual. Sinkhorn
+ # produces a doubly-stochastic but non-symmetric matrix, so the direction matters.
+ dtype = hidden_states.dtype
+ post, comb, collapsed = self.attn_hc(hidden_states)
+ attn_output, _ = self.self_attn(self.input_layernorm(collapsed), **kwargs)
+ hidden_states = post.to(dtype).unsqueeze(-1) * attn_output.unsqueeze(-2) + torch.matmul(
+ comb.to(dtype).transpose(-1, -2), hidden_states
+ )
+
+ post, comb, collapsed = self.ffn_hc(hidden_states)
+ mlp_output = self.mlp(self.post_attention_layernorm(collapsed), input_ids=input_ids)
+ return post.to(dtype).unsqueeze(-1) * mlp_output.unsqueeze(-2) + torch.matmul(
+ comb.to(dtype).transpose(-1, -2), hidden_states
+ )
+
+
+class DeepseekV4PreTrainedModel(MixtralPreTrainedModel):
+ config_class = DeepseekV4Config
+ base_model_prefix = "model"
+ _no_split_modules = ["DeepseekV4DecoderLayer"]
+ # V4 ships eager-only. The non-eager backends are off for the following reasons:
+ #
+ # * FlashAttention 2 / 3 cap the head dim at 256; V4's `head_dim=512`
+ # (V4-Flash and V4-Pro both) is structurally incompatible — `flash_attention_2`
+ # and the `kernels-community/vllm-flash-attn3` kernel both fail with
+ # `RuntimeError: FlashAttention forward only supports head dimension at most
+ # 256`. FA4 has the same 256 cap, so it's off too.
+ # * SDPA: torch's SDPA kernel doesn't carry the per-head learnable sink term V4
+ # inherits from gpt-oss-style attention.
+ # * FlexAttention: V4 attention concatenates compressor entries onto the KV
+ # axis *inside* the attention block, after the model-level mask was built,
+ # so the resulting KV length doesn't match the BlockMask's `kv_len`.
+ # BlockMask has no runtime resize, and rebuilding it per-block would require
+ # teaching the compressor's variable output count to a `mask_mod` — not
+ # worth it for a path the compressor already owns its own causality
+ # bookkeeping for.
+ _supports_flash_attn = False
+ _supports_sdpa = False
+ _supports_flex_attn = False
+ # The compressor's rolling-window buffer / compressed-entries / overlap state
+ # lives on the per-layer cache (:class:`DeepseekV4HCACache` /
+ # :class:`DeepseekV4CSACache`) and isn't compatible with :class:`StaticCache`
+ # — that path would hand the compressor a :class:`StaticSlidingWindowLayer`
+ # with no `store_compression_weights` method. Disabling fullgraph compile
+ # keeps generation tests on the dynamic cache build that does dispatch to
+ # V4's own cache layers.
+ _can_compile_fullgraph = False
+ _keep_in_fp32_modules_strict = [
+ "attn_hc",
+ "ffn_hc",
+ "e_score_correction_bias",
+ "q_a_norm",
+ "kv_norm",
+ "input_layernorm",
+ "post_attention_layernorm",
+ "norm",
+ ]
+ _keys_to_ignore_on_load_unexpected = [r"(^|\.)mtp\..*"]
+ # ``_is_stateful`` opts out of generation modes that need to roll the cache
+ # back across drafts (assisted generation, prompt lookup, contrastive search).
+ # The compressor's running-window state isn't rewindable, so `generate`
+ # raises a clear error early instead of failing deep in the compressor with
+ # a missing-method `AttributeError`.
+ _is_stateful = True
+ _can_record_outputs = {
+ "router_logits": OutputRecorder(DeepseekV4TopKRouter, index=0),
+ "hidden_states": DeepseekV4DecoderLayer,
+ "attentions": DeepseekV4Attention,
+ }
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ PreTrainedModel._init_weights(self, module)
+ std = self.config.initializer_range
+ if isinstance(module, (DeepseekV4TopKRouter, DeepseekV4HashRouter)):
+ init.normal_(module.weight, mean=0.0, std=std)
+ if isinstance(module, DeepseekV4TopKRouter):
+ init.zeros_(module.e_score_correction_bias) # buffer
+ if isinstance(module, DeepseekV4HashRouter):
+ init.zeros_(module.tid2eid) # buffer; real values come from the checkpoint
+ elif isinstance(module, DeepseekV4Experts):
+ init.normal_(module.gate_up_proj, mean=0.0, std=std)
+ init.normal_(module.down_proj, mean=0.0, std=std)
+ elif isinstance(module, DeepseekV4Attention):
+ init.zeros_(module.sinks)
+ elif isinstance(module, DeepseekV4HyperConnection):
+ init.normal_(module.fn, mean=0.0, std=std)
+ init.zeros_(module.base)
+ init.ones_(module.scale)
+ elif isinstance(module, DeepseekV4HyperHead):
+ init.normal_(module.hc_fn, mean=0.0, std=std)
+ init.zeros_(module.hc_base)
+ init.ones_(module.hc_scale)
+ elif isinstance(module, (DeepseekV4HCACompressor, DeepseekV4CSACompressor, DeepseekV4Indexer)):
+ init.zeros_(module.position_bias)
+ elif isinstance(module, DeepseekV4RotaryEmbedding):
+ for layer_type in module.layer_types:
+ rope_init_fn = module.compute_default_rope_parameters
+ if module.rope_type[layer_type] != "default":
+ rope_init_fn = ROPE_INIT_FUNCTIONS[module.rope_type[layer_type]]
+ curr_inv_freq, _ = rope_init_fn(module.config, layer_type=layer_type)
+ init.copy_(getattr(module, f"{layer_type}_inv_freq"), curr_inv_freq)
+ init.copy_(getattr(module, f"{layer_type}_original_inv_freq"), curr_inv_freq)
+
+
+@auto_docstring
+class DeepseekV4Model(LlamaModel):
+ def __init__(self, config: DeepseekV4Config):
+ super().__init__(config)
+ self.layers = nn.ModuleList(
+ [DeepseekV4DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
+ )
+ self.rotary_emb = DeepseekV4RotaryEmbedding(config)
+ self.hc_head = DeepseekV4HyperHead(config)
+ self.post_init()
+
+ @merge_with_config_defaults
+ @capture_outputs
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ use_cache: bool | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> MoeModelOutputWithPast:
+ if (input_ids is None) ^ (inputs_embeds is not None):
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
+ return_cache = past_key_values if use_cache else None
+ if past_key_values is None:
+ past_key_values = DynamicCache(config=self.config)
+ if inputs_embeds is None:
+ inputs_embeds = self.embed_tokens(input_ids)
+ if position_ids is None:
+ past_seen = past_key_values.get_seq_length()
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen
+ position_ids = position_ids.unsqueeze(0)
+ # `generate()` may pass a per-layer-type mask dict already built by
+ # `create_masks_for_generate`; all V4 layer types use the same sliding-window
+ # mask, so use the prebuilt one directly. Otherwise build it here.
+ if isinstance(attention_mask, dict):
+ causal_mask = next(iter(attention_mask.values()))
+ else:
+ causal_mask = create_sliding_window_causal_mask(
+ config=self.config,
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ position_ids=position_ids,
+ )
+ hidden_states = inputs_embeds.unsqueeze(2).expand(-1, -1, self.config.hc_mult, -1).contiguous()
+ position_embeddings = {
+ "main": self.rotary_emb(inputs_embeds, position_ids=position_ids, layer_type="main"),
+ "compress": self.rotary_emb(inputs_embeds, position_ids=position_ids, layer_type="compress"),
+ }
+
+ for layer in self.layers:
+ hidden_states = layer(
+ hidden_states,
+ position_embeddings=position_embeddings,
+ position_ids=position_ids,
+ attention_mask=causal_mask,
+ input_ids=input_ids,
+ past_key_values=past_key_values,
+ **kwargs,
+ )
+
+ hidden_states = self.norm(self.hc_head(hidden_states))
+ return MoeModelOutputWithPast(last_hidden_state=hidden_states, past_key_values=return_cache)
+
+
+class DeepseekV4ForCausalLM(MixtralForCausalLM):
+ pass
+
+
+__all__ = [
+ "DeepseekV4PreTrainedModel",
+ "DeepseekV4Model",
+ "DeepseekV4ForCausalLM",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/deprecated/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/deprecated/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..46f500fa0d12a8773d51b86111e839c58f825015
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/deprecated/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/depth_anything/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/depth_anything/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..7425e37e0399c792155a88488045176fb3b5e7a5
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/depth_anything/__init__.py
@@ -0,0 +1,27 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_depth_anything import *
+ from .modeling_depth_anything import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/depth_anything/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/depth_anything/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a4889419de054bb1e914b2cd351e33c72aebb173
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/depth_anything/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/depth_anything/__pycache__/configuration_depth_anything.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/depth_anything/__pycache__/configuration_depth_anything.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1608a7c811f25016236cf9e567039513e2658b93
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/depth_anything/__pycache__/configuration_depth_anything.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/depth_anything/__pycache__/modeling_depth_anything.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/depth_anything/__pycache__/modeling_depth_anything.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..319e2e7f4bb7834f2ccb8ac01cc8539ea648173a
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/depth_anything/__pycache__/modeling_depth_anything.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/depth_anything/configuration_depth_anything.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/depth_anything/configuration_depth_anything.py
new file mode 100644
index 0000000000000000000000000000000000000000..bdc68ec4fe02ea3d7b8ab68f7cdac9e6dab4d0a8
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/depth_anything/configuration_depth_anything.py
@@ -0,0 +1,99 @@
+# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""DepthAnything model configuration"""
+
+from huggingface_hub.dataclasses import strict
+
+from ...backbone_utils import consolidate_backbone_kwargs_to_config
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring
+from ..auto.configuration_auto import AutoConfig
+
+
+@auto_docstring(checkpoint="LiheYoung/depth-anything-small-hf")
+@strict
+class DepthAnythingConfig(PreTrainedConfig):
+ r"""
+ reassemble_hidden_size (`int`, *optional*, defaults to 384):
+ The number of input channels of the reassemble layers.
+ reassemble_factors (`list[int]`, *optional*, defaults to `[4, 2, 1, 0.5]`):
+ The up/downsampling factors of the reassemble layers.
+ neck_hidden_sizes (`list[str]`, *optional*, defaults to `[48, 96, 192, 384]`):
+ The hidden sizes to project to for the feature maps of the backbone.
+ fusion_hidden_size (`int`, *optional*, defaults to 64):
+ The number of channels before fusion.
+ head_in_index (`int`, *optional*, defaults to -1):
+ The index of the features to use in the depth estimation head.
+ head_hidden_size (`int`, *optional*, defaults to 32):
+ The number of output channels in the second convolution of the depth estimation head.
+ depth_estimation_type (`str`, *optional*, defaults to `"relative"`):
+ The type of depth estimation to use. Can be one of `["relative", "metric"]`.
+ max_depth (`float`, *optional*):
+ The maximum depth to use for the "metric" depth estimation head. 20 should be used for indoor models
+ and 80 for outdoor models. For "relative" depth estimation, this value is ignored.
+
+ Example:
+
+ ```python
+ >>> from transformers import DepthAnythingConfig, DepthAnythingForDepthEstimation
+
+ >>> # Initializing a DepthAnything small style configuration
+ >>> configuration = DepthAnythingConfig()
+
+ >>> # Initializing a model from the DepthAnything small style configuration
+ >>> model = DepthAnythingForDepthEstimation(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "depth_anything"
+ sub_configs = {"backbone_config": AutoConfig}
+
+ backbone_config: dict | PreTrainedConfig | None = None
+ patch_size: int | list[int] | tuple[int, int] = 14
+ initializer_range: float = 0.02
+ reassemble_hidden_size: int = 384
+ reassemble_factors: list[int | float] | tuple[int | float, ...] = (4, 2, 1, 0.5)
+ neck_hidden_sizes: list[int] | tuple[int, ...] = (48, 96, 192, 384)
+ fusion_hidden_size: int = 64
+ head_in_index: int = -1
+ head_hidden_size: int = 32
+ depth_estimation_type: str = "relative"
+ max_depth: int | None = None
+
+ def __post_init__(self, **kwargs):
+ self.backbone_config, kwargs = consolidate_backbone_kwargs_to_config(
+ backbone_config=self.backbone_config,
+ default_config_type="dinov2",
+ default_config_kwargs={
+ "image_size": 518,
+ "hidden_size": 384,
+ "num_attention_heads": 6,
+ "out_indices": [9, 10, 11, 12],
+ "reshape_hidden_states": False,
+ },
+ **kwargs,
+ )
+
+ self.max_depth = self.max_depth if self.max_depth else 1
+ super().__post_init__(**kwargs)
+
+ def validate_architecture(self):
+ """Part of `@strict`-powered validation. Validates the architecture of the config."""
+ if self.depth_estimation_type not in ["relative", "metric"]:
+ raise ValueError("depth_estimation_type must be one of ['relative', 'metric']")
+
+
+__all__ = ["DepthAnythingConfig"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/depth_anything/modeling_depth_anything.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/depth_anything/modeling_depth_anything.py
new file mode 100644
index 0000000000000000000000000000000000000000..3da9cef51e4a61f93cbecf66908616c127877534
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/depth_anything/modeling_depth_anything.py
@@ -0,0 +1,416 @@
+# Copyright 2024 TikTok and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch Depth Anything model."""
+
+import torch
+from torch import nn
+
+from ...backbone_utils import load_backbone
+from ...modeling_outputs import DepthEstimatorOutput
+from ...modeling_utils import PreTrainedModel
+from ...utils import auto_docstring, logging
+from .configuration_depth_anything import DepthAnythingConfig
+
+
+logger = logging.get_logger(__name__)
+
+# General docstring
+
+
+class DepthAnythingReassembleLayer(nn.Module):
+ def __init__(self, config, channels, factor):
+ super().__init__()
+ self.projection = nn.Conv2d(in_channels=config.reassemble_hidden_size, out_channels=channels, kernel_size=1)
+
+ # up/down sampling depending on factor
+ if factor > 1:
+ self.resize = nn.ConvTranspose2d(channels, channels, kernel_size=factor, stride=factor, padding=0)
+ elif factor == 1:
+ self.resize = nn.Identity()
+ elif factor < 1:
+ # so should downsample
+ self.resize = nn.Conv2d(channels, channels, kernel_size=3, stride=int(1 / factor), padding=1)
+
+ # Copied from transformers.models.dpt.modeling_dpt.DPTReassembleLayer.forward
+ def forward(self, hidden_state):
+ hidden_state = self.projection(hidden_state)
+ hidden_state = self.resize(hidden_state)
+
+ return hidden_state
+
+
+class DepthAnythingReassembleStage(nn.Module):
+ """
+ This class reassembles the hidden states of the backbone into image-like feature representations at various
+ resolutions.
+
+ This happens in 3 stages:
+ 1. Take the patch embeddings and reshape them to image-like feature representations.
+ 2. Project the channel dimension of the hidden states according to `config.neck_hidden_sizes`.
+ 3. Resizing the spatial dimensions (height, width).
+
+ Args:
+ config (`[DepthAnythingConfig]`):
+ Model configuration class defining the model architecture.
+ """
+
+ def __init__(self, config):
+ super().__init__()
+
+ self.config = config
+ self.layers = nn.ModuleList()
+ for channels, factor in zip(config.neck_hidden_sizes, config.reassemble_factors):
+ self.layers.append(DepthAnythingReassembleLayer(config, channels=channels, factor=factor))
+
+ def forward(self, hidden_states: list[torch.Tensor], patch_height=None, patch_width=None) -> list[torch.Tensor]:
+ """
+ Args:
+ hidden_states (`list[torch.FloatTensor]`, each of shape `(batch_size, sequence_length + 1, hidden_size)`):
+ List of hidden states from the backbone.
+ """
+ out = []
+
+ for i, hidden_state in enumerate(hidden_states):
+ # reshape to (batch_size, num_channels, height, width)
+ hidden_state = hidden_state[:, 1:]
+ batch_size, _, num_channels = hidden_state.shape
+ hidden_state = hidden_state.reshape(batch_size, patch_height, patch_width, num_channels)
+ hidden_state = hidden_state.permute(0, 3, 1, 2).contiguous()
+ hidden_state = self.layers[i](hidden_state)
+ out.append(hidden_state)
+
+ return out
+
+
+class DepthAnythingPreActResidualLayer(nn.Module):
+ """
+ ResidualConvUnit, pre-activate residual unit.
+
+ Args:
+ config (`[DepthAnythingConfig]`):
+ Model configuration class defining the model architecture.
+ """
+
+ def __init__(self, config):
+ super().__init__()
+
+ self.activation1 = nn.ReLU()
+ self.convolution1 = nn.Conv2d(
+ config.fusion_hidden_size,
+ config.fusion_hidden_size,
+ kernel_size=3,
+ stride=1,
+ padding=1,
+ bias=True,
+ )
+
+ self.activation2 = nn.ReLU()
+ self.convolution2 = nn.Conv2d(
+ config.fusion_hidden_size,
+ config.fusion_hidden_size,
+ kernel_size=3,
+ stride=1,
+ padding=1,
+ bias=True,
+ )
+
+ def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
+ residual = hidden_state
+ hidden_state = self.activation1(hidden_state)
+ hidden_state = self.convolution1(hidden_state)
+ hidden_state = self.activation2(hidden_state)
+ hidden_state = self.convolution2(hidden_state)
+
+ return hidden_state + residual
+
+
+class DepthAnythingFeatureFusionLayer(nn.Module):
+ """Feature fusion layer, merges feature maps from different stages.
+
+ Args:
+ config (`[DepthAnythingConfig]`):
+ Model configuration class defining the model architecture.
+ """
+
+ def __init__(self, config):
+ super().__init__()
+
+ self.projection = nn.Conv2d(config.fusion_hidden_size, config.fusion_hidden_size, kernel_size=1, bias=True)
+
+ self.residual_layer1 = DepthAnythingPreActResidualLayer(config)
+ self.residual_layer2 = DepthAnythingPreActResidualLayer(config)
+
+ def forward(self, hidden_state, residual=None, size=None):
+ if residual is not None:
+ if hidden_state.shape != residual.shape:
+ residual = nn.functional.interpolate(
+ residual, size=(hidden_state.shape[2], hidden_state.shape[3]), mode="bilinear", align_corners=False
+ )
+ hidden_state = hidden_state + self.residual_layer1(residual)
+
+ hidden_state = self.residual_layer2(hidden_state)
+
+ modifier = {"scale_factor": 2} if size is None else {"size": size}
+
+ hidden_state = nn.functional.interpolate(
+ hidden_state,
+ **modifier,
+ mode="bilinear",
+ align_corners=True,
+ )
+ hidden_state = self.projection(hidden_state)
+
+ return hidden_state
+
+
+class DepthAnythingFeatureFusionStage(nn.Module):
+ # Copied from transformers.models.dpt.modeling_dpt.DPTFeatureFusionStage.__init__ with DPT->DepthAnything
+ def __init__(self, config: DepthAnythingConfig):
+ super().__init__()
+ self.layers = nn.ModuleList()
+ for _ in range(len(config.neck_hidden_sizes)):
+ self.layers.append(DepthAnythingFeatureFusionLayer(config))
+
+ def forward(self, hidden_states, size=None):
+ # reversing the hidden_states, we start from the last
+ hidden_states = hidden_states[::-1]
+
+ fused_hidden_states = []
+ fused_hidden_state = None
+
+ for idx, (hidden_state, layer) in enumerate(zip(hidden_states, self.layers)):
+ size = hidden_states[idx + 1].shape[2:] if idx != (len(hidden_states) - 1) else None
+
+ if fused_hidden_state is None:
+ # first layer only uses the last hidden_state
+ fused_hidden_state = layer(hidden_state, size=size)
+ else:
+ fused_hidden_state = layer(fused_hidden_state, hidden_state, size=size)
+
+ fused_hidden_states.append(fused_hidden_state)
+
+ return fused_hidden_states
+
+
+# Modified from transformers.models.dpt.modeling_dpt.DPTPreTrainedModel with DPT->DepthAnything,dpt->depth_anything
+# avoiding sdpa and flash_attn_2 support, it's done in the backend
+@auto_docstring
+class DepthAnythingPreTrainedModel(PreTrainedModel):
+ config: DepthAnythingConfig
+ base_model_prefix = "depth_anything"
+ main_input_name = "pixel_values"
+ input_modalities = ("image",)
+ supports_gradient_checkpointing = True
+
+
+class DepthAnythingNeck(nn.Module):
+ """
+ DepthAnythingNeck. A neck is a module that is normally used between the backbone and the head. It takes a list of tensors as
+ input and produces another list of tensors as output. For DepthAnything, it includes 2 stages:
+
+ * DepthAnythingReassembleStage
+ * DepthAnythingFeatureFusionStage.
+
+ Args:
+ config (dict): config dict.
+ """
+
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+
+ self.reassemble_stage = DepthAnythingReassembleStage(config)
+
+ self.convs = nn.ModuleList()
+ for channel in config.neck_hidden_sizes:
+ self.convs.append(nn.Conv2d(channel, config.fusion_hidden_size, kernel_size=3, padding=1, bias=False))
+
+ # fusion
+ self.fusion_stage = DepthAnythingFeatureFusionStage(config)
+
+ def forward(self, hidden_states: list[torch.Tensor], patch_height=None, patch_width=None) -> list[torch.Tensor]:
+ """
+ Args:
+ hidden_states (`list[torch.FloatTensor]`, each of shape `(batch_size, sequence_length, hidden_size)` or `(batch_size, hidden_size, height, width)`):
+ List of hidden states from the backbone.
+ """
+ if not isinstance(hidden_states, (tuple, list)):
+ raise TypeError("hidden_states should be a tuple or list of tensors")
+
+ if len(hidden_states) != len(self.config.neck_hidden_sizes):
+ raise ValueError("The number of hidden states should be equal to the number of neck hidden sizes.")
+
+ # postprocess hidden states
+ hidden_states = self.reassemble_stage(hidden_states, patch_height, patch_width)
+
+ features = [self.convs[i](feature) for i, feature in enumerate(hidden_states)]
+
+ # fusion blocks
+ output = self.fusion_stage(features)
+
+ return output
+
+
+class DepthAnythingDepthEstimationHead(nn.Module):
+ """
+ Output head consisting of 3 convolutional layers. It progressively halves the feature dimension and upsamples
+ the predictions to the input resolution after the first convolutional layer (details can be found in the DPT paper's
+ supplementary material). The final activation function is either ReLU or Sigmoid, depending on the depth estimation
+ type (relative or metric). For metric depth estimation, the output is scaled by the maximum depth used during pretraining.
+ """
+
+ def __init__(self, config):
+ super().__init__()
+
+ self.head_in_index = config.head_in_index
+ self.patch_size = config.patch_size
+
+ features = config.fusion_hidden_size
+ self.conv1 = nn.Conv2d(features, features // 2, kernel_size=3, stride=1, padding=1)
+ self.conv2 = nn.Conv2d(features // 2, config.head_hidden_size, kernel_size=3, stride=1, padding=1)
+ self.activation1 = nn.ReLU()
+ self.conv3 = nn.Conv2d(config.head_hidden_size, 1, kernel_size=1, stride=1, padding=0)
+ if config.depth_estimation_type == "relative":
+ self.activation2 = nn.ReLU()
+ elif config.depth_estimation_type == "metric":
+ self.activation2 = nn.Sigmoid()
+ else:
+ raise ValueError(f"Unknown depth estimation type: {config.depth_estimation_type}")
+ self.max_depth = config.max_depth
+
+ def forward(self, hidden_states: list[torch.Tensor], patch_height, patch_width) -> torch.Tensor:
+ hidden_states = hidden_states[self.head_in_index]
+
+ predicted_depth = self.conv1(hidden_states)
+ predicted_depth = nn.functional.interpolate(
+ predicted_depth,
+ (int(patch_height * self.patch_size), int(patch_width * self.patch_size)),
+ mode="bilinear",
+ align_corners=True,
+ )
+ predicted_depth = self.conv2(predicted_depth)
+ predicted_depth = self.activation1(predicted_depth)
+ predicted_depth = self.conv3(predicted_depth)
+ predicted_depth = self.activation2(predicted_depth) * self.max_depth
+ predicted_depth = predicted_depth.squeeze(dim=1) # shape (batch_size, height, width)
+
+ return predicted_depth
+
+
+@auto_docstring(
+ custom_intro="""
+ Depth Anything Model with a depth estimation head on top (consisting of 3 convolutional layers) e.g. for KITTI, NYUv2.
+ """
+)
+class DepthAnythingForDepthEstimation(DepthAnythingPreTrainedModel):
+ _no_split_modules = ["DPTViTEmbeddings"]
+
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.backbone = load_backbone(config)
+ self.neck = DepthAnythingNeck(config)
+ self.head = DepthAnythingDepthEstimationHead(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: torch.FloatTensor,
+ labels: torch.LongTensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple[torch.Tensor] | DepthEstimatorOutput:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, height, width)`, *optional*):
+ Ground truth depth estimation maps for computing the loss.
+
+ Examples:
+ ```python
+ >>> from transformers import AutoImageProcessor, AutoModelForDepthEstimation
+ >>> import torch
+ >>> import numpy as np
+ >>> from PIL import Image
+ >>> import httpx
+ >>> from io import BytesIO
+
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
+ >>> with httpx.stream("GET", url) as response:
+ ... image = Image.open(BytesIO(response.read()))
+
+ >>> image_processor = AutoImageProcessor.from_pretrained("LiheYoung/depth-anything-small-hf")
+ >>> model = AutoModelForDepthEstimation.from_pretrained("LiheYoung/depth-anything-small-hf")
+
+ >>> # prepare image for the model
+ >>> inputs = image_processor(images=image, return_tensors="pt")
+
+ >>> with torch.no_grad():
+ ... outputs = model(**inputs)
+
+ >>> # interpolate to original size
+ >>> post_processed_output = image_processor.post_process_depth_estimation(
+ ... outputs,
+ ... target_sizes=[(image.height, image.width)],
+ ... )
+
+ >>> # visualize the prediction
+ >>> predicted_depth = post_processed_output[0]["predicted_depth"]
+ >>> depth = predicted_depth * 255 / predicted_depth.max()
+ >>> depth = depth.detach().cpu().numpy()
+ >>> depth = Image.fromarray(depth.astype("uint8"))
+ ```"""
+ loss = None
+ if labels is not None:
+ raise NotImplementedError("Training is not implemented yet")
+
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+
+ outputs = self.backbone.forward_with_filtered_kwargs(
+ pixel_values, output_hidden_states=output_hidden_states, output_attentions=output_attentions
+ )
+ hidden_states = outputs.feature_maps
+
+ _, _, height, width = pixel_values.shape
+ patch_size = self.config.patch_size
+ patch_height = height // patch_size
+ patch_width = width // patch_size
+
+ hidden_states = self.neck(hidden_states, patch_height, patch_width)
+
+ predicted_depth = self.head(hidden_states, patch_height, patch_width)
+
+ if not return_dict:
+ if output_hidden_states:
+ output = (predicted_depth,) + outputs[1:]
+ else:
+ output = (predicted_depth,) + outputs[2:]
+ return ((loss,) + output) if loss is not None else output
+
+ return DepthEstimatorOutput(
+ loss=loss,
+ predicted_depth=predicted_depth,
+ hidden_states=outputs.hidden_states if output_hidden_states else None,
+ attentions=outputs.attentions,
+ )
+
+
+__all__ = ["DepthAnythingForDepthEstimation", "DepthAnythingPreTrainedModel"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dia/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dia/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e5e3095c2c20932dc679979b8240d797bea6ad40
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dia/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dia/__pycache__/configuration_dia.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dia/__pycache__/configuration_dia.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6d74bb1fb2f498b1abd12869b4a1696dffc05e31
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dia/__pycache__/configuration_dia.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dia/__pycache__/feature_extraction_dia.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dia/__pycache__/feature_extraction_dia.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e34587a4a0b070cf6a42f62ad88d219e31bf82ac
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dia/__pycache__/feature_extraction_dia.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dia/__pycache__/generation_dia.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dia/__pycache__/generation_dia.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bc391543ba2de53a9749ac93e968966384b99dc2
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dia/__pycache__/generation_dia.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dia/__pycache__/modeling_dia.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dia/__pycache__/modeling_dia.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7220a3e7a89aae65cf88ab92d45ede303569f88b
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dia/__pycache__/modeling_dia.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dia/__pycache__/modular_dia.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dia/__pycache__/modular_dia.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..af2d8b6e8d68f35ece9d1ace6202853e1abc6b50
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dia/__pycache__/modular_dia.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dia/__pycache__/processing_dia.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dia/__pycache__/processing_dia.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d1bab3a8c3fb6532b86c50bea29015c3fe0709d8
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dia/__pycache__/processing_dia.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dia/__pycache__/tokenization_dia.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dia/__pycache__/tokenization_dia.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6e7e312dc579fb141fcb6f8f0777e99fa93a930e
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dia/__pycache__/tokenization_dia.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dialogpt/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dialogpt/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dialogpt/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dialogpt/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..187a9bc5ea15cd4d27de40bd191e87ee107343f2
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dialogpt/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dinat/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dinat/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cecdb4f961b9038d4f0a96151b2b14588c7f8790
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dinat/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dinat/__pycache__/configuration_dinat.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dinat/__pycache__/configuration_dinat.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..53d22562fde638c10119d112b36f68e3a0010267
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dinat/__pycache__/configuration_dinat.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dinat/__pycache__/modeling_dinat.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dinat/__pycache__/modeling_dinat.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1a57569d08bdcf8cb4e3e72f0460c91191d594fb
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dinat/__pycache__/modeling_dinat.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dinov2/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dinov2/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..002634ed4b490fdc845c911b4a5515fe9833db5d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dinov2/__init__.py
@@ -0,0 +1,27 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_dinov2 import *
+ from .modeling_dinov2 import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dinov2/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dinov2/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..17500de347804a68be47627a559febaed8e5a155
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dinov2/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dinov2/__pycache__/configuration_dinov2.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dinov2/__pycache__/configuration_dinov2.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9581187428c0e4da208cc9e3714106567c09a262
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dinov2/__pycache__/configuration_dinov2.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dinov2/__pycache__/modeling_dinov2.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dinov2/__pycache__/modeling_dinov2.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0e9713987a0ef846cb358d4eefa6d83211ca35db
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dinov2/__pycache__/modeling_dinov2.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dinov2/configuration_dinov2.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dinov2/configuration_dinov2.py
new file mode 100644
index 0000000000000000000000000000000000000000..0221c54db7fddc9ecca490d88aabf4a0d275d07d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dinov2/configuration_dinov2.py
@@ -0,0 +1,87 @@
+# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""DINOv2 model configuration"""
+
+from huggingface_hub.dataclasses import strict
+
+from ...backbone_utils import BackboneConfigMixin
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring
+
+
+@auto_docstring(checkpoint="facebook/dinov2-base")
+@strict
+class Dinov2Config(BackboneConfigMixin, PreTrainedConfig):
+ r"""
+ layerscale_value (`float`, *optional*, defaults to 1.0):
+ Initial value to use for layer scale.
+ use_swiglu_ffn (`bool`, *optional*, defaults to `False`):
+ Whether to use the SwiGLU feedforward neural network.
+ apply_layernorm (`bool`, *optional*, defaults to `True`):
+ Whether to apply layer normalization to the feature maps in case the model is used as backbone.
+ reshape_hidden_states (`bool`, *optional*, defaults to `True`):
+ Whether to reshape the feature maps to 4D tensors of shape `(batch_size, hidden_size, height, width)` in
+ case the model is used as backbone. If `False`, the feature maps will be 3D tensors of shape `(batch_size,
+ seq_len, hidden_size)`.
+ use_mask_token (`bool`, *optional*, defaults to `True`):
+ Whether to use mask_token in embeddings.
+
+ Example:
+
+ ```python
+ >>> from transformers import Dinov2Config, Dinov2Model
+
+ >>> # Initializing a Dinov2 dinov2-base style configuration
+ >>> configuration = Dinov2Config()
+
+ >>> # Initializing a model (with random weights) from the dinov2-base style configuration
+ >>> model = Dinov2Model(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "dinov2"
+
+ hidden_size: int = 768
+ num_hidden_layers: int = 12
+ num_attention_heads: int = 12
+ mlp_ratio: int = 4
+ hidden_act: str = "gelu"
+ hidden_dropout_prob: float | int = 0.0
+ attention_probs_dropout_prob: float | int = 0.0
+ initializer_range: float = 0.02
+ layer_norm_eps: float = 1e-6
+ image_size: int | list[int] | tuple[int, int] = 224
+ patch_size: int | list[int] | tuple[int, int] = 14
+ num_channels: int = 3
+ qkv_bias: bool = True
+ layerscale_value: float = 1.0
+ drop_path_rate: float | int = 0.0
+ use_swiglu_ffn: bool = False
+ _out_features: list[str] | None = None
+ _out_indices: list[int] | None = None
+ apply_layernorm: bool = True
+ reshape_hidden_states: bool = True
+ use_mask_token: bool = True
+
+ def __post_init__(self, **kwargs):
+ self.stage_names = ["stem"] + [f"stage{idx}" for idx in range(1, self.num_hidden_layers + 1)]
+ self.set_output_features_output_indices(
+ out_indices=kwargs.pop("out_indices", None), out_features=kwargs.pop("out_features", None)
+ )
+ super().__post_init__(**kwargs)
+
+
+__all__ = ["Dinov2Config"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dinov2/modeling_dinov2.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dinov2/modeling_dinov2.py
new file mode 100644
index 0000000000000000000000000000000000000000..f1b395da256b41d86e54f3c59f56e02411ba93e1
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dinov2/modeling_dinov2.py
@@ -0,0 +1,621 @@
+# Copyright 2023 Meta AI and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch DINOv2 model."""
+
+import collections.abc
+from collections.abc import Callable
+
+import torch
+from torch import nn
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...backbone_utils import BackboneMixin, filter_output_hidden_states
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import BackboneOutput, BaseModelOutput, BaseModelOutputWithPooling, ImageClassifierOutput
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import TransformersKwargs, auto_docstring, logging, torch_int
+from ...utils.generic import can_return_tuple, merge_with_config_defaults
+from ...utils.output_capturing import capture_outputs
+from .configuration_dinov2 import Dinov2Config
+
+
+logger = logging.get_logger(__name__)
+
+
+class Dinov2Embeddings(nn.Module):
+ """
+ Construct the CLS token, mask token, position and patch embeddings.
+ """
+
+ def __init__(self, config: Dinov2Config) -> None:
+ super().__init__()
+
+ self.cls_token = nn.Parameter(torch.randn(1, 1, config.hidden_size))
+ if config.use_mask_token:
+ self.mask_token = nn.Parameter(torch.zeros(1, config.hidden_size))
+ self.patch_embeddings = Dinov2PatchEmbeddings(config)
+ num_patches = self.patch_embeddings.num_patches
+ self.position_embeddings = nn.Parameter(torch.randn(1, num_patches + 1, config.hidden_size))
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+ self.patch_size = config.patch_size
+ self.use_mask_token = config.use_mask_token
+ self.config = config
+
+ def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor:
+ """
+ This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher resolution
+ images. This method is also adapted to support torch.jit tracing and interpolation at torch.float32 precision.
+
+ Adapted from:
+ - https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174-L194, and
+ - https://github.com/facebookresearch/dinov2/blob/e1277af2ba9496fbadf7aec6eba56e8d882d1e35/dinov2/models/vision_transformer.py#L179-L211
+ """
+
+ num_patches = embeddings.shape[1] - 1
+ num_positions = self.position_embeddings.shape[1] - 1
+
+ # always interpolate when tracing to ensure the exported model works for dynamic input shapes
+ if not torch.jit.is_tracing() and num_patches == num_positions and height == width:
+ return self.position_embeddings
+
+ class_pos_embed = self.position_embeddings[:, :1]
+ patch_pos_embed = self.position_embeddings[:, 1:]
+
+ dim = embeddings.shape[-1]
+
+ new_height = height // self.patch_size
+ new_width = width // self.patch_size
+
+ sqrt_num_positions = torch_int(num_positions**0.5)
+ patch_pos_embed = patch_pos_embed.reshape(1, sqrt_num_positions, sqrt_num_positions, dim)
+ patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2)
+ target_dtype = patch_pos_embed.dtype
+ patch_pos_embed = nn.functional.interpolate(
+ patch_pos_embed.to(torch.float32),
+ size=(new_height, new_width),
+ mode="bicubic",
+ align_corners=False,
+ ).to(dtype=target_dtype)
+
+ patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
+
+ return torch.cat((class_pos_embed, patch_pos_embed), dim=1)
+
+ def forward(self, pixel_values: torch.Tensor, bool_masked_pos: torch.Tensor | None = None) -> torch.Tensor:
+ batch_size, _, height, width = pixel_values.shape
+ target_dtype = self.patch_embeddings.projection.weight.dtype
+ embeddings = self.patch_embeddings(pixel_values.to(dtype=target_dtype))
+
+ if bool_masked_pos is not None and self.use_mask_token:
+ embeddings = torch.where(
+ bool_masked_pos.unsqueeze(-1), self.mask_token.to(embeddings.dtype).unsqueeze(0), embeddings
+ )
+
+ # add the [CLS] token to the embedded patch tokens
+ cls_tokens = self.cls_token.expand(batch_size, -1, -1)
+ embeddings = torch.cat((cls_tokens, embeddings), dim=1)
+
+ # add positional encoding to each token
+ embeddings = embeddings + self.interpolate_pos_encoding(embeddings, height, width)
+
+ embeddings = self.dropout(embeddings)
+
+ return embeddings
+
+
+class Dinov2PatchEmbeddings(nn.Module):
+ """
+ This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
+ `hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
+ Transformer.
+ """
+
+ def __init__(self, config):
+ super().__init__()
+ image_size, patch_size = config.image_size, config.patch_size
+ num_channels, hidden_size = config.num_channels, config.hidden_size
+
+ image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
+ patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
+ num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
+ self.image_size = image_size
+ self.patch_size = patch_size
+ self.num_channels = num_channels
+ self.num_patches = num_patches
+
+ self.projection = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=patch_size)
+
+ def forward(self, pixel_values: torch.Tensor) -> torch.Tensor:
+ num_channels = pixel_values.shape[1]
+ if num_channels != self.num_channels:
+ raise ValueError(
+ "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
+ f" Expected {self.num_channels} but got {num_channels}."
+ )
+ embeddings = self.projection(pixel_values).flatten(2).transpose(1, 2)
+ return embeddings
+
+
+# Copied from transformers.models.bert.modeling_bert.eager_attention_forward
+def eager_attention_forward(
+ module: nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: torch.Tensor | None,
+ scaling: float | None = None,
+ dropout: float = 0.0,
+ **kwargs: Unpack[TransformersKwargs],
+):
+ if scaling is None:
+ scaling = query.size(-1) ** -0.5
+
+ # Take the dot product between "query" and "key" to get the raw attention scores.
+ attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
+
+ if attention_mask is not None:
+ attn_weights = attn_weights + attention_mask
+
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
+
+ attn_output = torch.matmul(attn_weights, value)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+
+ return attn_output, attn_weights
+
+
+# Todo - Refactor as part of vision refactor. Copied from transformers.models.vit.modeling_vit.ViTAttention with ViT->Dinov2
+class Dinov2SelfAttention(nn.Module):
+ def __init__(self, config: Dinov2Config):
+ super().__init__()
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
+ raise ValueError(
+ f"The hidden size {config.hidden_size} is not a multiple of the number of attention "
+ f"heads {config.num_attention_heads}."
+ )
+
+ self.config = config
+ self.num_attention_heads = config.num_attention_heads
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
+ self.dropout_prob = config.attention_probs_dropout_prob
+ self.scaling = self.attention_head_size**-0.5
+ self.is_causal = False
+
+ self.query = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
+ self.key = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
+ self.value = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor, torch.Tensor]:
+ batch_size = hidden_states.shape[0]
+ new_shape = batch_size, -1, self.num_attention_heads, self.attention_head_size
+
+ key_layer = self.key(hidden_states).view(*new_shape).transpose(1, 2)
+ value_layer = self.value(hidden_states).view(*new_shape).transpose(1, 2)
+ query_layer = self.query(hidden_states).view(*new_shape).transpose(1, 2)
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ context_layer, attention_probs = attention_interface(
+ self,
+ query_layer,
+ key_layer,
+ value_layer,
+ None,
+ is_causal=self.is_causal,
+ scaling=self.scaling,
+ dropout=0.0 if not self.training else self.dropout_prob,
+ **kwargs,
+ )
+
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
+ context_layer = context_layer.reshape(new_context_layer_shape)
+
+ return context_layer, attention_probs
+
+
+# Todo - Refactor as part of vision refactor. Copied from transformers.models.vit.modeling_vit.ViTAttention with ViT->Dinov2
+class Dinov2SelfOutput(nn.Module):
+ """
+ The residual connection is defined in Dinov2Layer instead of here (as is the case with other models), due to the
+ layernorm applied before each block.
+ """
+
+ def __init__(self, config: Dinov2Config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ return hidden_states
+
+
+# Todo - Refactor as part of vision refactor. Copied from transformers.models.vit.modeling_vit.ViTAttention with ViT->Dinov2
+class Dinov2Attention(nn.Module):
+ def __init__(self, config: Dinov2Config):
+ super().__init__()
+ self.attention = Dinov2SelfAttention(config)
+ self.output = Dinov2SelfOutput(config)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.Tensor:
+ self_attn_output, _ = self.attention(hidden_states, **kwargs)
+ output = self.output(self_attn_output, hidden_states)
+ return output
+
+
+class Dinov2LayerScale(nn.Module):
+ def __init__(self, config) -> None:
+ super().__init__()
+ self.lambda1 = nn.Parameter(config.layerscale_value * torch.ones(config.hidden_size))
+
+ def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
+ return hidden_state * self.lambda1
+
+
+class Dinov2MLP(nn.Module):
+ def __init__(self, config) -> None:
+ super().__init__()
+ in_features = out_features = config.hidden_size
+ hidden_features = int(config.hidden_size * config.mlp_ratio)
+ self.fc1 = nn.Linear(in_features, hidden_features, bias=True)
+ if isinstance(config.hidden_act, str):
+ self.activation = ACT2FN[config.hidden_act]
+ else:
+ self.activation = config.hidden_act
+ self.fc2 = nn.Linear(hidden_features, out_features, bias=True)
+
+ def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
+ hidden_state = self.fc1(hidden_state)
+ hidden_state = self.activation(hidden_state)
+ hidden_state = self.fc2(hidden_state)
+ return hidden_state
+
+
+class Dinov2SwiGLUFFN(nn.Module):
+ def __init__(self, config) -> None:
+ super().__init__()
+ in_features = out_features = config.hidden_size
+ hidden_features = int(config.hidden_size * config.mlp_ratio)
+ hidden_features = (int(hidden_features * 2 / 3) + 7) // 8 * 8
+
+ self.weights_in = nn.Linear(in_features, 2 * hidden_features, bias=True)
+ self.weights_out = nn.Linear(hidden_features, out_features, bias=True)
+
+ def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
+ hidden_state = self.weights_in(hidden_state)
+ x1, x2 = hidden_state.chunk(2, dim=-1)
+ hidden = nn.functional.silu(x1) * x2
+ return self.weights_out(hidden)
+
+
+# Copied from transformers.models.swin.modular_swin.SwinDropPath with SwinDropPath->Dinov2DropPath
+class Dinov2DropPath(nn.Module):
+ """Stochastic depth (DropPath) per sample, for residual blocks.
+
+ Identity when ``drop_prob`` is 0 or outside training. See `Deep Networks with Stochastic Depth
+ `_.
+ """
+
+ def __init__(self, drop_prob: float = 0.0) -> None:
+ super().__init__()
+ self.drop_prob = drop_prob
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ if self.drop_prob == 0.0 or not self.training:
+ return hidden_states
+ keep_prob = 1 - self.drop_prob
+ shape = (hidden_states.shape[0],) + (1,) * (hidden_states.ndim - 1)
+ random_tensor = torch.rand(shape, dtype=hidden_states.dtype, device=hidden_states.device)
+ random_tensor = torch.floor(random_tensor + keep_prob)
+ return hidden_states.div(keep_prob) * random_tensor
+
+ def extra_repr(self) -> str:
+ return f"p={self.drop_prob}"
+
+
+class Dinov2Layer(GradientCheckpointingLayer):
+ """This corresponds to the Block class in the original implementation."""
+
+ def __init__(self, config: Dinov2Config) -> None:
+ super().__init__()
+
+ self.norm1 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.attention = Dinov2Attention(config)
+ self.layer_scale1 = Dinov2LayerScale(config)
+ self.drop_path = Dinov2DropPath(config.drop_path_rate) if config.drop_path_rate > 0.0 else nn.Identity()
+
+ self.norm2 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+
+ if config.use_swiglu_ffn:
+ self.mlp = Dinov2SwiGLUFFN(config)
+ else:
+ self.mlp = Dinov2MLP(config)
+ self.layer_scale2 = Dinov2LayerScale(config)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ ) -> torch.Tensor:
+ hidden_states_norm = self.norm1(hidden_states)
+ self_attention_output = self.attention(hidden_states_norm)
+ self_attention_output = self.layer_scale1(self_attention_output)
+
+ # first residual connection
+ hidden_states = self.drop_path(self_attention_output) + hidden_states
+
+ # in Dinov2, layernorm is also applied after self-attention
+ layer_output = self.norm2(hidden_states)
+ layer_output = self.mlp(layer_output)
+ layer_output = self.layer_scale2(layer_output)
+
+ # second residual connection
+ layer_output = self.drop_path(layer_output) + hidden_states
+
+ return layer_output
+
+
+@auto_docstring
+class Dinov2PreTrainedModel(PreTrainedModel):
+ config: Dinov2Config
+ base_model_prefix = "dinov2"
+ main_input_name = "pixel_values"
+ input_modalities = ("image",)
+ supports_gradient_checkpointing = True
+ _no_split_modules = ["Dinov2Layer"]
+ _supports_sdpa = True
+ _supports_flash_attn = True
+ _supports_flex_attn = True
+ _supports_attention_backend = True
+ _can_record_outputs = {
+ "hidden_states": Dinov2Layer,
+ "attentions": Dinov2SelfAttention,
+ }
+
+ @torch.no_grad()
+ def _init_weights(self, module: nn.Linear | nn.Conv2d | nn.LayerNorm) -> None:
+ """Initialize the weights"""
+ if isinstance(module, (nn.Linear, nn.Conv2d)):
+ init.trunc_normal_(module.weight, mean=0.0, std=self.config.initializer_range)
+ if module.bias is not None:
+ init.zeros_(module.bias)
+ elif isinstance(module, nn.LayerNorm):
+ init.zeros_(module.bias)
+ init.ones_(module.weight)
+ elif isinstance(module, Dinov2Embeddings):
+ init.trunc_normal_(module.position_embeddings, mean=0.0, std=self.config.initializer_range)
+ init.trunc_normal_(module.cls_token, mean=0.0, std=self.config.initializer_range)
+ if self.config.use_mask_token:
+ init.zeros_(module.mask_token)
+ elif isinstance(module, Dinov2LayerScale):
+ init.constant_(module.lambda1, self.config.layerscale_value)
+
+
+class Dinov2Encoder(Dinov2PreTrainedModel):
+ def __init__(self, config: Dinov2Config):
+ super().__init__(config)
+ self.layer = nn.ModuleList([Dinov2Layer(config) for _ in range(config.num_hidden_layers)])
+ self.post_init()
+
+ @merge_with_config_defaults
+ @capture_outputs(tie_last_hidden_states=False)
+ def forward(self, hidden_states: torch.Tensor, **kwargs: Unpack[TransformersKwargs]) -> BaseModelOutput:
+ for layer_module in self.layer:
+ hidden_states = layer_module(hidden_states)
+
+ return BaseModelOutput(last_hidden_state=hidden_states)
+
+
+@auto_docstring
+class Dinov2Model(Dinov2PreTrainedModel):
+ def __init__(self, config: Dinov2Config):
+ super().__init__(config)
+ self.config = config
+
+ self.embeddings = Dinov2Embeddings(config)
+ self.encoder = Dinov2Encoder(config)
+
+ self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self) -> Dinov2PatchEmbeddings:
+ return self.embeddings.patch_embeddings
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: torch.Tensor | None = None,
+ bool_masked_pos: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> BaseModelOutputWithPooling:
+ r"""
+ bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, sequence_length)`):
+ Boolean masked positions. Indicates which patches are masked (1) and which aren't (0). Only relevant for
+ pre-training.
+ """
+ if pixel_values is None:
+ raise ValueError("You have to specify pixel_values")
+
+ embedding_output = self.embeddings(pixel_values, bool_masked_pos=bool_masked_pos)
+
+ encoder_outputs: BaseModelOutput = self.encoder(embedding_output, **kwargs)
+ sequence_output = encoder_outputs.last_hidden_state
+ sequence_output = self.layernorm(sequence_output)
+ pooled_output = sequence_output[:, 0, :]
+
+ return BaseModelOutputWithPooling(
+ last_hidden_state=sequence_output,
+ pooler_output=pooled_output,
+ hidden_states=encoder_outputs.hidden_states,
+ attentions=encoder_outputs.attentions,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ Dinov2 Model transformer with an image classification head on top (a linear layer on top of the final hidden state
+ of the [CLS] token) e.g. for ImageNet.
+ """
+)
+class Dinov2ForImageClassification(Dinov2PreTrainedModel):
+ def __init__(self, config: Dinov2Config) -> None:
+ super().__init__(config)
+
+ self.num_labels = config.num_labels
+ self.dinov2 = Dinov2Model(config)
+
+ # Classifier head
+ self.classifier = (
+ nn.Linear(config.hidden_size * 2, config.num_labels) if config.num_labels > 0 else nn.Identity()
+ )
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: torch.Tensor | None = None,
+ labels: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> ImageClassifierOutput:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+ outputs: BaseModelOutputWithPooling = self.dinov2(pixel_values, **kwargs)
+
+ sequence_output = outputs.last_hidden_state # batch_size, sequence_length, hidden_size
+ cls_token = sequence_output[:, 0]
+ patch_tokens = sequence_output[:, 1:]
+
+ linear_input = torch.cat([cls_token, patch_tokens.mean(dim=1)], dim=1)
+ logits = self.classifier(linear_input)
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(labels, logits, self.config, **kwargs)
+
+ return ImageClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ Dinov2 backbone, to be used with frameworks like DETR and MaskFormer.
+ """
+)
+class Dinov2Backbone(BackboneMixin, Dinov2PreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.num_features = [config.hidden_size for _ in range(config.num_hidden_layers + 1)]
+ self.embeddings = Dinov2Embeddings(config)
+ self.encoder = Dinov2Encoder(config)
+
+ self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self) -> Dinov2PatchEmbeddings:
+ return self.embeddings.patch_embeddings
+
+ @can_return_tuple
+ @filter_output_hidden_states
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: torch.Tensor,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> BackboneOutput:
+ r"""
+ Examples:
+
+ ```python
+ >>> from transformers import AutoImageProcessor, AutoBackbone
+ >>> import torch
+ >>> from PIL import Image
+ >>> import httpx
+ >>> from io import BytesIO
+
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
+ >>> with httpx.stream("GET", url) as response:
+ ... image = Image.open(BytesIO(response.read()))
+
+ >>> processor = AutoImageProcessor.from_pretrained("facebook/dinov2-base")
+ >>> model = AutoBackbone.from_pretrained(
+ ... "facebook/dinov2-base", out_features=["stage2", "stage5", "stage8", "stage11"]
+ ... )
+
+ >>> inputs = processor(image, return_tensors="pt")
+
+ >>> outputs = model(**inputs)
+ >>> feature_maps = outputs.feature_maps
+ >>> list(feature_maps[-1].shape)
+ [1, 768, 16, 16]
+ ```"""
+ kwargs["output_hidden_states"] = True # required to extract layers for the stages
+
+ embedding_output = self.embeddings(pixel_values)
+ output: BaseModelOutput = self.encoder(embedding_output, **kwargs)
+ hidden_states = output.hidden_states
+
+ feature_maps = []
+ for stage, hidden_state in zip(self.stage_names, hidden_states):
+ if stage in self.out_features:
+ if self.config.apply_layernorm:
+ hidden_state = self.layernorm(hidden_state)
+ if self.config.reshape_hidden_states:
+ hidden_state = hidden_state[:, 1:]
+ # this was actually a bug in the original implementation that we copied here,
+ # cause normally the order is height, width
+ batch_size, _, height, width = pixel_values.shape
+ patch_size = self.config.patch_size
+ hidden_state = hidden_state.reshape(batch_size, height // patch_size, width // patch_size, -1)
+ hidden_state = hidden_state.permute(0, 3, 1, 2).contiguous()
+ feature_maps.append(hidden_state)
+
+ return BackboneOutput(
+ feature_maps=tuple(feature_maps),
+ hidden_states=hidden_states,
+ attentions=output.attentions,
+ )
+
+
+__all__ = ["Dinov2ForImageClassification", "Dinov2Model", "Dinov2PreTrainedModel", "Dinov2Backbone"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dinov3_convnext/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dinov3_convnext/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2110527b71a713896413298c33784e45506b08f9
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dinov3_convnext/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dinov3_convnext/__pycache__/configuration_dinov3_convnext.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dinov3_convnext/__pycache__/configuration_dinov3_convnext.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bbfcbd720adc9f0e08fd42782f8e89839e696f72
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dinov3_convnext/__pycache__/configuration_dinov3_convnext.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dinov3_convnext/__pycache__/modeling_dinov3_convnext.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dinov3_convnext/__pycache__/modeling_dinov3_convnext.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fa8f3a79dd6d43536cf5665f9edded576a56237d
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dinov3_convnext/__pycache__/modeling_dinov3_convnext.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/doge/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/doge/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..8c214c32dfcdecd28e5afddab2bc266120f45283
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/doge/__init__.py
@@ -0,0 +1,27 @@
+# Copyright 2025 Jingze Shi and the HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_doge import *
+ from .modeling_doge import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/doge/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/doge/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..15f5384f2739782cc6fdef450787eb776877c264
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/doge/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/doge/__pycache__/configuration_doge.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/doge/__pycache__/configuration_doge.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..167ae43a83ede067005ecb94cb7370f48fdf9787
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/doge/__pycache__/configuration_doge.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/doge/__pycache__/modeling_doge.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/doge/__pycache__/modeling_doge.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b741e47716f10b5e1e358736f3cb0a219e3d5f35
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/doge/__pycache__/modeling_doge.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/doge/__pycache__/modular_doge.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/doge/__pycache__/modular_doge.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..35615ba54f842a3fc352fc22b99efbf1ea8cf55a
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/doge/__pycache__/modular_doge.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/doge/configuration_doge.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/doge/configuration_doge.py
new file mode 100644
index 0000000000000000000000000000000000000000..8518d9021458b170fc4773705a425a62eafee752
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/doge/configuration_doge.py
@@ -0,0 +1,110 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/doge/modular_doge.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_doge.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2025 Jingze Shi and the HuggingFace Inc. team. All rights reserved.
+#
+# The Doge family of small language models is trained by SmallDoge Team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...modeling_rope_utils import RopeParameters
+from ...utils import auto_docstring
+
+
+@auto_docstring(checkpoint="SmallDoge/Doge-320M")
+@strict
+class DogeConfig(PreTrainedConfig):
+ r"""
+ keep_window_size (`int`, *optional*, defaults to 2048):
+ The window size of tokens that are not dynamically masked, and dynamic masking is only performed when the sequence length exceeds this value.
+ is_moe (`bool`, *optional*, defaults to `False`):
+ Whether to use the Cross Domain Mixture of Experts, if `True`, the MoE will inherit the MLP to initialize.
+
+ ```python
+ >>> from transformers import DogeConfig, DogeModel
+
+ >>> # Initializing a Doge-320M style configuration
+ >>> configuration = DogeConfig()
+
+ >>> # Initializing a model from the Doge-320M style configuration
+ >>> model = DogeModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "doge"
+ keys_to_ignore_at_inference = ["past_key_values"]
+ # Default tensor parallel plan for base model `DogeModel`
+ base_model_tp_plan = {
+ "layers.*.self_attn.q_proj": "colwise",
+ "layers.*.self_attn.k_proj": "colwise",
+ "layers.*.self_attn.v_proj": "colwise",
+ "layers.*.self_attn.dt_proj": "rowwise",
+ "layers.*.self_attn.o_proj": "rowwise",
+ "layers.*.mlp.gate_proj": "colwise",
+ "layers.*.mlp.up_proj": "colwise",
+ "layers.*.mlp.down_proj": "rowwise",
+ "layers.*.mlp.router_gate": "colwise_gather_output",
+ "layers.*.mlp.down_embed": "rowwise_split_input",
+ "layers.*.mlp.up_embed": "rowwise_split_input",
+ }
+ base_model_pp_plan = {
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
+ "norm": (["hidden_states"], ["hidden_states"]),
+ }
+
+ vocab_size: int = 32768
+ hidden_size: int = 1024
+ intermediate_size: int = 2048
+ num_hidden_layers: int = 32
+ hidden_dropout: float | int = 0.0
+ hidden_act: str = "silu"
+ initializer_range: float = 0.02
+ rms_norm_eps: float = 1e-06
+ use_cache: bool = True
+ tie_word_embeddings: bool = False
+ max_position_embeddings: int = 2048
+ rope_parameters: RopeParameters | dict | None = None
+ num_attention_heads: int = 8
+ num_key_value_heads: int | None = None
+ attention_bias: bool = False
+ attention_dropout: float | None = 0.0
+ mlp_bias: bool = False
+ sliding_window: int | None = None
+ keep_window_size: int = 2048
+ is_moe: bool = False
+ num_experts: int = 16384
+ num_experts_per_tok: int = 64
+ norm_topk_prob: bool = False
+ output_router_logits: bool = False
+ router_aux_loss_coef: float = 0.001
+ pad_token_id: int | None = None
+ bos_token_id: int | None = None
+ eos_token_id: int | list[int] | None = None
+
+ def __post_init__(self, **kwargs):
+ # for backward compatibility
+ if self.num_key_value_heads is None:
+ self.num_key_value_heads = self.num_attention_heads
+
+ super().__post_init__(**kwargs)
+
+
+__all__ = ["DogeConfig"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/doge/modeling_doge.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/doge/modeling_doge.py
new file mode 100644
index 0000000000000000000000000000000000000000..4aad59b52a9af9c01e956da26b8ddae2c157e43e
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/doge/modeling_doge.py
@@ -0,0 +1,822 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/doge/modular_doge.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_doge.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2025 Jingze Shi and the HuggingFace Inc. team. All rights reserved.
+#
+# The Doge family of small language models is trained by SmallDoge Team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import math
+from collections.abc import Callable
+from typing import Optional, Union
+
+import torch
+import torch.nn.functional as F
+from torch import nn
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...cache_utils import Cache, DynamicCache
+from ...generation import GenerationMixin
+from ...integrations import use_kernel_forward_from_hub, use_kernel_func_from_hub
+from ...integrations.flex_attention import compile_friendly_flex_attention
+from ...masking_utils import create_causal_mask, create_sliding_window_causal_mask
+from ...modeling_layers import GenericForSequenceClassification, GradientCheckpointingLayer
+from ...modeling_outputs import MoeCausalLMOutputWithPast, MoeModelOutputWithPast
+from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
+from ...modeling_utils import AttentionInterface, PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, is_torch_flex_attn_available
+from ...utils.generic import maybe_autocast, merge_with_config_defaults
+from ...utils.output_capturing import OutputRecorder, capture_outputs
+from .configuration_doge import DogeConfig
+
+
+if is_torch_flex_attn_available():
+ from torch.nn.attention.flex_attention import BlockMask
+
+
+@use_kernel_forward_from_hub("RMSNorm")
+class DogeRMSNorm(nn.Module):
+ def __init__(self, hidden_size, eps: float = 1e-6) -> None:
+ """
+ DogeRMSNorm is equivalent to T5LayerNorm
+ """
+ super().__init__()
+ self.weight = nn.Parameter(torch.ones(hidden_size))
+ self.variance_epsilon = eps
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ input_dtype = hidden_states.dtype
+ hidden_states = hidden_states.to(torch.float32)
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
+ return self.weight * hidden_states.to(input_dtype)
+
+ def extra_repr(self):
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
+
+
+class DogeRotaryEmbedding(nn.Module):
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
+
+ def __init__(self, config: DogeConfig, device=None):
+ super().__init__()
+ self.max_seq_len_cached = config.max_position_embeddings
+ self.original_max_seq_len = config.max_position_embeddings
+
+ self.config = config
+
+ self.rope_type = self.config.rope_parameters["rope_type"]
+ rope_init_fn: Callable = self.compute_default_rope_parameters
+ if self.rope_type != "default":
+ rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
+ inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
+
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
+ self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
+
+ @staticmethod
+ def compute_default_rope_parameters(
+ config: DogeConfig | None = None,
+ device: Optional["torch.device"] = None,
+ seq_len: int | None = None,
+ ) -> tuple["torch.Tensor", float]:
+ """
+ Computes the inverse frequencies according to the original RoPE implementation
+ Args:
+ config ([`~transformers.PreTrainedConfig`]):
+ The model configuration.
+ device (`torch.device`):
+ The device to use for initialization of the inverse frequencies.
+ seq_len (`int`, *optional*):
+ The current sequence length. Unused for this type of RoPE.
+ Returns:
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
+ """
+ base = config.rope_parameters["rope_theta"]
+ dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
+
+ attention_factor = 1.0 # Unused in this type of RoPE
+
+ # Compute the inverse frequencies
+ inv_freq = 1.0 / (
+ base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
+ )
+ return inv_freq, attention_factor
+
+ @torch.no_grad()
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
+ def forward(self, x, position_ids):
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
+ position_ids_expanded = position_ids[:, None, :].float()
+
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
+ with maybe_autocast(device_type=device_type, enabled=False): # Force float32
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
+ emb = torch.cat((freqs, freqs), dim=-1)
+ cos = emb.cos() * self.attention_scaling
+ sin = emb.sin() * self.attention_scaling
+
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
+
+
+def rotate_half(x):
+ """Rotates half the hidden dims of the input."""
+ x1 = x[..., : x.shape[-1] // 2]
+ x2 = x[..., x.shape[-1] // 2 :]
+ return torch.cat((-x2, x1), dim=-1)
+
+
+@use_kernel_func_from_hub("rotary_pos_emb")
+def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
+ """Applies Rotary Position Embedding to the query and key tensors.
+
+ Args:
+ q (`torch.Tensor`): The query tensor.
+ k (`torch.Tensor`): The key tensor.
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
+ Returns:
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
+ """
+ cos = cos.unsqueeze(unsqueeze_dim)
+ sin = sin.unsqueeze(unsqueeze_dim)
+ q_embed = (q * cos) + (rotate_half(q) * sin)
+ k_embed = (k * cos) + (rotate_half(k) * sin)
+ return q_embed, k_embed
+
+
+def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
+ """
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
+ """
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
+ if n_rep == 1:
+ return hidden_states
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
+
+
+def eager_attention_forward(
+ module: nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: torch.Tensor | None,
+ scaling: float,
+ dropout: float = 0.0,
+ **kwargs: Unpack[TransformersKwargs],
+):
+ key_states = repeat_kv(key, module.num_key_value_groups)
+ value_states = repeat_kv(value, module.num_key_value_groups)
+
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
+ if attention_mask is not None:
+ attn_weights = attn_weights + attention_mask
+
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
+ attn_output = torch.matmul(attn_weights, value_states)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+
+ return attn_output, attn_weights
+
+
+def flex_attention_forward(
+ module: nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: Union[torch.Tensor, "BlockMask"],
+ scaling: float | None = None,
+ softcap: float | None = None,
+ **kwargs,
+) -> tuple[torch.Tensor, torch.Tensor]:
+ block_mask = None
+ causal_mask = None
+ if isinstance(attention_mask, BlockMask):
+ block_mask = attention_mask
+ else:
+ causal_mask = attention_mask
+
+ if causal_mask is not None:
+ causal_mask = causal_mask[:, :, :, : key.shape[-2]]
+
+ def score_mod(score, batch_idx, head_idx, q_idx, kv_idx):
+ if softcap is not None:
+ score = softcap * torch.tanh(score / softcap)
+ if causal_mask is not None:
+ score = score + causal_mask[batch_idx][head_idx][q_idx][kv_idx]
+ return score
+
+ attn_output, attention_weights = compile_friendly_flex_attention(
+ query,
+ key,
+ value,
+ score_mod=score_mod,
+ block_mask=block_mask,
+ enable_gqa=True,
+ scale=scaling,
+ # Last time checked on PyTorch == 2.5.1: Flex Attention always computes the lse regardless.
+ # For simplification, we thus always return it as no additional computations are introduced.
+ return_lse=True,
+ )
+ # lse is returned in float32
+ attention_weights = attention_weights.to(value.dtype)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+
+ return attn_output, attention_weights
+
+
+ALL_ATTENTION_FUNCTIONS = AttentionInterface()
+ALL_ATTENTION_FUNCTIONS["doge_flex_attention"] = flex_attention_forward
+
+
+class DogeAttention(nn.Module):
+ def __init__(self, config: DogeConfig, layer_idx: int | None = None):
+ super().__init__()
+ self.config = config
+ self.layer_idx = layer_idx
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
+ self.scaling = self.head_dim**-0.5
+ self.attention_dropout = config.attention_dropout
+ self.keep_window_size = config.keep_window_size
+
+ self.q_proj = nn.Linear(
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
+ )
+ self.k_proj = nn.Linear(
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
+ )
+ self.v_proj = nn.Linear(
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
+ )
+ # dynamic mask for the QK^T attention weights matrix
+ self.A = nn.Parameter(torch.zeros(config.num_key_value_heads))
+ self.dt_proj = nn.Linear(
+ config.num_key_value_heads * self.head_dim, config.num_key_value_heads, bias=config.attention_bias
+ )
+ self.o_proj = nn.Linear(
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
+ )
+ self.q_norm = DogeRMSNorm(self.head_dim, eps=config.rms_norm_eps)
+ self.k_norm = DogeRMSNorm(self.head_dim, eps=config.rms_norm_eps)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
+ attention_mask: torch.Tensor | None = None,
+ past_key_values: Cache | None = None,
+ **kwargs,
+ ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
+ input_shape = hidden_states.shape[:-1]
+ hidden_shape = (*input_shape, -1, self.head_dim)
+
+ query_states = self.q_norm(self.q_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
+ key_states = self.k_norm(self.k_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+
+ cos, sin = position_embeddings
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
+
+ if past_key_values is not None:
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
+
+ # calculate dynamic mask from value_states
+ dt_states = self.dt_proj(
+ value_states.transpose(1, 2).reshape(value_states.shape[0], value_states.shape[-2], -1)
+ )
+ dt_states = torch.exp(self.A * F.softplus(dt_states)).transpose(-1, -2)
+ attn_mask = self.prepare_dynamic_mask(
+ hidden_states=hidden_states,
+ dt_states=dt_states,
+ keep_window_size=self.keep_window_size,
+ attention_mask=attention_mask,
+ )
+ attn_mask = repeat_kv(attn_mask, self.num_key_value_groups)
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_states,
+ key_states,
+ value_states,
+ attention_mask=attn_mask,
+ dropout=0.0 if not self.training else self.attention_dropout,
+ scaling=self.scaling,
+ **kwargs,
+ )
+
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ attn_output = self.o_proj(attn_output)
+ return attn_output, attn_weights
+
+ def prepare_dynamic_mask(
+ self,
+ hidden_states: torch.Tensor,
+ dt_states: torch.Tensor,
+ keep_window_size: int = 2048,
+ attention_mask: torch.Tensor | None = None,
+ ):
+ """
+ The core idea of DMA is to calculate the dynamic attention mask to mask the tokens that should be masked, so as to form sparse attention.
+
+ Combine `dt_states` with `attention_mask` to generate the final `attn_mask`.
+
+ Args:
+ hidden_states (`torch.Tensor`): The input hidden_states, used to determine the minimum value of the current input precision.
+ dt_states (`torch.Tensor`): dt_states of shape `(batch_size, num_heads, key_sequence_length)`.
+ keep_window_size (`int`): The window size of tokens that are not dynamically masked, and dynamic masking is only performed when the sequence length exceeds this value.
+ attention_mask (`torch.Tensor`, *optional*): attention mask of shape `(batch_size, 1, query_sequence_length, key_sequence_length)`.
+ """
+ min_dtype = torch.finfo(hidden_states.dtype).min
+ dtype = hidden_states.dtype
+ attn_mask = dt_states[:, :, None, :].expand(
+ -1, -1, hidden_states.shape[1], -1
+ ) # [batch_size, num_heads, query_len, key_len]
+ if attention_mask is not None and not isinstance(attention_mask, BlockMask):
+ if attention_mask.dtype == torch.bool:
+ dtype = hidden_states.dtype
+ attention_mask = torch.where(
+ attention_mask, torch.tensor(0.0, device=attention_mask.device, dtype=dtype), min_dtype
+ )
+ attn_mask = attn_mask.masked_fill(attention_mask[:, :, :, : attn_mask.shape[-1]] != 0, min_dtype)
+ if attn_mask.shape[-1] > keep_window_size:
+ active_mask = torch.zeros_like(attn_mask, dtype=dtype, device=attn_mask.device)
+ topk_indices = torch.topk(attn_mask, keep_window_size, dim=-1, largest=True, sorted=False).indices
+ active_mask = active_mask.scatter(-1, topk_indices, 1.0)
+ attn_mask = attn_mask.masked_fill(active_mask == 0.0, min_dtype)
+ return attn_mask
+
+
+class DogeMLP(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.hidden_size = config.hidden_size
+ self.intermediate_size = config.intermediate_size
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
+ self.act_fn = ACT2FN[config.hidden_act]
+
+ def forward(self, x):
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
+ return down_proj
+
+
+class DogeCDMoE(nn.Module):
+ def __init__(self, config: DogeConfig):
+ super().__init__()
+ self.hidden_size = config.hidden_size
+ self.intermediate_size = config.intermediate_size
+ self.act_fn = ACT2FN[config.hidden_act]
+
+ self.num_experts = config.num_experts
+ self.num_keys = math.floor(math.sqrt(self.num_experts))
+ self.top_k = config.num_experts_per_tok
+ self.norm_topk_prob = config.norm_topk_prob
+
+ # shared expert
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
+
+ # router gate for retrieval experts
+ self.router_gate = nn.Linear(self.hidden_size, self.num_keys * 2, bias=False)
+
+ # routed experts
+ self.down_embed = nn.Embedding(self.num_experts, self.hidden_size)
+ self.up_embed = nn.Embedding(self.num_experts, self.hidden_size)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ **kwargs,
+ ) -> torch.Tensor:
+ bsz, seq_len, _ = hidden_states.shape
+
+ # get routing logits with router gate
+ router_logits = self.router_gate(hidden_states).view(2, bsz * seq_len, -1)
+
+ # get experts with the highest routing logits
+ (scores_x, scores_y), (indices_x, indices_y) = router_logits.topk(self.num_keys, dim=-1)
+ all_scores = scores_x.unsqueeze(-1) + scores_y.unsqueeze(-2)
+ all_indices = indices_x.unsqueeze(-1) * self.num_keys + indices_y.unsqueeze(-2)
+ all_scores = all_scores.view(*all_scores.shape[:-2], -1)
+ all_indices = all_indices.view(*all_indices.shape[:-2], -1)
+ scores, position_indices = all_scores.topk(self.top_k, dim=-1)
+ indices = all_indices.gather(-1, position_indices)
+ routing_weights = F.softmax(scores, dim=-1)
+ if self.norm_topk_prob:
+ routing_weights /= routing_weights.sum(dim=-1, keepdim=True)
+
+ # mix routed experts states with shared expert states
+ down_embed = self.down_embed(indices)
+ up_embed = self.up_embed(indices)
+ experts_weights = torch.matmul(down_embed, hidden_states.view(bsz * seq_len, -1, 1)).view(bsz * seq_len, -1)
+ experts_weights = self.act_fn(experts_weights) * routing_weights
+ experts_states = torch.matmul(experts_weights.view(bsz * seq_len, 1, -1), up_embed).view(bsz, seq_len, -1)
+ hidden_states = self.down_proj(self.act_fn(self.gate_proj(hidden_states)) * self.up_proj(hidden_states))
+ hidden_states = hidden_states + experts_states
+ return hidden_states, router_logits
+
+
+class DogeDecoderLayer(GradientCheckpointingLayer):
+ def __init__(self, config: DogeConfig, layer_idx: int | None = None):
+ super().__init__()
+ self.hidden_dropout = config.hidden_dropout
+
+ self.input_layernorm = DogeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.self_attn = DogeAttention(config=config, layer_idx=layer_idx)
+ self.input_residual = nn.Parameter(torch.ones(config.hidden_size))
+
+ self.post_attention_layernorm = DogeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.mlp = DogeMLP(config) if not config.is_moe else DogeCDMoE(config)
+ self.post_attention_residual = nn.Parameter(torch.ones(config.hidden_size))
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ use_cache: bool | None = False,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.FloatTensor, tuple[torch.FloatTensor, torch.FloatTensor] | None]:
+ # sequence transformation
+ residual = hidden_states
+ hidden_states = self.input_layernorm(hidden_states)
+ hidden_states, self_attn_weights = self.self_attn(
+ hidden_states=hidden_states,
+ position_embeddings=position_embeddings,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ **kwargs,
+ )
+ hidden_states = F.dropout(hidden_states, p=self.hidden_dropout, training=self.training)
+ hidden_states = self.input_residual * residual + hidden_states
+
+ # state transformation
+ residual = hidden_states
+ hidden_states = self.post_attention_layernorm(hidden_states)
+ hidden_states = self.mlp(hidden_states)
+ hidden_states = F.dropout(hidden_states, p=self.hidden_dropout, training=self.training)
+ hidden_states = self.post_attention_residual * residual + hidden_states
+
+ return hidden_states
+
+
+@auto_docstring
+class DogePreTrainedModel(PreTrainedModel):
+ config: DogeConfig
+ base_model_prefix = "model"
+ supports_gradient_checkpointing = True
+ _no_split_modules = ["DogeDecoderLayer"]
+ _skip_keys_device_placement = ["past_key_values"]
+ _supports_flash_attn = False
+ _supports_sdpa = True
+ _supports_flex_attn = True
+ _can_compile_fullgraph = False
+ _supports_attention_backend = True
+ _can_record_outputs = {
+ "router_logits": OutputRecorder(DogeCDMoE, index=1),
+ "hidden_states": DogeDecoderLayer,
+ "attentions": DogeAttention,
+ }
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ """Initialize the weights"""
+ super()._init_weights(module)
+ if isinstance(module, DogeAttention):
+ if hasattr(module, "A"):
+ init.zeros_(module.A)
+ elif isinstance(module, DogeDecoderLayer):
+ if hasattr(module, "input_residual"):
+ init.ones_(module.input_residual)
+ if hasattr(module, "post_attention_residual"):
+ init.ones_(module.post_attention_residual)
+
+
+@auto_docstring
+class DogeModel(DogePreTrainedModel):
+ def __init__(self, config: DogeConfig):
+ super().__init__(config)
+ self.padding_idx = config.pad_token_id
+ self.vocab_size = config.vocab_size
+
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
+ self.layers = nn.ModuleList(
+ [DogeDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
+ )
+ self.norm = DogeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.rotary_emb = DogeRotaryEmbedding(config=config)
+ self.gradient_checkpointing = False
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @merge_with_config_defaults
+ @capture_outputs
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ use_cache: bool | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> MoeModelOutputWithPast:
+ if (input_ids is None) ^ (inputs_embeds is not None):
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
+
+ if use_cache and past_key_values is None:
+ past_key_values = DynamicCache(config=self.config)
+
+ if inputs_embeds is None:
+ inputs_embeds = self.embed_tokens(input_ids)
+
+ if position_ids is None:
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
+ position_ids = position_ids.unsqueeze(0)
+
+ mask_function = create_causal_mask if self.config.sliding_window is None else create_sliding_window_causal_mask
+ causal_mask = mask_function(
+ config=self.config,
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ position_ids=position_ids,
+ )
+
+ hidden_states = inputs_embeds
+ position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
+
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
+ hidden_states = decoder_layer(
+ hidden_states,
+ attention_mask=causal_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ position_embeddings=position_embeddings,
+ **kwargs,
+ )
+
+ hidden_states = self.norm(hidden_states)
+
+ return MoeModelOutputWithPast( # only diff with Mistral is the output type, we need MoE
+ last_hidden_state=hidden_states,
+ past_key_values=past_key_values,
+ )
+
+
+def load_balancing_loss_func(
+ gate_logits: torch.Tensor | tuple[torch.Tensor] | None,
+ num_experts: int | None = None,
+ num_keys: int | None = None,
+ top_k: int = 2,
+ attention_mask: torch.Tensor | None = None,
+) -> torch.Tensor | int:
+ r"""
+ Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
+
+ See Switch Transformer (https://huggingface.co/papers/2101.03961) for more details. This function implements the loss
+ function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
+ experts is too unbalanced.
+
+ Args:
+ gate_logits:
+ Logits from the `router_gate`, should be a tuple of model.config.num_hidden_layers tensors of
+ shape [2, batch_size * sequence_length, num_keys].
+ num_experts:
+ Number of experts
+ num_keys:
+ Number of keys
+ top_k:
+ The number of experts to route per-token, can be also interpreted as the `top-k` routing
+ parameter.
+ attention_mask (`torch.Tensor`, *optional*):
+ The attention_mask used in forward function
+ shape [batch_size X sequence_length] if not None.
+
+ Returns:
+ The auxiliary loss.
+ """
+ if gate_logits is None or not isinstance(gate_logits, tuple):
+ return 0
+
+ compute_dtype = gate_logits[0].dtype
+ compute_device = gate_logits[0].device
+ all_expert_indices = []
+ all_routing_weights = []
+
+ for layer_gate_logits in gate_logits:
+ layer_gate_logits = layer_gate_logits.to(compute_device)
+
+ (scores_x, scores_y), (indices_x, indices_y) = layer_gate_logits.topk(num_keys, dim=-1)
+
+ all_scores = scores_x.unsqueeze(-1) + scores_y.unsqueeze(-2)
+ all_indices = indices_x.unsqueeze(-1) * num_keys + indices_y.unsqueeze(-2)
+ all_scores = all_scores.view(*all_scores.shape[:-2], -1)
+ all_indices = all_indices.view(*all_indices.shape[:-2], -1)
+
+ _, position_indices = all_scores.topk(top_k, dim=-1)
+ expert_indices = all_indices.gather(-1, position_indices)
+
+ routing_weights = F.softmax(all_scores, dim=-1)
+
+ all_expert_indices.append(expert_indices)
+ all_routing_weights.append(routing_weights)
+ all_expert_indices = torch.cat(all_expert_indices, dim=0)
+ all_routing_weights = torch.cat(all_routing_weights, dim=0)
+
+ if attention_mask is None:
+ # Compute the percentage of tokens routed to each experts
+ all_expert_indices = all_expert_indices.view(-1)
+ tokens_per_expert = torch.zeros(num_experts, dtype=compute_dtype, device=compute_device)
+ pad = torch.ones_like(all_expert_indices, dtype=compute_dtype, device=compute_device)
+ tokens_per_expert = tokens_per_expert.scatter_add_(0, all_expert_indices, pad) / all_expert_indices.shape[0]
+
+ # Compute the average probability of routing to these experts
+ router_prob_per_expert = torch.mean(all_routing_weights, dim=0)
+ else:
+ batch_size, sequence_length = attention_mask.shape
+ num_hidden_layers = len(gate_logits)
+
+ # Compute the mask that masks all padding tokens as 0 with the same shape of expert_mask
+ expert_attention_mask = (
+ attention_mask[None, :, :, None]
+ .expand((num_hidden_layers, batch_size, sequence_length, top_k))
+ .reshape(-1)
+ .to(compute_device)
+ )
+ all_expert_indices = all_expert_indices.view(-1)[expert_attention_mask.bool()]
+
+ # Compute the percentage of tokens routed to each experts
+ tokens_per_expert = torch.zeros(num_experts, dtype=compute_dtype, device=compute_device)
+ pad = torch.ones_like(all_expert_indices, dtype=compute_dtype, device=compute_device)
+ tokens_per_expert = tokens_per_expert.scatter_add_(0, all_expert_indices, pad) / torch.sum(
+ expert_attention_mask
+ )
+
+ # Compute the mask that masks all padding tokens as 0 with the same shape of tokens_per_expert
+ router_per_expert_attention_mask = (
+ attention_mask[None, :, :, None]
+ .expand((num_hidden_layers, batch_size, sequence_length, num_experts))
+ .reshape(-1, num_experts)
+ .to(compute_device)
+ )
+
+ # Compute the average probability of routing to these experts
+ router_prob_per_expert = torch.sum(all_routing_weights * router_per_expert_attention_mask, dim=0) / torch.sum(
+ router_per_expert_attention_mask, dim=0
+ )
+
+ overall_loss = torch.sum(tokens_per_expert * router_prob_per_expert)
+ return overall_loss * num_experts
+
+
+@auto_docstring
+class DogeForCausalLM(DogePreTrainedModel, GenerationMixin):
+ _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
+ _tp_plan = {"lm_head": "colwise_gather_output"}
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
+
+ def __init__(self, config):
+ super().__init__(config)
+ self.model = DogeModel(config)
+ self.vocab_size = config.vocab_size
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
+ self.router_aux_loss_coef = config.router_aux_loss_coef
+ self.num_experts = config.num_experts
+ self.num_experts_per_tok = config.num_experts_per_tok
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ use_cache: bool | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ output_router_logits: bool | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> MoeCausalLMOutputWithPast:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
+
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, DogeForCausalLM
+
+ >>> model = DogeForCausalLM.from_pretrained("SmallDoge/Doge-320M")
+ >>> tokenizer = AutoTokenizer.from_pretrained("SmallDoge/Doge-320M")
+
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
+
+ >>> # Generate
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
+ ```"""
+ output_router_logits = (
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
+ )
+
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
+ outputs: MoeModelOutputWithPast = self.model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ **kwargs,
+ )
+
+ hidden_states = outputs.last_hidden_state
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
+
+ aux_loss = None
+ if output_router_logits:
+ aux_loss = load_balancing_loss_func(
+ outputs.router_logits,
+ self.num_experts,
+ math.floor(math.sqrt(self.num_experts)),
+ self.num_experts_per_tok,
+ attention_mask,
+ )
+ if labels is not None:
+ loss += self.router_aux_loss_coef * aux_loss.to(loss.device) # make sure to reside in the same device
+
+ return MoeCausalLMOutputWithPast(
+ loss=loss,
+ aux_loss=aux_loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ router_logits=outputs.router_logits,
+ )
+
+
+class DogeForSequenceClassification(GenericForSequenceClassification, DogePreTrainedModel):
+ pass
+
+
+__all__ = ["DogeForCausalLM", "DogeModel", "DogePreTrainedModel", "DogeForSequenceClassification"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/doge/modular_doge.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/doge/modular_doge.py
new file mode 100644
index 0000000000000000000000000000000000000000..8b78126c0a001f23b6e252eaa76356f89c5f7009
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/doge/modular_doge.py
@@ -0,0 +1,659 @@
+# Copyright 2025 Jingze Shi and the HuggingFace Inc. team. All rights reserved.
+#
+# The Doge family of small language models is trained by SmallDoge Team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch Doge model."""
+
+import math
+from collections.abc import Callable
+from typing import Union
+
+import torch
+import torch.nn.functional as F
+from huggingface_hub.dataclasses import strict
+from torch import nn
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...cache_utils import Cache
+from ...configuration_utils import PreTrainedConfig
+from ...integrations.flex_attention import compile_friendly_flex_attention
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import MoeCausalLMOutputWithPast, MoeModelOutputWithPast
+from ...modeling_rope_utils import RopeParameters
+from ...modeling_utils import AttentionInterface, PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import TransformersKwargs, auto_docstring, is_torch_flex_attn_available, logging
+from ...utils.output_capturing import OutputRecorder
+from ..llama.modeling_llama import (
+ LlamaForSequenceClassification,
+ LlamaMLP,
+ LlamaPreTrainedModel,
+ LlamaRMSNorm,
+ LlamaRotaryEmbedding,
+ apply_rotary_pos_emb,
+ eager_attention_forward,
+ repeat_kv,
+)
+from ..mixtral.modeling_mixtral import MixtralForCausalLM, MixtralModel
+
+
+logger = logging.get_logger(__name__)
+
+if is_torch_flex_attn_available():
+ from torch.nn.attention.flex_attention import BlockMask
+
+
+@auto_docstring(checkpoint="SmallDoge/Doge-320M")
+@strict
+class DogeConfig(PreTrainedConfig):
+ r"""
+ keep_window_size (`int`, *optional*, defaults to 2048):
+ The window size of tokens that are not dynamically masked, and dynamic masking is only performed when the sequence length exceeds this value.
+ is_moe (`bool`, *optional*, defaults to `False`):
+ Whether to use the Cross Domain Mixture of Experts, if `True`, the MoE will inherit the MLP to initialize.
+
+ ```python
+ >>> from transformers import DogeConfig, DogeModel
+
+ >>> # Initializing a Doge-320M style configuration
+ >>> configuration = DogeConfig()
+
+ >>> # Initializing a model from the Doge-320M style configuration
+ >>> model = DogeModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "doge"
+ keys_to_ignore_at_inference = ["past_key_values"]
+ # Default tensor parallel plan for base model `DogeModel`
+ base_model_tp_plan = {
+ "layers.*.self_attn.q_proj": "colwise",
+ "layers.*.self_attn.k_proj": "colwise",
+ "layers.*.self_attn.v_proj": "colwise",
+ "layers.*.self_attn.dt_proj": "rowwise",
+ "layers.*.self_attn.o_proj": "rowwise",
+ "layers.*.mlp.gate_proj": "colwise",
+ "layers.*.mlp.up_proj": "colwise",
+ "layers.*.mlp.down_proj": "rowwise",
+ "layers.*.mlp.router_gate": "colwise_gather_output",
+ "layers.*.mlp.down_embed": "rowwise_split_input",
+ "layers.*.mlp.up_embed": "rowwise_split_input",
+ }
+ base_model_pp_plan = {
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
+ "norm": (["hidden_states"], ["hidden_states"]),
+ }
+
+ vocab_size: int = 32768
+ hidden_size: int = 1024
+ intermediate_size: int = 2048
+ num_hidden_layers: int = 32
+ hidden_dropout: float | int = 0.0
+ hidden_act: str = "silu"
+ initializer_range: float = 0.02
+ rms_norm_eps: float = 1e-06
+ use_cache: bool = True
+ tie_word_embeddings: bool = False
+ max_position_embeddings: int = 2048
+ rope_parameters: RopeParameters | dict | None = None
+ num_attention_heads: int = 8
+ num_key_value_heads: int | None = None
+ attention_bias: bool = False
+ attention_dropout: float | None = 0.0
+ mlp_bias: bool = False
+ sliding_window: int | None = None
+ keep_window_size: int = 2048
+ is_moe: bool = False
+ num_experts: int = 16384
+ num_experts_per_tok: int = 64
+ norm_topk_prob: bool = False
+ output_router_logits: bool = False
+ router_aux_loss_coef: float = 0.001
+ pad_token_id: int | None = None
+ bos_token_id: int | None = None
+ eos_token_id: int | list[int] | None = None
+
+ def __post_init__(self, **kwargs):
+ # for backward compatibility
+ if self.num_key_value_heads is None:
+ self.num_key_value_heads = self.num_attention_heads
+
+ super().__post_init__(**kwargs)
+
+
+class DogeRMSNorm(LlamaRMSNorm):
+ pass
+
+
+class DogeRotaryEmbedding(LlamaRotaryEmbedding):
+ pass
+
+
+def flex_attention_forward(
+ module: nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: Union[torch.Tensor, "BlockMask"],
+ scaling: float | None = None,
+ softcap: float | None = None,
+ **kwargs,
+) -> tuple[torch.Tensor, torch.Tensor]:
+ block_mask = None
+ causal_mask = None
+ if isinstance(attention_mask, BlockMask):
+ block_mask = attention_mask
+ else:
+ causal_mask = attention_mask
+
+ if causal_mask is not None:
+ causal_mask = causal_mask[:, :, :, : key.shape[-2]]
+
+ def score_mod(score, batch_idx, head_idx, q_idx, kv_idx):
+ if softcap is not None:
+ score = softcap * torch.tanh(score / softcap)
+ if causal_mask is not None:
+ score = score + causal_mask[batch_idx][head_idx][q_idx][kv_idx]
+ return score
+
+ attn_output, attention_weights = compile_friendly_flex_attention(
+ query,
+ key,
+ value,
+ score_mod=score_mod,
+ block_mask=block_mask,
+ enable_gqa=True,
+ scale=scaling,
+ # Last time checked on PyTorch == 2.5.1: Flex Attention always computes the lse regardless.
+ # For simplification, we thus always return it as no additional computations are introduced.
+ return_lse=True,
+ )
+ # lse is returned in float32
+ attention_weights = attention_weights.to(value.dtype)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+
+ return attn_output, attention_weights
+
+
+ALL_ATTENTION_FUNCTIONS = AttentionInterface()
+ALL_ATTENTION_FUNCTIONS["doge_flex_attention"] = flex_attention_forward
+
+
+class DogeAttention(nn.Module):
+ def __init__(self, config: DogeConfig, layer_idx: int | None = None):
+ super().__init__()
+ self.config = config
+ self.layer_idx = layer_idx
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
+ self.scaling = self.head_dim**-0.5
+ self.attention_dropout = config.attention_dropout
+ self.keep_window_size = config.keep_window_size
+
+ self.q_proj = nn.Linear(
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
+ )
+ self.k_proj = nn.Linear(
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
+ )
+ self.v_proj = nn.Linear(
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
+ )
+ # dynamic mask for the QK^T attention weights matrix
+ self.A = nn.Parameter(torch.zeros(config.num_key_value_heads))
+ self.dt_proj = nn.Linear(
+ config.num_key_value_heads * self.head_dim, config.num_key_value_heads, bias=config.attention_bias
+ )
+ self.o_proj = nn.Linear(
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
+ )
+ self.q_norm = DogeRMSNorm(self.head_dim, eps=config.rms_norm_eps)
+ self.k_norm = DogeRMSNorm(self.head_dim, eps=config.rms_norm_eps)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
+ attention_mask: torch.Tensor | None = None,
+ past_key_values: Cache | None = None,
+ **kwargs,
+ ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
+ input_shape = hidden_states.shape[:-1]
+ hidden_shape = (*input_shape, -1, self.head_dim)
+
+ query_states = self.q_norm(self.q_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
+ key_states = self.k_norm(self.k_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+
+ cos, sin = position_embeddings
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
+
+ if past_key_values is not None:
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
+
+ # calculate dynamic mask from value_states
+ dt_states = self.dt_proj(
+ value_states.transpose(1, 2).reshape(value_states.shape[0], value_states.shape[-2], -1)
+ )
+ dt_states = torch.exp(self.A * F.softplus(dt_states)).transpose(-1, -2)
+ attn_mask = self.prepare_dynamic_mask(
+ hidden_states=hidden_states,
+ dt_states=dt_states,
+ keep_window_size=self.keep_window_size,
+ attention_mask=attention_mask,
+ )
+ attn_mask = repeat_kv(attn_mask, self.num_key_value_groups)
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_states,
+ key_states,
+ value_states,
+ attention_mask=attn_mask,
+ dropout=0.0 if not self.training else self.attention_dropout,
+ scaling=self.scaling,
+ **kwargs,
+ )
+
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ attn_output = self.o_proj(attn_output)
+ return attn_output, attn_weights
+
+ def prepare_dynamic_mask(
+ self,
+ hidden_states: torch.Tensor,
+ dt_states: torch.Tensor,
+ keep_window_size: int = 2048,
+ attention_mask: torch.Tensor | None = None,
+ ):
+ """
+ The core idea of DMA is to calculate the dynamic attention mask to mask the tokens that should be masked, so as to form sparse attention.
+
+ Combine `dt_states` with `attention_mask` to generate the final `attn_mask`.
+
+ Args:
+ hidden_states (`torch.Tensor`): The input hidden_states, used to determine the minimum value of the current input precision.
+ dt_states (`torch.Tensor`): dt_states of shape `(batch_size, num_heads, key_sequence_length)`.
+ keep_window_size (`int`): The window size of tokens that are not dynamically masked, and dynamic masking is only performed when the sequence length exceeds this value.
+ attention_mask (`torch.Tensor`, *optional*): attention mask of shape `(batch_size, 1, query_sequence_length, key_sequence_length)`.
+ """
+ min_dtype = torch.finfo(hidden_states.dtype).min
+ dtype = hidden_states.dtype
+ attn_mask = dt_states[:, :, None, :].expand(
+ -1, -1, hidden_states.shape[1], -1
+ ) # [batch_size, num_heads, query_len, key_len]
+ if attention_mask is not None and not isinstance(attention_mask, BlockMask):
+ if attention_mask.dtype == torch.bool:
+ dtype = hidden_states.dtype
+ attention_mask = torch.where(
+ attention_mask, torch.tensor(0.0, device=attention_mask.device, dtype=dtype), min_dtype
+ )
+ attn_mask = attn_mask.masked_fill(attention_mask[:, :, :, : attn_mask.shape[-1]] != 0, min_dtype)
+ if attn_mask.shape[-1] > keep_window_size:
+ active_mask = torch.zeros_like(attn_mask, dtype=dtype, device=attn_mask.device)
+ topk_indices = torch.topk(attn_mask, keep_window_size, dim=-1, largest=True, sorted=False).indices
+ active_mask = active_mask.scatter(-1, topk_indices, 1.0)
+ attn_mask = attn_mask.masked_fill(active_mask == 0.0, min_dtype)
+ return attn_mask
+
+
+class DogeMLP(LlamaMLP):
+ pass
+
+
+class DogeCDMoE(nn.Module):
+ def __init__(self, config: DogeConfig):
+ super().__init__()
+ self.hidden_size = config.hidden_size
+ self.intermediate_size = config.intermediate_size
+ self.act_fn = ACT2FN[config.hidden_act]
+
+ self.num_experts = config.num_experts
+ self.num_keys = math.floor(math.sqrt(self.num_experts))
+ self.top_k = config.num_experts_per_tok
+ self.norm_topk_prob = config.norm_topk_prob
+
+ # shared expert
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
+
+ # router gate for retrieval experts
+ self.router_gate = nn.Linear(self.hidden_size, self.num_keys * 2, bias=False)
+
+ # routed experts
+ self.down_embed = nn.Embedding(self.num_experts, self.hidden_size)
+ self.up_embed = nn.Embedding(self.num_experts, self.hidden_size)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ **kwargs,
+ ) -> torch.Tensor:
+ bsz, seq_len, _ = hidden_states.shape
+
+ # get routing logits with router gate
+ router_logits = self.router_gate(hidden_states).view(2, bsz * seq_len, -1)
+
+ # get experts with the highest routing logits
+ (scores_x, scores_y), (indices_x, indices_y) = router_logits.topk(self.num_keys, dim=-1)
+ all_scores = scores_x.unsqueeze(-1) + scores_y.unsqueeze(-2)
+ all_indices = indices_x.unsqueeze(-1) * self.num_keys + indices_y.unsqueeze(-2)
+ all_scores = all_scores.view(*all_scores.shape[:-2], -1)
+ all_indices = all_indices.view(*all_indices.shape[:-2], -1)
+ scores, position_indices = all_scores.topk(self.top_k, dim=-1)
+ indices = all_indices.gather(-1, position_indices)
+ routing_weights = F.softmax(scores, dim=-1)
+ if self.norm_topk_prob:
+ routing_weights /= routing_weights.sum(dim=-1, keepdim=True)
+
+ # mix routed experts states with shared expert states
+ down_embed = self.down_embed(indices)
+ up_embed = self.up_embed(indices)
+ experts_weights = torch.matmul(down_embed, hidden_states.view(bsz * seq_len, -1, 1)).view(bsz * seq_len, -1)
+ experts_weights = self.act_fn(experts_weights) * routing_weights
+ experts_states = torch.matmul(experts_weights.view(bsz * seq_len, 1, -1), up_embed).view(bsz, seq_len, -1)
+ hidden_states = self.down_proj(self.act_fn(self.gate_proj(hidden_states)) * self.up_proj(hidden_states))
+ hidden_states = hidden_states + experts_states
+ return hidden_states, router_logits
+
+
+class DogeDecoderLayer(GradientCheckpointingLayer):
+ def __init__(self, config: DogeConfig, layer_idx: int | None = None):
+ super().__init__()
+ self.hidden_dropout = config.hidden_dropout
+
+ self.input_layernorm = DogeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.self_attn = DogeAttention(config=config, layer_idx=layer_idx)
+ self.input_residual = nn.Parameter(torch.ones(config.hidden_size))
+
+ self.post_attention_layernorm = DogeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.mlp = DogeMLP(config) if not config.is_moe else DogeCDMoE(config)
+ self.post_attention_residual = nn.Parameter(torch.ones(config.hidden_size))
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ use_cache: bool | None = False,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.FloatTensor, tuple[torch.FloatTensor, torch.FloatTensor] | None]:
+ # sequence transformation
+ residual = hidden_states
+ hidden_states = self.input_layernorm(hidden_states)
+ hidden_states, self_attn_weights = self.self_attn(
+ hidden_states=hidden_states,
+ position_embeddings=position_embeddings,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ **kwargs,
+ )
+ hidden_states = F.dropout(hidden_states, p=self.hidden_dropout, training=self.training)
+ hidden_states = self.input_residual * residual + hidden_states
+
+ # state transformation
+ residual = hidden_states
+ hidden_states = self.post_attention_layernorm(hidden_states)
+ hidden_states = self.mlp(hidden_states)
+ hidden_states = F.dropout(hidden_states, p=self.hidden_dropout, training=self.training)
+ hidden_states = self.post_attention_residual * residual + hidden_states
+
+ return hidden_states
+
+
+class DogePreTrainedModel(LlamaPreTrainedModel):
+ _supports_flash_attn = False
+ _can_compile_fullgraph = False
+ _can_record_outputs = {
+ "router_logits": OutputRecorder(DogeCDMoE, index=1),
+ "hidden_states": DogeDecoderLayer,
+ "attentions": DogeAttention,
+ }
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ """Initialize the weights"""
+ PreTrainedModel._init_weights(self, module)
+ if isinstance(module, DogeAttention):
+ if hasattr(module, "A"):
+ init.zeros_(module.A)
+ elif isinstance(module, DogeDecoderLayer):
+ if hasattr(module, "input_residual"):
+ init.ones_(module.input_residual)
+ if hasattr(module, "post_attention_residual"):
+ init.ones_(module.post_attention_residual)
+
+
+class DogeModel(MixtralModel):
+ pass
+
+
+def load_balancing_loss_func(
+ gate_logits: torch.Tensor | tuple[torch.Tensor] | None,
+ num_experts: int | None = None,
+ num_keys: int | None = None,
+ top_k: int = 2,
+ attention_mask: torch.Tensor | None = None,
+) -> torch.Tensor | int:
+ r"""
+ Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
+
+ See Switch Transformer (https://huggingface.co/papers/2101.03961) for more details. This function implements the loss
+ function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
+ experts is too unbalanced.
+
+ Args:
+ gate_logits:
+ Logits from the `router_gate`, should be a tuple of model.config.num_hidden_layers tensors of
+ shape [2, batch_size * sequence_length, num_keys].
+ num_experts:
+ Number of experts
+ num_keys:
+ Number of keys
+ top_k:
+ The number of experts to route per-token, can be also interpreted as the `top-k` routing
+ parameter.
+ attention_mask (`torch.Tensor`, *optional*):
+ The attention_mask used in forward function
+ shape [batch_size X sequence_length] if not None.
+
+ Returns:
+ The auxiliary loss.
+ """
+ if gate_logits is None or not isinstance(gate_logits, tuple):
+ return 0
+
+ compute_dtype = gate_logits[0].dtype
+ compute_device = gate_logits[0].device
+ all_expert_indices = []
+ all_routing_weights = []
+
+ for layer_gate_logits in gate_logits:
+ layer_gate_logits = layer_gate_logits.to(compute_device)
+
+ (scores_x, scores_y), (indices_x, indices_y) = layer_gate_logits.topk(num_keys, dim=-1)
+
+ all_scores = scores_x.unsqueeze(-1) + scores_y.unsqueeze(-2)
+ all_indices = indices_x.unsqueeze(-1) * num_keys + indices_y.unsqueeze(-2)
+ all_scores = all_scores.view(*all_scores.shape[:-2], -1)
+ all_indices = all_indices.view(*all_indices.shape[:-2], -1)
+
+ _, position_indices = all_scores.topk(top_k, dim=-1)
+ expert_indices = all_indices.gather(-1, position_indices)
+
+ routing_weights = F.softmax(all_scores, dim=-1)
+
+ all_expert_indices.append(expert_indices)
+ all_routing_weights.append(routing_weights)
+ all_expert_indices = torch.cat(all_expert_indices, dim=0)
+ all_routing_weights = torch.cat(all_routing_weights, dim=0)
+
+ if attention_mask is None:
+ # Compute the percentage of tokens routed to each experts
+ all_expert_indices = all_expert_indices.view(-1)
+ tokens_per_expert = torch.zeros(num_experts, dtype=compute_dtype, device=compute_device)
+ pad = torch.ones_like(all_expert_indices, dtype=compute_dtype, device=compute_device)
+ tokens_per_expert = tokens_per_expert.scatter_add_(0, all_expert_indices, pad) / all_expert_indices.shape[0]
+
+ # Compute the average probability of routing to these experts
+ router_prob_per_expert = torch.mean(all_routing_weights, dim=0)
+ else:
+ batch_size, sequence_length = attention_mask.shape
+ num_hidden_layers = len(gate_logits)
+
+ # Compute the mask that masks all padding tokens as 0 with the same shape of expert_mask
+ expert_attention_mask = (
+ attention_mask[None, :, :, None]
+ .expand((num_hidden_layers, batch_size, sequence_length, top_k))
+ .reshape(-1)
+ .to(compute_device)
+ )
+ all_expert_indices = all_expert_indices.view(-1)[expert_attention_mask.bool()]
+
+ # Compute the percentage of tokens routed to each experts
+ tokens_per_expert = torch.zeros(num_experts, dtype=compute_dtype, device=compute_device)
+ pad = torch.ones_like(all_expert_indices, dtype=compute_dtype, device=compute_device)
+ tokens_per_expert = tokens_per_expert.scatter_add_(0, all_expert_indices, pad) / torch.sum(
+ expert_attention_mask
+ )
+
+ # Compute the mask that masks all padding tokens as 0 with the same shape of tokens_per_expert
+ router_per_expert_attention_mask = (
+ attention_mask[None, :, :, None]
+ .expand((num_hidden_layers, batch_size, sequence_length, num_experts))
+ .reshape(-1, num_experts)
+ .to(compute_device)
+ )
+
+ # Compute the average probability of routing to these experts
+ router_prob_per_expert = torch.sum(all_routing_weights * router_per_expert_attention_mask, dim=0) / torch.sum(
+ router_per_expert_attention_mask, dim=0
+ )
+
+ overall_loss = torch.sum(tokens_per_expert * router_prob_per_expert)
+ return overall_loss * num_experts
+
+
+class DogeForCausalLM(MixtralForCausalLM):
+ def __init__(self, config):
+ super().__init__(config)
+ self.model = DogeModel(config)
+ self.num_experts = config.num_experts
+
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ use_cache: bool | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ output_router_logits: bool | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> MoeCausalLMOutputWithPast:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
+
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, DogeForCausalLM
+
+ >>> model = DogeForCausalLM.from_pretrained("SmallDoge/Doge-320M")
+ >>> tokenizer = AutoTokenizer.from_pretrained("SmallDoge/Doge-320M")
+
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
+
+ >>> # Generate
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
+ ```"""
+ output_router_logits = (
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
+ )
+
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
+ outputs: MoeModelOutputWithPast = self.model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ **kwargs,
+ )
+
+ hidden_states = outputs.last_hidden_state
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
+
+ aux_loss = None
+ if output_router_logits:
+ aux_loss = load_balancing_loss_func(
+ outputs.router_logits,
+ self.num_experts,
+ math.floor(math.sqrt(self.num_experts)),
+ self.num_experts_per_tok,
+ attention_mask,
+ )
+ if labels is not None:
+ loss += self.router_aux_loss_coef * aux_loss.to(loss.device) # make sure to reside in the same device
+
+ return MoeCausalLMOutputWithPast(
+ loss=loss,
+ aux_loss=aux_loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ router_logits=outputs.router_logits,
+ )
+
+
+class DogeForSequenceClassification(LlamaForSequenceClassification):
+ pass
+
+
+__all__ = [
+ "DogeConfig",
+ "DogeForCausalLM",
+ "DogeModel",
+ "DogePreTrainedModel",
+ "DogeForSequenceClassification",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dpr/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dpr/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..386b47bb2ecd07ed85a243e7c1920c8d2bfb4441
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dpr/__init__.py
@@ -0,0 +1,29 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_dpr import *
+ from .modeling_dpr import *
+ from .tokenization_dpr import *
+ from .tokenization_dpr_fast import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dpr/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dpr/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e0c030f2a5b90aa99d73cbfcc0ccc1d7cf74ba9a
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dpr/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dpr/__pycache__/configuration_dpr.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dpr/__pycache__/configuration_dpr.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5ebe2394e4c5a1447f086425c4f5d7f5c23fe792
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dpr/__pycache__/configuration_dpr.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dpr/__pycache__/modeling_dpr.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dpr/__pycache__/modeling_dpr.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4f5a4873b267c3f920412847b21c985eed1b876a
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dpr/__pycache__/modeling_dpr.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dpr/__pycache__/tokenization_dpr.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dpr/__pycache__/tokenization_dpr.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..be5e37b3275ccdff143e48c26a1e1fb1d8c7311f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dpr/__pycache__/tokenization_dpr.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dpr/__pycache__/tokenization_dpr_fast.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dpr/__pycache__/tokenization_dpr_fast.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8c9f869c48533f5bc89887e3bfcf0c5f4f927049
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dpr/__pycache__/tokenization_dpr_fast.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dpr/configuration_dpr.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dpr/configuration_dpr.py
new file mode 100644
index 0000000000000000000000000000000000000000..4a5429581d8d28ca12f918a753853c198c1568f5
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dpr/configuration_dpr.py
@@ -0,0 +1,63 @@
+# Copyright 2010, DPR authors, The Hugging Face Team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""DPR model configuration"""
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring
+
+
+@auto_docstring(checkpoint="facebook/dpr-ctx_encoder-single-nq-base")
+@strict
+class DPRConfig(PreTrainedConfig):
+ r"""
+ Example:
+
+ ```python
+ >>> from transformers import DPRConfig, DPRContextEncoder
+
+ >>> # Initializing a DPR facebook/dpr-ctx_encoder-single-nq-base style configuration
+ >>> configuration = DPRConfig()
+
+ >>> # Initializing a model (with random weights) from the facebook/dpr-ctx_encoder-single-nq-base style configuration
+ >>> model = DPRContextEncoder(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "dpr"
+
+ vocab_size: int = 30522
+ hidden_size: int = 768
+ num_hidden_layers: int = 12
+ num_attention_heads: int = 12
+ intermediate_size: int = 3072
+ hidden_act: str = "gelu"
+ hidden_dropout_prob: float | int = 0.1
+ attention_probs_dropout_prob: float | int = 0.1
+ max_position_embeddings: int = 512
+ type_vocab_size: int = 2
+ initializer_range: float = 0.02
+ layer_norm_eps: float = 1e-12
+ pad_token_id: int | None = 0
+ bos_token_id: int | None = None
+ eos_token_id: int | list[int] | None = None
+ projection_dim: int = 0
+ is_decoder: bool = False
+ add_cross_attention: bool = False
+
+
+__all__ = ["DPRConfig"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dpr/modeling_dpr.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dpr/modeling_dpr.py
new file mode 100644
index 0000000000000000000000000000000000000000..18cecd0495e4fffbdab574be9fc03e044f624525
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dpr/modeling_dpr.py
@@ -0,0 +1,576 @@
+# Copyright 2018 DPR Authors, The Hugging Face Team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch DPR model for Open Domain Question Answering."""
+
+from dataclasses import dataclass
+
+import torch
+from torch import Tensor, nn
+
+from ...modeling_outputs import BaseModelOutputWithPooling
+from ...modeling_utils import PreTrainedModel
+from ...utils import (
+ ModelOutput,
+ auto_docstring,
+ logging,
+)
+from ..bert.modeling_bert import BertModel
+from .configuration_dpr import DPRConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+##########
+# Outputs
+##########
+
+
+@auto_docstring(
+ custom_intro="""
+ Class for outputs of [`DPRQuestionEncoder`].
+ """
+)
+@dataclass
+class DPRContextEncoderOutput(ModelOutput):
+ r"""
+ pooler_output (`torch.FloatTensor` of shape `(batch_size, embeddings_size)`):
+ The DPR encoder outputs the *pooler_output* that corresponds to the context representation. Last layer
+ hidden-state of the first token of the sequence (classification token) further processed by a Linear layer.
+ This output is to be used to embed contexts for nearest neighbors queries with questions embeddings.
+ """
+
+ pooler_output: torch.FloatTensor
+ hidden_states: tuple[torch.FloatTensor, ...] | None = None
+ attentions: tuple[torch.FloatTensor, ...] | None = None
+
+
+@auto_docstring(
+ custom_intro="""
+ Class for outputs of [`DPRQuestionEncoder`].
+ """
+)
+@dataclass
+class DPRQuestionEncoderOutput(ModelOutput):
+ r"""
+ pooler_output (`torch.FloatTensor` of shape `(batch_size, embeddings_size)`):
+ The DPR encoder outputs the *pooler_output* that corresponds to the question representation. Last layer
+ hidden-state of the first token of the sequence (classification token) further processed by a Linear layer.
+ This output is to be used to embed questions for nearest neighbors queries with context embeddings.
+ """
+
+ pooler_output: torch.FloatTensor
+ hidden_states: tuple[torch.FloatTensor, ...] | None = None
+ attentions: tuple[torch.FloatTensor, ...] | None = None
+
+
+@auto_docstring(
+ custom_intro="""
+ Class for outputs of [`DPRQuestionEncoder`].
+ """
+)
+@dataclass
+class DPRReaderOutput(ModelOutput):
+ r"""
+ start_logits (`torch.FloatTensor` of shape `(n_passages, sequence_length)`):
+ Logits of the start index of the span for each passage.
+ end_logits (`torch.FloatTensor` of shape `(n_passages, sequence_length)`):
+ Logits of the end index of the span for each passage.
+ relevance_logits (`torch.FloatTensor` of shape `(n_passages, )`):
+ Outputs of the QA classifier of the DPRReader that corresponds to the scores of each passage to answer the
+ question, compared to all the other passages.
+ """
+
+ start_logits: torch.FloatTensor
+ end_logits: torch.FloatTensor | None = None
+ relevance_logits: torch.FloatTensor | None = None
+ hidden_states: tuple[torch.FloatTensor, ...] | None = None
+ attentions: tuple[torch.FloatTensor, ...] | None = None
+
+
+@auto_docstring
+class DPRPreTrainedModel(PreTrainedModel):
+ _supports_sdpa = True
+
+
+class DPREncoder(DPRPreTrainedModel):
+ base_model_prefix = "bert_model"
+
+ def __init__(self, config: DPRConfig):
+ super().__init__(config)
+ self.bert_model = BertModel(config, add_pooling_layer=False)
+ if self.bert_model.config.hidden_size <= 0:
+ raise ValueError("Encoder hidden_size can't be zero")
+ self.projection_dim = config.projection_dim
+ if self.projection_dim > 0:
+ self.encode_proj = nn.Linear(self.bert_model.config.hidden_size, config.projection_dim)
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def forward(
+ self,
+ input_ids: Tensor,
+ attention_mask: Tensor | None = None,
+ token_type_ids: Tensor | None = None,
+ inputs_embeds: Tensor | None = None,
+ output_attentions: bool = False,
+ output_hidden_states: bool = False,
+ return_dict: bool = False,
+ **kwargs,
+ ) -> BaseModelOutputWithPooling | tuple[Tensor, ...]:
+ outputs = self.bert_model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+ sequence_output = outputs[0]
+ pooled_output = sequence_output[:, 0, :]
+
+ if self.projection_dim > 0:
+ pooled_output = self.encode_proj(pooled_output)
+
+ if not return_dict:
+ return (sequence_output, pooled_output) + outputs[2:]
+
+ return BaseModelOutputWithPooling(
+ last_hidden_state=sequence_output,
+ pooler_output=pooled_output,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+ @property
+ def embeddings_size(self) -> int:
+ if self.projection_dim > 0:
+ return self.encode_proj.out_features
+ return self.bert_model.config.hidden_size
+
+
+class DPRSpanPredictor(DPRPreTrainedModel):
+ base_model_prefix = "encoder"
+
+ def __init__(self, config: DPRConfig):
+ super().__init__(config)
+ self.encoder = DPREncoder(config)
+ self.qa_outputs = nn.Linear(self.encoder.embeddings_size, 2)
+ self.qa_classifier = nn.Linear(self.encoder.embeddings_size, 1)
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def forward(
+ self,
+ input_ids: Tensor,
+ attention_mask: Tensor,
+ inputs_embeds: Tensor | None = None,
+ output_attentions: bool = False,
+ output_hidden_states: bool = False,
+ return_dict: bool = False,
+ **kwargs,
+ ) -> DPRReaderOutput | tuple[Tensor, ...]:
+ # notations: N - number of questions in a batch, M - number of passages per questions, L - sequence length
+ n_passages, sequence_length = input_ids.size() if input_ids is not None else inputs_embeds.size()[:2]
+ # feed encoder
+ outputs = self.encoder(
+ input_ids,
+ attention_mask=attention_mask,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+ sequence_output = outputs[0]
+
+ # compute logits
+ logits = self.qa_outputs(sequence_output)
+ start_logits, end_logits = logits.split(1, dim=-1)
+ start_logits = start_logits.squeeze(-1).contiguous()
+ end_logits = end_logits.squeeze(-1).contiguous()
+ relevance_logits = self.qa_classifier(sequence_output[:, 0, :])
+
+ # resize
+ start_logits = start_logits.view(n_passages, sequence_length)
+ end_logits = end_logits.view(n_passages, sequence_length)
+ relevance_logits = relevance_logits.view(n_passages)
+
+ if not return_dict:
+ return (start_logits, end_logits, relevance_logits) + outputs[2:]
+
+ return DPRReaderOutput(
+ start_logits=start_logits,
+ end_logits=end_logits,
+ relevance_logits=relevance_logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+##################
+# PreTrainedModel
+##################
+
+
+class DPRPretrainedContextEncoder(DPRPreTrainedModel):
+ """
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
+ models.
+ """
+
+ config: DPRConfig
+ base_model_prefix = "ctx_encoder"
+
+
+class DPRPretrainedQuestionEncoder(DPRPreTrainedModel):
+ """
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
+ models.
+ """
+
+ config: DPRConfig
+ base_model_prefix = "question_encoder"
+
+
+class DPRPretrainedReader(DPRPreTrainedModel):
+ """
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
+ models.
+ """
+
+ config: DPRConfig
+ base_model_prefix = "span_predictor"
+
+
+###############
+# Actual Models
+###############
+
+
+@auto_docstring(
+ custom_intro="""
+ The bare DPRContextEncoder transformer outputting pooler outputs as context representations.
+ """
+)
+class DPRContextEncoder(DPRPretrainedContextEncoder):
+ def __init__(self, config: DPRConfig):
+ super().__init__(config)
+ self.config = config
+ self.ctx_encoder = DPREncoder(config)
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: Tensor | None = None,
+ attention_mask: Tensor | None = None,
+ token_type_ids: Tensor | None = None,
+ inputs_embeds: Tensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> DPRContextEncoderOutput | tuple[Tensor, ...]:
+ r"""
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary. To match pretraining, DPR input sequence should be
+ formatted with [CLS] and [SEP] tokens as follows:
+
+ (a) For sequence pairs (for a pair title+text for example):
+
+ ```
+ tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]
+ token_type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1
+ ```
+
+ (b) For single sequences (for a question for example):
+
+ ```
+ tokens: [CLS] the dog is hairy . [SEP]
+ token_type_ids: 0 0 0 0 0 0 0
+ ```
+
+ DPR is a model with absolute position embeddings so it's usually advised to pad the inputs on the right
+ rather than the left.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input-ids)
+
+ Examples:
+
+ ```python
+ >>> from transformers import DPRContextEncoder, DPRContextEncoderTokenizer
+
+ >>> tokenizer = DPRContextEncoderTokenizer.from_pretrained("facebook/dpr-ctx_encoder-single-nq-base")
+ >>> model = DPRContextEncoder.from_pretrained("facebook/dpr-ctx_encoder-single-nq-base")
+ >>> input_ids = tokenizer("Hello, is my dog cute ?", return_tensors="pt")["input_ids"]
+ >>> embeddings = model(input_ids).pooler_output
+ ```"""
+
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ if input_ids is not None and inputs_embeds is not None:
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
+ elif input_ids is not None:
+ input_shape = input_ids.size()
+ elif inputs_embeds is not None:
+ input_shape = inputs_embeds.size()[:-1]
+ else:
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
+
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
+
+ if attention_mask is None:
+ attention_mask = (
+ torch.ones(input_shape, device=device)
+ if input_ids is None
+ else (input_ids != self.config.pad_token_id)
+ )
+ if token_type_ids is None:
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
+
+ outputs = self.ctx_encoder(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ if not return_dict:
+ return outputs[1:]
+ return DPRContextEncoderOutput(
+ pooler_output=outputs.pooler_output, hidden_states=outputs.hidden_states, attentions=outputs.attentions
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ The bare DPRQuestionEncoder transformer outputting pooler outputs as question representations.
+ """
+)
+class DPRQuestionEncoder(DPRPretrainedQuestionEncoder):
+ def __init__(self, config: DPRConfig):
+ super().__init__(config)
+ self.config = config
+ self.question_encoder = DPREncoder(config)
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: Tensor | None = None,
+ attention_mask: Tensor | None = None,
+ token_type_ids: Tensor | None = None,
+ inputs_embeds: Tensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> DPRQuestionEncoderOutput | tuple[Tensor, ...]:
+ r"""
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary. To match pretraining, DPR input sequence should be
+ formatted with [CLS] and [SEP] tokens as follows:
+
+ (a) For sequence pairs (for a pair title+text for example):
+
+ ```
+ tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]
+ token_type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1
+ ```
+
+ (b) For single sequences (for a question for example):
+
+ ```
+ tokens: [CLS] the dog is hairy . [SEP]
+ token_type_ids: 0 0 0 0 0 0 0
+ ```
+
+ DPR is a model with absolute position embeddings so it's usually advised to pad the inputs on the right
+ rather than the left.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input-ids)
+
+ Examples:
+
+ ```python
+ >>> from transformers import DPRQuestionEncoder, DPRQuestionEncoderTokenizer
+
+ >>> tokenizer = DPRQuestionEncoderTokenizer.from_pretrained("facebook/dpr-question_encoder-single-nq-base")
+ >>> model = DPRQuestionEncoder.from_pretrained("facebook/dpr-question_encoder-single-nq-base")
+ >>> input_ids = tokenizer("Hello, is my dog cute ?", return_tensors="pt")["input_ids"]
+ >>> embeddings = model(input_ids).pooler_output
+ ```
+ """
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ if input_ids is not None and inputs_embeds is not None:
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
+ elif input_ids is not None:
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
+ input_shape = input_ids.size()
+ elif inputs_embeds is not None:
+ input_shape = inputs_embeds.size()[:-1]
+ else:
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
+
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
+
+ if attention_mask is None:
+ attention_mask = (
+ torch.ones(input_shape, device=device)
+ if input_ids is None
+ else (input_ids != self.config.pad_token_id)
+ )
+ if token_type_ids is None:
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
+
+ outputs = self.question_encoder(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ if not return_dict:
+ return outputs[1:]
+ return DPRQuestionEncoderOutput(
+ pooler_output=outputs.pooler_output, hidden_states=outputs.hidden_states, attentions=outputs.attentions
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ The bare DPRReader transformer outputting span predictions.
+ """
+)
+class DPRReader(DPRPretrainedReader):
+ def __init__(self, config: DPRConfig):
+ super().__init__(config)
+ self.config = config
+ self.span_predictor = DPRSpanPredictor(config)
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: Tensor | None = None,
+ attention_mask: Tensor | None = None,
+ inputs_embeds: Tensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> DPRReaderOutput | tuple[Tensor, ...]:
+ r"""
+ input_ids (`tuple[torch.LongTensor]` of shapes `(n_passages, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary. It has to be a sequence triplet with 1) the question
+ and 2) the passages titles and 3) the passages texts To match pretraining, DPR `input_ids` sequence should
+ be formatted with [CLS] and [SEP] with the format:
+
+ `[CLS] [SEP] [SEP] `
+
+ DPR is a model with absolute position embeddings so it's usually advised to pad the inputs on the right
+ rather than the left.
+
+ Indices can be obtained using [`DPRReaderTokenizer`]. See this class documentation for more details.
+
+ [What are input IDs?](../glossary#input-ids)
+ inputs_embeds (`torch.FloatTensor` of shape `(n_passages, sequence_length, hidden_size)`, *optional*):
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
+ model's internal embedding lookup matrix.
+
+ Examples:
+
+ ```python
+ >>> from transformers import DPRReader, DPRReaderTokenizer
+
+ >>> tokenizer = DPRReaderTokenizer.from_pretrained("facebook/dpr-reader-single-nq-base")
+ >>> model = DPRReader.from_pretrained("facebook/dpr-reader-single-nq-base")
+ >>> encoded_inputs = tokenizer(
+ ... questions=["What is love ?"],
+ ... titles=["Haddaway"],
+ ... texts=["'What Is Love' is a song recorded by the artist Haddaway"],
+ ... return_tensors="pt",
+ ... )
+ >>> outputs = model(**encoded_inputs)
+ >>> start_logits = outputs.start_logits
+ >>> end_logits = outputs.end_logits
+ >>> relevance_logits = outputs.relevance_logits
+ ```
+ """
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ if input_ids is not None and inputs_embeds is not None:
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
+ elif input_ids is not None:
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
+ input_shape = input_ids.size()
+ elif inputs_embeds is not None:
+ input_shape = inputs_embeds.size()[:-1]
+ else:
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
+
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
+
+ if attention_mask is None:
+ attention_mask = torch.ones(input_shape, device=device)
+
+ return self.span_predictor(
+ input_ids,
+ attention_mask,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+
+__all__ = [
+ "DPRContextEncoder",
+ "DPRPretrainedContextEncoder",
+ "DPRPreTrainedModel",
+ "DPRPretrainedQuestionEncoder",
+ "DPRPretrainedReader",
+ "DPRQuestionEncoder",
+ "DPRReader",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dpr/tokenization_dpr.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dpr/tokenization_dpr.py
new file mode 100644
index 0000000000000000000000000000000000000000..ff33ec5e0f0742341128924c01770410e4d39fb3
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dpr/tokenization_dpr.py
@@ -0,0 +1,330 @@
+# Copyright 2018 The HuggingFace Inc. team, The Hugging Face Team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Tokenization classes for DPR."""
+
+import collections
+
+from ...tokenization_utils_base import BatchEncoding
+from ...utils import TensorType, add_end_docstrings, add_start_docstrings, logging
+from ..bert.tokenization_bert import BertTokenizer
+
+
+logger = logging.get_logger(__name__)
+
+VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"}
+
+
+class DPRContextEncoderTokenizer(BertTokenizer):
+ r"""
+ Construct a DPRContextEncoder tokenizer.
+
+ [`DPRContextEncoderTokenizer`] is identical to [`BertTokenizer`] and runs end-to-end tokenization: punctuation
+ splitting and wordpiece.
+
+ Refer to superclass [`BertTokenizer`] for usage examples and documentation concerning parameters.
+ """
+
+ vocab_files_names = VOCAB_FILES_NAMES
+
+ def __init__(self, *args, do_lower_case=False, **kwargs):
+ super().__init__(*args, **kwargs)
+ self.do_lower_case = do_lower_case
+
+
+class DPRQuestionEncoderTokenizer(BertTokenizer):
+ r"""
+ Constructs a DPRQuestionEncoder tokenizer.
+
+ [`DPRQuestionEncoderTokenizer`] is identical to [`BertTokenizer`] and runs end-to-end tokenization: punctuation
+ splitting and wordpiece.
+
+ Refer to superclass [`BertTokenizer`] for usage examples and documentation concerning parameters.
+ """
+
+ vocab_files_names = VOCAB_FILES_NAMES
+
+ def __init__(self, *args, do_lower_case=False, **kwargs):
+ super().__init__(*args, **kwargs)
+ self.do_lower_case = do_lower_case
+
+
+DPRSpanPrediction = collections.namedtuple(
+ "DPRSpanPrediction", ["span_score", "relevance_score", "doc_id", "start_index", "end_index", "text"]
+)
+
+DPRReaderOutput = collections.namedtuple("DPRReaderOutput", ["start_logits", "end_logits", "relevance_logits"])
+
+
+CUSTOM_DPR_READER_DOCSTRING = r"""
+ Return a dictionary with the token ids of the input strings and other information to give to `.decode_best_spans`.
+ It converts the strings of a question and different passages (title and text) in a sequence of IDs (integers),
+ using the tokenizer and vocabulary. The resulting `input_ids` is a matrix of size `(n_passages, sequence_length)`
+ with the format:
+
+ ```
+ [CLS] [SEP] [SEP]
+ ```
+
+ Args:
+ questions (`str` or `list[str]`):
+ The questions to be encoded. You can specify one question for many passages. In this case, the question
+ will be duplicated like `[questions] * n_passages`. Otherwise you have to specify as many questions as in
+ `titles` or `texts`.
+ titles (`str` or `list[str]`):
+ The passages titles to be encoded. This can be a string or a list of strings if there are several passages.
+ texts (`str` or `list[str]`):
+ The passages texts to be encoded. This can be a string or a list of strings if there are several passages.
+ padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`):
+ Activates and controls padding. Accepts the following values:
+
+ - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single sequence
+ if provided).
+ - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
+ acceptable input length for the model if that argument is not provided.
+ - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
+ lengths).
+ truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`):
+ Activates and controls truncation. Accepts the following values:
+
+ - `True` or `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or to
+ the maximum acceptable input length for the model if that argument is not provided. This will truncate
+ token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch
+ of pairs) is provided.
+ - `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum
+ acceptable input length for the model if that argument is not provided. This will only truncate the first
+ sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
+ - `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum
+ acceptable input length for the model if that argument is not provided. This will only truncate the
+ second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
+ - `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths
+ greater than the model maximum admissible input size).
+ max_length (`int`, *optional*):
+ Controls the maximum length to use by one of the truncation/padding parameters.
+
+ If left unset or set to `None`, this will use the predefined model maximum length if a maximum length
+ is required by one of the truncation/padding parameters. If the model has no specific maximum input
+ length (like XLNet) truncation/padding to a maximum length will be deactivated.
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
+ If set, will return tensors instead of list of python integers. Acceptable values are:
+
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
+ - `'np'`: Return Numpy `np.ndarray` objects.
+ return_attention_mask (`bool`, *optional*):
+ Whether or not to return the attention mask. If not set, will return the attention mask according to the
+ specific tokenizer's default, defined by the `return_outputs` attribute.
+
+ [What are attention masks?](../glossary#attention-mask)
+
+ Returns:
+ `dict[str, list[list[int]]]`: A dictionary with the following keys:
+
+ - `input_ids`: List of token ids to be fed to a model.
+ - `attention_mask`: List of indices specifying which tokens should be attended to by the model.
+ """
+
+
+@add_start_docstrings(CUSTOM_DPR_READER_DOCSTRING)
+class CustomDPRReaderTokenizerMixin:
+ def __call__(
+ self,
+ questions,
+ titles: str | None = None,
+ texts: str | None = None,
+ padding: bool | str = False,
+ truncation: bool | str = False,
+ max_length: int | None = None,
+ return_tensors: str | TensorType | None = None,
+ return_attention_mask: bool | None = None,
+ **kwargs,
+ ) -> BatchEncoding:
+ if titles is None and texts is None:
+ return super().__call__(
+ questions,
+ padding=padding,
+ truncation=truncation,
+ max_length=max_length,
+ return_tensors=return_tensors,
+ return_attention_mask=return_attention_mask,
+ **kwargs,
+ )
+ elif titles is None or texts is None:
+ text_pair = titles if texts is None else texts
+ return super().__call__(
+ questions,
+ text_pair,
+ padding=padding,
+ truncation=truncation,
+ max_length=max_length,
+ return_tensors=return_tensors,
+ return_attention_mask=return_attention_mask,
+ **kwargs,
+ )
+ titles = titles if not isinstance(titles, str) else [titles]
+ texts = texts if not isinstance(texts, str) else [texts]
+ n_passages = len(titles)
+ questions = questions if not isinstance(questions, str) else [questions] * n_passages
+ if len(titles) != len(texts):
+ raise ValueError(
+ f"There should be as many titles than texts but got {len(titles)} titles and {len(texts)} texts."
+ )
+ encoded_question_and_titles = super().__call__(questions, titles, padding=False, truncation=False)["input_ids"]
+ encoded_texts = super().__call__(texts, add_special_tokens=False, padding=False, truncation=False)["input_ids"]
+ encoded_inputs = {
+ "input_ids": [
+ (encoded_question_and_title + encoded_text)[:max_length]
+ if max_length is not None and truncation
+ else encoded_question_and_title + encoded_text
+ for encoded_question_and_title, encoded_text in zip(encoded_question_and_titles, encoded_texts)
+ ]
+ }
+ if return_attention_mask is not False:
+ attention_mask = []
+ for input_ids in encoded_inputs["input_ids"]:
+ attention_mask.append([int(input_id != self.pad_token_id) for input_id in input_ids])
+ encoded_inputs["attention_mask"] = attention_mask
+ return self.pad(encoded_inputs, padding=padding, max_length=max_length, return_tensors=return_tensors)
+
+ def decode_best_spans(
+ self,
+ reader_input: BatchEncoding,
+ reader_output: DPRReaderOutput,
+ num_spans: int = 16,
+ max_answer_length: int = 64,
+ num_spans_per_passage: int = 4,
+ ) -> list[DPRSpanPrediction]:
+ """
+ Get the span predictions for the extractive Q&A model.
+
+ Returns: *List* of *DPRReaderOutput* sorted by descending *(relevance_score, span_score)*. Each
+ *DPRReaderOutput* is a *Tuple* with:
+
+ - **span_score**: `float` that corresponds to the score given by the reader for this span compared to other
+ spans in the same passage. It corresponds to the sum of the start and end logits of the span.
+ - **relevance_score**: `float` that corresponds to the score of the each passage to answer the question,
+ compared to all the other passages. It corresponds to the output of the QA classifier of the DPRReader.
+ - **doc_id**: `int` the id of the passage. - **start_index**: `int` the start index of the span
+ (inclusive). - **end_index**: `int` the end index of the span (inclusive).
+
+ Examples:
+
+ ```python
+ >>> from transformers import DPRReader, DPRReaderTokenizer
+
+ >>> tokenizer = DPRReaderTokenizer.from_pretrained("facebook/dpr-reader-single-nq-base")
+ >>> model = DPRReader.from_pretrained("facebook/dpr-reader-single-nq-base")
+ >>> encoded_inputs = tokenizer(
+ ... questions=["What is love ?"],
+ ... titles=["Haddaway"],
+ ... texts=["'What Is Love' is a song recorded by the artist Haddaway"],
+ ... return_tensors="pt",
+ ... )
+ >>> outputs = model(**encoded_inputs)
+ >>> predicted_spans = tokenizer.decode_best_spans(encoded_inputs, outputs)
+ >>> print(predicted_spans[0].text) # best span
+ a song
+ ```"""
+ input_ids = reader_input["input_ids"]
+ start_logits, end_logits, relevance_logits = reader_output[:3]
+ n_passages = len(relevance_logits)
+ sorted_docs = sorted(range(n_passages), reverse=True, key=relevance_logits.__getitem__)
+ nbest_spans_predictions: list[DPRReaderOutput] = []
+ for doc_id in sorted_docs:
+ sequence_ids = list(input_ids[doc_id])
+ # assuming question & title information is at the beginning of the sequence
+ passage_offset = sequence_ids.index(self.sep_token_id, 2) + 1 # second sep id
+ if sequence_ids[-1] == self.pad_token_id:
+ sequence_len = sequence_ids.index(self.pad_token_id)
+ else:
+ sequence_len = len(sequence_ids)
+
+ best_spans = self._get_best_spans(
+ start_logits=start_logits[doc_id][passage_offset:sequence_len],
+ end_logits=end_logits[doc_id][passage_offset:sequence_len],
+ max_answer_length=max_answer_length,
+ top_spans=num_spans_per_passage,
+ )
+ for start_index, end_index in best_spans:
+ start_index += passage_offset
+ end_index += passage_offset
+ nbest_spans_predictions.append(
+ DPRSpanPrediction(
+ span_score=start_logits[doc_id][start_index] + end_logits[doc_id][end_index],
+ relevance_score=relevance_logits[doc_id],
+ doc_id=doc_id,
+ start_index=start_index,
+ end_index=end_index,
+ text=self.decode(sequence_ids[start_index : end_index + 1]),
+ )
+ )
+ if len(nbest_spans_predictions) >= num_spans:
+ break
+ return nbest_spans_predictions[:num_spans]
+
+ def _get_best_spans(
+ self,
+ start_logits: list[int],
+ end_logits: list[int],
+ max_answer_length: int,
+ top_spans: int,
+ ) -> list[DPRSpanPrediction]:
+ """
+ Finds the best answer span for the extractive Q&A model for one passage. It returns the best span by descending
+ `span_score` order and keeping max `top_spans` spans. Spans longer that `max_answer_length` are ignored.
+ """
+ scores = []
+ for start_index, start_score in enumerate(start_logits):
+ for answer_length, end_score in enumerate(end_logits[start_index : start_index + max_answer_length]):
+ scores.append(((start_index, start_index + answer_length), start_score + end_score))
+ scores = sorted(scores, key=lambda x: x[1], reverse=True)
+ chosen_span_intervals = []
+ for (start_index, end_index), score in scores:
+ if start_index > end_index:
+ raise ValueError(f"Wrong span indices: [{start_index}:{end_index}]")
+ length = end_index - start_index + 1
+ if length > max_answer_length:
+ raise ValueError(f"Span is too long: {length} > {max_answer_length}")
+ if any(
+ start_index <= prev_start_index <= prev_end_index <= end_index
+ or prev_start_index <= start_index <= end_index <= prev_end_index
+ for (prev_start_index, prev_end_index) in chosen_span_intervals
+ ):
+ continue
+ chosen_span_intervals.append((start_index, end_index))
+
+ if len(chosen_span_intervals) == top_spans:
+ break
+ return chosen_span_intervals
+
+
+@add_end_docstrings(CUSTOM_DPR_READER_DOCSTRING)
+class DPRReaderTokenizer(CustomDPRReaderTokenizerMixin, BertTokenizer):
+ r"""
+ Construct a DPRReader tokenizer.
+
+ [`DPRReaderTokenizer`] is almost identical to [`BertTokenizer`] and runs end-to-end tokenization: punctuation
+ splitting and wordpiece. The difference is that is has three inputs strings: question, titles and texts that are
+ combined to be fed to the [`DPRReader`] model.
+
+ Refer to superclass [`BertTokenizer`] for usage examples and documentation concerning parameters.
+ """
+
+ vocab_files_names = VOCAB_FILES_NAMES
+ model_input_names = ["input_ids", "attention_mask"]
+
+ def __init__(self, *args, do_lower_case=False, **kwargs):
+ super().__init__(*args, **kwargs)
+ self.do_lower_case = do_lower_case
+
+
+__all__ = ["DPRContextEncoderTokenizer", "DPRQuestionEncoderTokenizer", "DPRReaderOutput", "DPRReaderTokenizer"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dpr/tokenization_dpr_fast.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dpr/tokenization_dpr_fast.py
new file mode 100644
index 0000000000000000000000000000000000000000..96723f63cdfe3904c86dd1de5b3786d0112ae160
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/dpr/tokenization_dpr_fast.py
@@ -0,0 +1,318 @@
+# Copyright 2018 The HuggingFace Inc. team, The Hugging Face Team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Tokenization classes for DPR."""
+
+import collections
+
+from ...tokenization_utils_base import BatchEncoding
+from ...utils import TensorType, add_end_docstrings, add_start_docstrings, logging
+from ..bert.tokenization_bert import BertTokenizer
+from .tokenization_dpr import DPRContextEncoderTokenizer, DPRQuestionEncoderTokenizer, DPRReaderTokenizer
+
+
+logger = logging.get_logger(__name__)
+
+VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"}
+
+
+class DPRContextEncoderTokenizerFast(BertTokenizer):
+ r"""
+ Construct a "fast" DPRContextEncoder tokenizer (backed by HuggingFace's *tokenizers* library).
+
+ [`DPRContextEncoderTokenizerFast`] is identical to [`BertTokenizer`] and runs end-to-end tokenization:
+ punctuation splitting and wordpiece.
+
+ Refer to superclass [`BertTokenizer`] for usage examples and documentation concerning parameters.
+ """
+
+ vocab_files_names = VOCAB_FILES_NAMES
+ slow_tokenizer_class = DPRContextEncoderTokenizer
+
+
+class DPRQuestionEncoderTokenizerFast(BertTokenizer):
+ r"""
+ Constructs a "fast" DPRQuestionEncoder tokenizer (backed by HuggingFace's *tokenizers* library).
+
+ [`DPRQuestionEncoderTokenizerFast`] is identical to [`BertTokenizer`] and runs end-to-end tokenization:
+ punctuation splitting and wordpiece.
+
+ Refer to superclass [`BertTokenizer`] for usage examples and documentation concerning parameters.
+ """
+
+ vocab_files_names = VOCAB_FILES_NAMES
+ slow_tokenizer_class = DPRQuestionEncoderTokenizer
+
+
+DPRSpanPrediction = collections.namedtuple(
+ "DPRSpanPrediction", ["span_score", "relevance_score", "doc_id", "start_index", "end_index", "text"]
+)
+
+DPRReaderOutput = collections.namedtuple("DPRReaderOutput", ["start_logits", "end_logits", "relevance_logits"])
+
+
+CUSTOM_DPR_READER_DOCSTRING = r"""
+ Return a dictionary with the token ids of the input strings and other information to give to `.decode_best_spans`.
+ It converts the strings of a question and different passages (title and text) in a sequence of IDs (integers),
+ using the tokenizer and vocabulary. The resulting `input_ids` is a matrix of size `(n_passages, sequence_length)`
+ with the format:
+
+ [CLS] [SEP] [SEP]
+
+ Args:
+ questions (`str` or `list[str]`):
+ The questions to be encoded. You can specify one question for many passages. In this case, the question
+ will be duplicated like `[questions] * n_passages`. Otherwise you have to specify as many questions as in
+ `titles` or `texts`.
+ titles (`str` or `list[str]`):
+ The passages titles to be encoded. This can be a string or a list of strings if there are several passages.
+ texts (`str` or `list[str]`):
+ The passages texts to be encoded. This can be a string or a list of strings if there are several passages.
+ padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`):
+ Activates and controls padding. Accepts the following values:
+
+ - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single sequence
+ if provided).
+ - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
+ acceptable input length for the model if that argument is not provided.
+ - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
+ lengths).
+ truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`):
+ Activates and controls truncation. Accepts the following values:
+
+ - `True` or `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or to
+ the maximum acceptable input length for the model if that argument is not provided. This will truncate
+ token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch
+ of pairs) is provided.
+ - `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum
+ acceptable input length for the model if that argument is not provided. This will only truncate the first
+ sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
+ - `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum
+ acceptable input length for the model if that argument is not provided. This will only truncate the
+ second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
+ - `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths
+ greater than the model maximum admissible input size).
+ max_length (`int`, *optional*):
+ Controls the maximum length to use by one of the truncation/padding parameters.
+
+ If left unset or set to `None`, this will use the predefined model maximum length if a maximum length
+ is required by one of the truncation/padding parameters. If the model has no specific maximum input
+ length (like XLNet) truncation/padding to a maximum length will be deactivated.
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
+ If set, will return tensors instead of list of python integers. Acceptable values are:
+
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
+ - `'np'`: Return Numpy `np.ndarray` objects.
+ return_attention_mask (`bool`, *optional*):
+ Whether or not to return the attention mask. If not set, will return the attention mask according to the
+ specific tokenizer's default, defined by the `return_outputs` attribute.
+
+ [What are attention masks?](../glossary#attention-mask)
+
+ Return:
+ `dict[str, list[list[int]]]`: A dictionary with the following keys:
+
+ - `input_ids`: List of token ids to be fed to a model.
+ - `attention_mask`: List of indices specifying which tokens should be attended to by the model.
+ """
+
+
+@add_start_docstrings(CUSTOM_DPR_READER_DOCSTRING)
+class CustomDPRReaderTokenizerMixin:
+ def __call__(
+ self,
+ questions,
+ titles: str | None = None,
+ texts: str | None = None,
+ padding: bool | str = False,
+ truncation: bool | str = False,
+ max_length: int | None = None,
+ return_tensors: str | TensorType | None = None,
+ return_attention_mask: bool | None = None,
+ **kwargs,
+ ) -> BatchEncoding:
+ if titles is None and texts is None:
+ return super().__call__(
+ questions,
+ padding=padding,
+ truncation=truncation,
+ max_length=max_length,
+ return_tensors=return_tensors,
+ return_attention_mask=return_attention_mask,
+ **kwargs,
+ )
+ elif titles is None or texts is None:
+ text_pair = titles if texts is None else texts
+ return super().__call__(
+ questions,
+ text_pair,
+ padding=padding,
+ truncation=truncation,
+ max_length=max_length,
+ return_tensors=return_tensors,
+ return_attention_mask=return_attention_mask,
+ **kwargs,
+ )
+ titles = titles if not isinstance(titles, str) else [titles]
+ texts = texts if not isinstance(texts, str) else [texts]
+ n_passages = len(titles)
+ questions = questions if not isinstance(questions, str) else [questions] * n_passages
+ assert len(titles) == len(texts), (
+ f"There should be as many titles than texts but got {len(titles)} titles and {len(texts)} texts."
+ )
+ encoded_question_and_titles = super().__call__(questions, titles, padding=False, truncation=False)["input_ids"]
+ encoded_texts = super().__call__(texts, add_special_tokens=False, padding=False, truncation=False)["input_ids"]
+ encoded_inputs = {
+ "input_ids": [
+ (encoded_question_and_title + encoded_text)[:max_length]
+ if max_length is not None and truncation
+ else encoded_question_and_title + encoded_text
+ for encoded_question_and_title, encoded_text in zip(encoded_question_and_titles, encoded_texts)
+ ]
+ }
+ if return_attention_mask is not False:
+ attention_mask = []
+ for input_ids in encoded_inputs["input_ids"]:
+ attention_mask.append([int(input_id != self.pad_token_id) for input_id in input_ids])
+ encoded_inputs["attention_mask"] = attention_mask
+ return self.pad(encoded_inputs, padding=padding, max_length=max_length, return_tensors=return_tensors)
+
+ def decode_best_spans(
+ self,
+ reader_input: BatchEncoding,
+ reader_output: DPRReaderOutput,
+ num_spans: int = 16,
+ max_answer_length: int = 64,
+ num_spans_per_passage: int = 4,
+ ) -> list[DPRSpanPrediction]:
+ """
+ Get the span predictions for the extractive Q&A model.
+
+ Returns: *List* of *DPRReaderOutput* sorted by descending *(relevance_score, span_score)*. Each
+ *DPRReaderOutput* is a *Tuple* with:
+
+ - **span_score**: `float` that corresponds to the score given by the reader for this span compared to other
+ spans in the same passage. It corresponds to the sum of the start and end logits of the span.
+ - **relevance_score**: `float` that corresponds to the score of the each passage to answer the question,
+ compared to all the other passages. It corresponds to the output of the QA classifier of the DPRReader.
+ - **doc_id**: `int` the id of the passage. - ***start_index**: `int` the start index of the span
+ (inclusive). - **end_index**: `int` the end index of the span (inclusive).
+
+ Examples:
+
+ ```python
+ >>> from transformers import DPRReader, DPRReaderTokenizer
+
+ >>> tokenizer = DPRReaderTokenizer.from_pretrained("facebook/dpr-reader-single-nq-base")
+ >>> model = DPRReader.from_pretrained("facebook/dpr-reader-single-nq-base")
+ >>> encoded_inputs = tokenizer(
+ ... questions=["What is love ?"],
+ ... titles=["Haddaway"],
+ ... texts=["'What Is Love' is a song recorded by the artist Haddaway"],
+ ... return_tensors="pt",
+ ... )
+ >>> outputs = model(**encoded_inputs)
+ >>> predicted_spans = tokenizer.decode_best_spans(encoded_inputs, outputs)
+ >>> print(predicted_spans[0].text) # best span
+ a song
+ ```"""
+ input_ids = reader_input["input_ids"]
+ start_logits, end_logits, relevance_logits = reader_output[:3]
+ n_passages = len(relevance_logits)
+ sorted_docs = sorted(range(n_passages), reverse=True, key=relevance_logits.__getitem__)
+ nbest_spans_predictions: list[DPRReaderOutput] = []
+ for doc_id in sorted_docs:
+ sequence_ids = list(input_ids[doc_id])
+ # assuming question & title information is at the beginning of the sequence
+ passage_offset = sequence_ids.index(self.sep_token_id, 2) + 1 # second sep id
+ if sequence_ids[-1] == self.pad_token_id:
+ sequence_len = sequence_ids.index(self.pad_token_id)
+ else:
+ sequence_len = len(sequence_ids)
+
+ best_spans = self._get_best_spans(
+ start_logits=start_logits[doc_id][passage_offset:sequence_len],
+ end_logits=end_logits[doc_id][passage_offset:sequence_len],
+ max_answer_length=max_answer_length,
+ top_spans=num_spans_per_passage,
+ )
+ for start_index, end_index in best_spans:
+ start_index += passage_offset
+ end_index += passage_offset
+ nbest_spans_predictions.append(
+ DPRSpanPrediction(
+ span_score=start_logits[doc_id][start_index] + end_logits[doc_id][end_index],
+ relevance_score=relevance_logits[doc_id],
+ doc_id=doc_id,
+ start_index=start_index,
+ end_index=end_index,
+ text=self.decode(sequence_ids[start_index : end_index + 1]),
+ )
+ )
+ if len(nbest_spans_predictions) >= num_spans:
+ break
+ return nbest_spans_predictions[:num_spans]
+
+ def _get_best_spans(
+ self,
+ start_logits: list[int],
+ end_logits: list[int],
+ max_answer_length: int,
+ top_spans: int,
+ ) -> list[DPRSpanPrediction]:
+ """
+ Finds the best answer span for the extractive Q&A model for one passage. It returns the best span by descending
+ `span_score` order and keeping max `top_spans` spans. Spans longer that `max_answer_length` are ignored.
+ """
+ scores = []
+ for start_index, start_score in enumerate(start_logits):
+ for answer_length, end_score in enumerate(end_logits[start_index : start_index + max_answer_length]):
+ scores.append(((start_index, start_index + answer_length), start_score + end_score))
+ scores = sorted(scores, key=lambda x: x[1], reverse=True)
+ chosen_span_intervals = []
+ for (start_index, end_index), score in scores:
+ assert start_index <= end_index, f"Wrong span indices: [{start_index}:{end_index}]"
+ length = end_index - start_index + 1
+ assert length <= max_answer_length, f"Span is too long: {length} > {max_answer_length}"
+ if any(
+ start_index <= prev_start_index <= prev_end_index <= end_index
+ or prev_start_index <= start_index <= end_index <= prev_end_index
+ for (prev_start_index, prev_end_index) in chosen_span_intervals
+ ):
+ continue
+ chosen_span_intervals.append((start_index, end_index))
+
+ if len(chosen_span_intervals) == top_spans:
+ break
+ return chosen_span_intervals
+
+
+@add_end_docstrings(CUSTOM_DPR_READER_DOCSTRING)
+class DPRReaderTokenizerFast(CustomDPRReaderTokenizerMixin, BertTokenizer):
+ r"""
+ Constructs a "fast" DPRReader tokenizer (backed by HuggingFace's *tokenizers* library).
+
+ [`DPRReaderTokenizerFast`] is almost identical to [`BertTokenizer`] and runs end-to-end tokenization:
+ punctuation splitting and wordpiece. The difference is that is has three inputs strings: question, titles and texts
+ that are combined to be fed to the [`DPRReader`] model.
+
+ Refer to superclass [`BertTokenizer`] for usage examples and documentation concerning parameters.
+
+ """
+
+ vocab_files_names = VOCAB_FILES_NAMES
+ model_input_names = ["input_ids", "attention_mask"]
+ slow_tokenizer_class = DPRReaderTokenizer
+
+
+__all__ = ["DPRContextEncoderTokenizerFast", "DPRQuestionEncoderTokenizerFast", "DPRReaderTokenizerFast"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/efficientnet/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/efficientnet/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d838688aa3f97e714eab3f4e02ba9f3079dd7204
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/efficientnet/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/efficientnet/__pycache__/configuration_efficientnet.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/efficientnet/__pycache__/configuration_efficientnet.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fd9b28b2af24489d978adef2bc6ff5891e0c8b30
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/efficientnet/__pycache__/configuration_efficientnet.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/efficientnet/__pycache__/image_processing_efficientnet.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/efficientnet/__pycache__/image_processing_efficientnet.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6c30d34a63ffa1310b453e759032901dcc95ccb3
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/efficientnet/__pycache__/image_processing_efficientnet.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/efficientnet/__pycache__/image_processing_pil_efficientnet.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/efficientnet/__pycache__/image_processing_pil_efficientnet.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9721adba42166338c838dccc95ef089d2e72f382
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/efficientnet/__pycache__/image_processing_pil_efficientnet.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/efficientnet/__pycache__/modeling_efficientnet.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/efficientnet/__pycache__/modeling_efficientnet.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..315f80915ed00e2d8baea376d56c7a873a6b2abe
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/efficientnet/__pycache__/modeling_efficientnet.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/electra/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/electra/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3f3c7630686428357171711b76d94743fe37c750
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/electra/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/electra/__pycache__/configuration_electra.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/electra/__pycache__/configuration_electra.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..579ae3e1481aa2177abb556682c94bae6d10f070
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/electra/__pycache__/configuration_electra.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/electra/__pycache__/modeling_electra.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/electra/__pycache__/modeling_electra.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..94af0b2336efb3b4074050ec1ceccf09f0c6800e
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/electra/__pycache__/modeling_electra.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/eomt_dinov3/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/eomt_dinov3/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..10e4ae987f7dd7642a190d594be313a98f955713
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/eomt_dinov3/__init__.py
@@ -0,0 +1,28 @@
+# Copyright 2026 the HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_eomt_dinov3 import *
+ from .modeling_eomt_dinov3 import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/eomt_dinov3/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/eomt_dinov3/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..313a0fc9525323be9cc64d20930741f78efc2982
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/eomt_dinov3/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/eomt_dinov3/__pycache__/configuration_eomt_dinov3.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/eomt_dinov3/__pycache__/configuration_eomt_dinov3.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0f77666777f28f57704c86382915b095f00d5e58
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/eomt_dinov3/__pycache__/configuration_eomt_dinov3.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/eomt_dinov3/__pycache__/modeling_eomt_dinov3.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/eomt_dinov3/__pycache__/modeling_eomt_dinov3.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a18ef40a473a88983f56d267a068a1697be1bec9
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/eomt_dinov3/__pycache__/modeling_eomt_dinov3.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/eomt_dinov3/__pycache__/modular_eomt_dinov3.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/eomt_dinov3/__pycache__/modular_eomt_dinov3.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bad3b8c5a611f33c7b2c7b2336bd04259da46a1f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/eomt_dinov3/__pycache__/modular_eomt_dinov3.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/eomt_dinov3/configuration_eomt_dinov3.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/eomt_dinov3/configuration_eomt_dinov3.py
new file mode 100644
index 0000000000000000000000000000000000000000..93f6350f26d2e08c5faf36ae5079b451bc3becc7
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/eomt_dinov3/configuration_eomt_dinov3.py
@@ -0,0 +1,107 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/eomt_dinov3/modular_eomt_dinov3.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_eomt_dinov3.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2026 the HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...modeling_rope_utils import RopeParameters
+from ...utils import auto_docstring
+
+
+@auto_docstring(checkpoint="tue-mps/coco_panoptic_eomt_large_640_dinov3")
+@strict
+class EomtDinov3Config(PreTrainedConfig):
+ r"""
+ layerscale_value (`float`, *optional*, defaults to 1.0):
+ Initial value for the LayerScale parameter.
+ num_upscale_blocks (`int`, *optional*, defaults to 2):
+ Number of upsampling blocks used in the decoder or segmentation head.
+ num_blocks (`int`, *optional*, defaults to 4):
+ Number of feature blocks or stages in the architecture.
+ no_object_weight (`float`, *optional*, defaults to 0.1):
+ Loss weight for the "no object" class in panoptic/instance segmentation.
+ train_num_points (`int`, *optional*, defaults to 12544):
+ Number of points to sample for mask loss computation during training.
+ oversample_ratio (`float`, *optional*, defaults to 3.0):
+ Oversampling ratio used in point sampling for mask training.
+ importance_sample_ratio (`float`, *optional*, defaults to 0.75):
+ Ratio of points to sample based on importance during training.
+ num_queries (`int`, *optional*, defaults to 200):
+ Number of object queries in the Transformer.
+ num_register_tokens (`int`, *optional*, defaults to 4):
+ Number of learnable register tokens added to the transformer input.
+ query_bias (`bool`, *optional*, defaults to `True`):
+ Whether to use bias in query projection.
+ key_bias (`bool`, *optional*, defaults to `False`):
+ Whether to use bias in key projection.
+ value_bias (`bool`, *optional*, defaults to `True`):
+ Whether to use bias in value projection.
+ proj_bias (`bool`, *optional*, defaults to `True`):
+ Whether to use bias in output projection.
+ use_gated_mlp (`bool`, *optional*, defaults to `False`):
+ Whether to use gated MLP layers.
+ pos_embed_shift (`float`, *optional*):
+ Shift value for position embeddings.
+ pos_embed_jitter (`float`, *optional*):
+ Jitter value for position embeddings.
+ pos_embed_rescale (`float`, *optional*, defaults to 2.0):
+ Rescale value for position embeddings.
+ """
+
+ model_type = "eomt_dinov3"
+
+ hidden_size: int = 1024
+ num_hidden_layers: int = 24
+ num_attention_heads: int = 16
+ hidden_act: str = "gelu"
+ hidden_dropout_prob: float | int = 0.0
+ initializer_range: float = 0.02
+ layer_norm_eps: float = 1e-6
+ image_size: int | list[int] | tuple[int, int] = 640
+ patch_size: int | list[int] | tuple[int, int] = 16
+ num_channels: int = 3
+ layerscale_value: float = 1.0
+ drop_path_rate: float | int = 0.0
+ num_upscale_blocks: int = 2
+ attention_dropout: float | int = 0.0
+ num_blocks: int = 4
+ no_object_weight: float = 0.1
+ class_weight: float = 2.0
+ mask_weight: float = 5.0
+ dice_weight: float = 5.0
+ train_num_points: int = 12544
+ oversample_ratio: float = 3.0
+ importance_sample_ratio: float = 0.75
+ num_queries: int = 200
+ num_register_tokens: int = 4
+ default_theta = 100.0
+ intermediate_size: int = 4096
+ rope_parameters: RopeParameters | dict | None = None
+ query_bias: bool = True
+ key_bias: bool = False
+ value_bias: bool = True
+ proj_bias: bool = True
+ mlp_bias: bool = True
+ use_gated_mlp: bool = False
+ pos_embed_shift: float | None = None
+ pos_embed_jitter: float | None = None
+ pos_embed_rescale: float | None = 2.0
+
+
+__all__ = ["EomtDinov3Config"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/eomt_dinov3/modeling_eomt_dinov3.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/eomt_dinov3/modeling_eomt_dinov3.py
new file mode 100644
index 0000000000000000000000000000000000000000..18d2c37f042c2f87ee6a50940163b44dd7b7b922
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/eomt_dinov3/modeling_eomt_dinov3.py
@@ -0,0 +1,1374 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/eomt_dinov3/modular_eomt_dinov3.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_eomt_dinov3.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2026 the HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import math
+from collections.abc import Callable
+from dataclasses import dataclass
+from typing import Optional
+
+import numpy as np
+import torch
+import torch.nn.functional as F
+from torch import Tensor, nn
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...file_utils import ModelOutput, is_scipy_available, requires_backends
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
+from ...processing_utils import Unpack
+from ...pytorch_utils import compile_compatible_method_lru_cache
+from ...utils import TransformersKwargs, auto_docstring, is_accelerate_available
+from ...utils.generic import maybe_autocast, merge_with_config_defaults
+from ...utils.output_capturing import capture_outputs
+from .configuration_eomt_dinov3 import EomtDinov3Config
+
+
+if is_scipy_available():
+ from scipy.optimize import linear_sum_assignment
+
+if is_accelerate_available():
+ from accelerate import PartialState
+ from accelerate.utils import reduce
+
+
+def rotate_half(x):
+ """Rotates half the hidden dims of the input."""
+ x1 = x[..., : x.shape[-1] // 2]
+ x2 = x[..., x.shape[-1] // 2 :]
+ return torch.cat((-x2, x1), dim=-1)
+
+
+def eager_attention_forward(
+ module: nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: torch.Tensor | None,
+ scaling: float | None = None,
+ dropout: float = 0.0,
+ **kwargs: Unpack[TransformersKwargs],
+):
+ if scaling is None:
+ scaling = query.size(-1) ** -0.5
+
+ # Take the dot product between "query" and "key" to get the raw attention scores.
+ attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
+
+ if attention_mask is not None:
+ attn_weights = attn_weights + attention_mask
+
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
+
+ attn_output = torch.matmul(attn_weights, value)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+
+ return attn_output, attn_weights
+
+
+def apply_rotary_pos_emb(
+ q: torch.Tensor, k: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, **kwargs
+) -> tuple[torch.Tensor, torch.Tensor]:
+ """Applies Rotary Position Embedding to the query and key tensors, but only to the patch tokens,
+ ignoring the prefix tokens (cls token and register tokens).
+
+ Args:
+ q (`torch.Tensor`): The query tensor.
+ k (`torch.Tensor`): The key tensor.
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
+
+ Returns:
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
+ """
+
+ num_tokens = q.shape[-2]
+ num_patches = sin.shape[-2]
+ num_prefix_tokens = num_tokens - num_patches # cls token + register tokens
+
+ q_prefix_tokens, q_patches = q.split((num_prefix_tokens, num_patches), dim=-2)
+ k_prefix_tokens, k_patches = k.split((num_prefix_tokens, num_patches), dim=-2)
+
+ # apply rope only to patch tokens
+ q_patches = (q_patches * cos) + (rotate_half(q_patches) * sin)
+ k_patches = (k_patches * cos) + (rotate_half(k_patches) * sin)
+
+ q = torch.cat((q_prefix_tokens, q_patches), dim=-2)
+ k = torch.cat((k_prefix_tokens, k_patches), dim=-2)
+
+ return q, k
+
+
+class EomtDinov3Attention(nn.Module):
+ """
+ Multi-headed attention compatible with ALL_ATTENTION_FUNCTIONS.
+ """
+
+ def __init__(self, config: EomtDinov3Config):
+ super().__init__()
+ self.config = config
+ self.embed_dim = config.hidden_size
+ self.num_heads = config.num_attention_heads
+ self.head_dim = self.embed_dim // self.num_heads
+ self.is_causal = False
+
+ self.scaling = self.head_dim**-0.5
+ self.is_causal = False
+
+ self.dropout = config.attention_dropout
+ self.k_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.key_bias)
+ self.v_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.value_bias)
+
+ self.q_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.query_bias)
+ self.o_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.proj_bias)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor | None = None,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor, torch.Tensor | None]:
+ """Input shape: Batch x Time x Channel"""
+
+ batch_size, patches, _ = hidden_states.size()
+
+ query_states = self.q_proj(hidden_states)
+ key_states = self.k_proj(hidden_states)
+ value_states = self.v_proj(hidden_states)
+
+ query_states = query_states.view(batch_size, patches, self.num_heads, self.head_dim).transpose(1, 2)
+ key_states = key_states.view(batch_size, patches, self.num_heads, self.head_dim).transpose(1, 2)
+ value_states = value_states.view(batch_size, patches, self.num_heads, self.head_dim).transpose(1, 2)
+
+ cos, sin = position_embeddings
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_states,
+ key_states,
+ value_states,
+ attention_mask,
+ dropout=0.0 if not self.training else self.dropout,
+ scaling=self.scaling,
+ **kwargs,
+ )
+
+ attn_output = attn_output.reshape(batch_size, patches, -1).contiguous()
+ attn_output = self.o_proj(attn_output)
+
+ return attn_output, attn_weights
+
+
+class EomtDinov3Embeddings(nn.Module):
+ """
+ Construct the CLS token, mask token, position and patch embeddings.
+ """
+
+ def __init__(self, config: EomtDinov3Config):
+ super().__init__()
+ self.config = config
+ self.cls_token = nn.Parameter(torch.randn(1, 1, config.hidden_size))
+ self.mask_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
+ self.register_tokens = nn.Parameter(torch.empty(1, config.num_register_tokens, config.hidden_size))
+ self.patch_embeddings = nn.Conv2d(
+ config.num_channels, config.hidden_size, kernel_size=config.patch_size, stride=config.patch_size
+ )
+ self.num_prefix_tokens = 1 + config.num_register_tokens
+
+ def forward(self, pixel_values: torch.Tensor, bool_masked_pos: torch.Tensor | None = None) -> torch.Tensor:
+ batch_size = pixel_values.shape[0]
+ target_dtype = self.patch_embeddings.weight.dtype
+
+ # (batch_size, num_channels, height, width) -> (batch_size, num_patches, hidden_size)
+ patch_embeddings = self.patch_embeddings(pixel_values.to(dtype=target_dtype))
+ patch_embeddings = patch_embeddings.flatten(2).transpose(1, 2)
+
+ if bool_masked_pos is not None:
+ mask_token = self.mask_token.to(patch_embeddings.dtype)
+ patch_embeddings = torch.where(bool_masked_pos.unsqueeze(-1), mask_token, patch_embeddings)
+
+ # Add CLS and register tokens
+ cls_token = self.cls_token.expand(batch_size, -1, -1)
+ register_tokens = self.register_tokens.expand(batch_size, -1, -1)
+ embeddings = torch.cat([cls_token, register_tokens, patch_embeddings], dim=1)
+
+ return embeddings
+
+
+class EomtDinov3MLP(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.hidden_size = config.hidden_size
+ self.intermediate_size = config.intermediate_size
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
+ self.act_fn = ACT2FN[config.hidden_act]
+
+ def forward(self, x):
+ return self.down_proj(self.act_fn(self.up_proj(x)))
+
+
+class EomtDinov3GatedMLP(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.hidden_size = config.hidden_size
+ self.intermediate_size = config.intermediate_size
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
+ self.act_fn = ACT2FN[config.hidden_act]
+
+ def forward(self, x):
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
+ return down_proj
+
+
+class EomtDinov3DropPath(nn.Module):
+ """Stochastic depth (DropPath) per sample, for residual blocks.
+
+ Identity when ``drop_prob`` is 0 or outside training. See `Deep Networks with Stochastic Depth
+ `_.
+ """
+
+ def __init__(self, drop_prob: float = 0.0) -> None:
+ super().__init__()
+ self.drop_prob = drop_prob
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ if self.drop_prob == 0.0 or not self.training:
+ return hidden_states
+ keep_prob = 1 - self.drop_prob
+ shape = (hidden_states.shape[0],) + (1,) * (hidden_states.ndim - 1)
+ random_tensor = torch.rand(shape, dtype=hidden_states.dtype, device=hidden_states.device)
+ random_tensor = torch.floor(random_tensor + keep_prob)
+ return hidden_states.div(keep_prob) * random_tensor
+
+ def extra_repr(self) -> str:
+ return f"p={self.drop_prob}"
+
+
+class EomtDinov3Layer(GradientCheckpointingLayer):
+ """This corresponds to the Block class in the original implementation."""
+
+ def __init__(self, config: EomtDinov3Config):
+ super().__init__()
+
+ self.norm1 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.attention = EomtDinov3Attention(config)
+ self.layer_scale1 = EomtDinov3LayerScale(config)
+ self.drop_path = EomtDinov3DropPath(config.drop_path_rate) if config.drop_path_rate > 0.0 else nn.Identity()
+
+ self.norm2 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+
+ if config.use_gated_mlp:
+ self.mlp = EomtDinov3GatedMLP(config)
+ else:
+ self.mlp = EomtDinov3MLP(config)
+ self.layer_scale2 = EomtDinov3LayerScale(config)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor | None = None,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.Tensor:
+ # Attention with residual connection
+ residual = hidden_states
+ hidden_states = self.norm1(hidden_states)
+ hidden_states, _ = self.attention(
+ hidden_states,
+ attention_mask=attention_mask,
+ position_embeddings=position_embeddings,
+ **kwargs,
+ )
+ hidden_states = self.layer_scale1(hidden_states)
+ hidden_states = self.drop_path(hidden_states) + residual
+
+ # MLP with residual connection
+ residual = hidden_states
+ hidden_states = self.norm2(hidden_states)
+ hidden_states = self.mlp(hidden_states)
+ hidden_states = self.layer_scale2(hidden_states)
+ hidden_states = self.drop_path(hidden_states) + residual
+
+ return hidden_states
+
+
+class EomtDinov3LayerScale(nn.Module):
+ def __init__(self, config) -> None:
+ super().__init__()
+ self.lambda1 = nn.Parameter(config.layerscale_value * torch.ones(config.hidden_size))
+
+ def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
+ return hidden_state * self.lambda1
+
+
+@compile_compatible_method_lru_cache(maxsize=32)
+def get_patches_center_coordinates(
+ num_patches_h: int, num_patches_w: int, dtype: torch.dtype, device: torch.device
+) -> torch.Tensor:
+ """
+ Computes the 2D coordinates of the centers of image patches, normalized to the range [-1, +1].
+ The center of each patch is exactly halfway between its top-left and bottom-right corners.
+
+ Args:
+ num_patches_h (int): Number of patches along the vertical (height) axis.
+ num_patches_w (int): Number of patches along the horizontal (width) axis.
+ dtype (torch.dtype): The desired data type of the returned tensor.
+
+ Returns:
+ torch.Tensor: A tensor of shape (height * width, 2), where each row contains the (y, x)
+ coordinates of a patch center, normalized to [-1, +1].
+ """
+ coords_h = torch.arange(0.5, num_patches_h, dtype=dtype, device=device)
+ coords_w = torch.arange(0.5, num_patches_w, dtype=dtype, device=device)
+ coords_h = coords_h / num_patches_h
+ coords_w = coords_w / num_patches_w
+ # (height, width, 2) -> (height * width, 2)
+ coords = torch.stack(torch.meshgrid(coords_h, coords_w, indexing="ij"), dim=-1)
+ coords = coords.flatten(0, 1)
+ # Shift range [0, 1] to [-1, +1]
+ coords = 2.0 * coords - 1.0
+ return coords
+
+
+def augment_patches_center_coordinates(
+ coords: torch.Tensor,
+ shift: float | None = None,
+ jitter: float | None = None,
+ rescale: float | None = None,
+) -> torch.Tensor:
+ # Shift coords by adding a uniform value in [-shift, shift]
+ if shift is not None:
+ shift_hw = torch.empty((1, 2), device=coords.device, dtype=coords.dtype)
+ shift_hw = shift_hw.uniform_(-shift, shift)
+ coords = coords + shift_hw
+
+ # Jitter coords by multiplying the range [-1, 1] by a log-uniform value in [1/jitter, jitter]
+ if jitter is not None:
+ jitter_range = np.log(jitter)
+ jitter_hw = torch.empty((1, 2), device=coords.device, dtype=coords.dtype)
+ jitter_hw = jitter_hw.uniform_(-jitter_range, jitter_range).exp()
+ coords = coords * jitter_hw
+
+ # Rescale coords by multiplying the range [-1, 1] by a log-uniform value in [1/rescale, rescale]
+ if rescale is not None:
+ rescale_range = np.log(rescale)
+ rescale_hw = torch.empty(1, device=coords.device, dtype=coords.dtype)
+ rescale_hw = rescale_hw.uniform_(-rescale_range, rescale_range).exp()
+ coords = coords * rescale_hw
+
+ return coords
+
+
+class EomtDinov3RotaryEmbedding(nn.Module):
+ inv_freq: Tensor
+
+ def __init__(self, config: EomtDinov3Config, device=None):
+ super().__init__()
+ self.config = config
+
+ self.rope_type = self.config.rope_parameters["rope_type"]
+ rope_init_fn: Callable = self.compute_default_rope_parameters
+ if self.rope_type != "default":
+ raise ValueError("`EomtDinov3` only supports `default` RoPE! Please check your `rope_type`")
+ inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
+
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
+ self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
+
+ def forward(self, pixel_values: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
+ _, _, height, width = pixel_values.shape
+ num_patches_h = height // self.config.patch_size
+ num_patches_w = width // self.config.patch_size
+
+ device = pixel_values.device
+ device_type = device.type if isinstance(device.type, str) and device.type != "mps" else "cpu"
+
+ with maybe_autocast(device_type=device_type, enabled=False): # Force float32
+ # Although we could precompute static patch_coords from image_size and patch_size in the config,
+ # the model was trained with random_scale, so it can process images of varying sizes.
+ # Therefore, it's better to compute patch_coords dynamically (with lru_cache).
+ patch_coords = get_patches_center_coordinates(
+ num_patches_h, num_patches_w, dtype=torch.float32, device=device
+ )
+ if self.training:
+ patch_coords = augment_patches_center_coordinates(
+ patch_coords,
+ shift=self.config.pos_embed_shift,
+ jitter=self.config.pos_embed_jitter,
+ rescale=self.config.pos_embed_rescale,
+ )
+
+ # (height * width, 2, head_dim / 4) -> (height * width, head_dim / 2) -> (height * width, head_dim)
+ angles = 2 * math.pi * patch_coords[:, :, None] * self.inv_freq[None, None, :]
+ angles = angles.flatten(1, 2)
+ angles = angles.tile(2)
+
+ cos = torch.cos(angles)
+ sin = torch.sin(angles)
+
+ dtype = pixel_values.dtype
+ return cos.to(dtype=dtype), sin.to(dtype=dtype)
+
+ @staticmethod
+ def compute_default_rope_parameters(
+ config: EomtDinov3Config | None = None,
+ device: Optional["torch.device"] = None,
+ seq_len: int | None = None,
+ ) -> torch.Tensor:
+ """
+ Computes the inverse frequencies according to the original RoPE implementation
+ Args:
+ config ([`~transformers.PreTrainedConfig`]):
+ The model configuration.
+ device (`torch.device`):
+ The device to use for initialization of the inverse frequencies.
+ seq_len (`int`, *optional*):
+ The current sequence length. Unused for this type of RoPE.
+ Returns:
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
+ """
+ base = config.rope_parameters["rope_theta"]
+ head_dim = config.hidden_size // config.num_attention_heads
+
+ attention_factor = 1.0 # Unused in this type of RoPE
+
+ # Compute the inverse frequencies
+ inv_freq = 1 / base ** torch.arange(0, 1, 4 / head_dim, dtype=torch.float32, device=device)
+ return inv_freq, attention_factor
+
+
+# Adapted from https://github.com/facebookresearch/detectron2/blob/main/projects/PointRend/point_rend/point_features.py
+def sample_point(
+ input_features: torch.Tensor, point_coordinates: torch.Tensor, add_dim=False, **kwargs
+) -> torch.Tensor:
+ """
+ A wrapper around `torch.nn.functional.grid_sample` to support 3D point_coordinates tensors.
+
+ Args:
+ input_features (`torch.Tensor` of shape (batch_size, channels, height, width)):
+ A tensor that contains features map on a height * width grid
+ point_coordinates (`torch.Tensor` of shape (batch_size, num_points, 2) or (batch_size, grid_height, grid_width,:
+ 2)):
+ A tensor that contains [0, 1] * [0, 1] normalized point coordinates
+ add_dim (`bool`):
+ boolean value to keep track of added dimension
+
+ Returns:
+ point_features (`torch.Tensor` of shape (batch_size, channels, num_points) or (batch_size, channels,
+ height_grid, width_grid):
+ A tensor that contains features for points in `point_coordinates`.
+ """
+ if point_coordinates.dim() == 3:
+ add_dim = True
+ point_coordinates = point_coordinates.unsqueeze(2)
+
+ # use nn.function.grid_sample to get features for points in `point_coordinates` via bilinear interpolation
+ point_features = torch.nn.functional.grid_sample(input_features, 2.0 * point_coordinates - 1.0, **kwargs)
+ if add_dim:
+ point_features = point_features.squeeze(3)
+
+ return point_features
+
+
+def pair_wise_dice_loss(inputs: Tensor, labels: Tensor) -> Tensor:
+ """
+ A pair wise version of the dice loss, see `dice_loss` for usage.
+
+ Args:
+ inputs (`torch.Tensor`):
+ A tensor representing a mask
+ labels (`torch.Tensor`):
+ A tensor with the same shape as inputs. Stores the binary classification labels for each element in inputs
+ (0 for the negative class and 1 for the positive class).
+
+ Returns:
+ `torch.Tensor`: The computed loss between each pairs.
+ """
+ inputs = inputs.sigmoid().flatten(1)
+ numerator = 2 * torch.matmul(inputs, labels.T)
+ # using broadcasting to get a [num_queries, NUM_CLASSES] matrix
+ denominator = inputs.sum(-1)[:, None] + labels.sum(-1)[None, :]
+ loss = 1 - (numerator + 1) / (denominator + 1)
+ return loss
+
+
+def pair_wise_sigmoid_cross_entropy_loss(inputs: torch.Tensor, labels: torch.Tensor) -> torch.Tensor:
+ r"""
+ A pair wise version of the cross entropy loss, see `sigmoid_cross_entropy_loss` for usage.
+
+ Args:
+ inputs (`torch.Tensor`):
+ A tensor representing a mask.
+ labels (`torch.Tensor`):
+ A tensor with the same shape as inputs. Stores the binary classification labels for each element in inputs
+ (0 for the negative class and 1 for the positive class).
+
+ Returns:
+ loss (`torch.Tensor`): The computed loss between each pairs.
+ """
+
+ height_and_width = inputs.shape[1]
+
+ criterion = nn.BCEWithLogitsLoss(reduction="none")
+ cross_entropy_loss_pos = criterion(inputs, torch.ones_like(inputs))
+ cross_entropy_loss_neg = criterion(inputs, torch.zeros_like(inputs))
+
+ loss_pos = torch.matmul(cross_entropy_loss_pos / height_and_width, labels.T)
+ loss_neg = torch.matmul(cross_entropy_loss_neg / height_and_width, (1 - labels).T)
+ loss = loss_pos + loss_neg
+ return loss
+
+
+# Adapted from https://github.com/facebookresearch/EomtDinov3/blob/main/eomt_dinov3/modeling/matcher.py
+class EomtDinov3HungarianMatcher(nn.Module):
+ """This class computes an assignment between the labels and the predictions of the network.
+
+ For efficiency reasons, the labels don't include the no_object. Because of this, in general, there are more
+ predictions than labels. In this case, we do a 1-to-1 matching of the best predictions, while the others are
+ un-matched (and thus treated as non-objects).
+ """
+
+ def __init__(
+ self, cost_class: float = 1.0, cost_mask: float = 1.0, cost_dice: float = 1.0, num_points: int = 12544
+ ):
+ """Creates the matcher
+
+ Params:
+ cost_class (`float`, *optional*, defaults to 1.0):
+ Relative weight of the classification error in the matching cost.
+ cost_mask (`float`, *optional*, defaults to 1.0):
+ This is the relative weight of the focal loss of the binary mask in the matching cost.
+ cost_dice (`float`, *optional*, defaults to 1.0):
+ This is the relative weight of the dice loss of the binary mask in the matching cost.
+ num_points (`int`, *optional*, defaults to 12544):
+ No. of points to sample on which the mask loss will be calculated. The same set of K points are
+ uniformly sampled for all prediction and ground truth masks to construct the cost matrix for bipartite
+ matching.
+ """
+ super().__init__()
+ if cost_class == 0 and cost_mask == 0 and cost_dice == 0:
+ raise ValueError("All costs can't be 0")
+
+ self.num_points = num_points
+ self.cost_class = cost_class
+ self.cost_mask = cost_mask
+ self.cost_dice = cost_dice
+
+ @torch.no_grad()
+ def forward(
+ self,
+ masks_queries_logits: torch.Tensor,
+ class_queries_logits: torch.Tensor,
+ mask_labels: torch.Tensor,
+ class_labels: torch.Tensor,
+ ) -> list[tuple[Tensor]]:
+ """
+ Params:
+ masks_queries_logits (`torch.Tensor`):
+ A tensor of dim `batch_size, num_queries, num_labels` with the classification logits.
+ class_queries_logits (`torch.Tensor`):
+ A tensor of dim `batch_size, num_queries, height, width` with the predicted masks.
+ class_labels (`torch.Tensor`):
+ A tensor of dim `num_target_boxes` (where num_target_boxes is the number of ground-truth objects in the
+ target) containing the class labels.
+ mask_labels (`torch.Tensor`):
+ A tensor of dim `num_target_boxes, height, width` containing the target masks.
+
+ Returns:
+ matched_indices (`list[tuple[Tensor]]`): A list of size batch_size, containing tuples of (index_i, index_j)
+ where:
+ - index_i is the indices of the selected predictions (in order)
+ - index_j is the indices of the corresponding selected labels (in order)
+ For each batch element, it holds:
+ len(index_i) = len(index_j) = min(num_queries, num_target_boxes).
+ """
+ indices: list[tuple[np.array]] = []
+
+ # iterate through batch size
+ batch_size = masks_queries_logits.shape[0]
+ for i in range(batch_size):
+ pred_probs = class_queries_logits[i].softmax(-1)
+ pred_mask = masks_queries_logits[i]
+
+ # Compute the classification cost. Contrary to the loss, we don't use the NLL, but approximate it in 1 - proba[target class]. The 1 is a constant that doesn't change the matching, it can be omitted.
+ cost_class = -pred_probs[:, class_labels[i]]
+ target_mask = mask_labels[i].to(pred_mask)
+ target_mask = target_mask[:, None]
+ pred_mask = pred_mask[:, None]
+
+ # Sample ground truth and predicted masks
+ point_coordinates = torch.rand(1, self.num_points, 2, device=pred_mask.device)
+
+ target_coordinates = point_coordinates.repeat(target_mask.shape[0], 1, 1)
+ target_mask = sample_point(target_mask, target_coordinates, align_corners=False).squeeze(1)
+
+ pred_coordinates = point_coordinates.repeat(pred_mask.shape[0], 1, 1)
+ pred_mask = sample_point(pred_mask, pred_coordinates, align_corners=False).squeeze(1)
+
+ # compute the cross entropy loss between each mask pairs -> shape (num_queries, num_labels)
+ cost_mask = pair_wise_sigmoid_cross_entropy_loss(pred_mask, target_mask)
+ # Compute the dice loss between each mask pairs -> shape (num_queries, num_labels)
+ cost_dice = pair_wise_dice_loss(pred_mask, target_mask)
+ # final cost matrix
+ cost_matrix = self.cost_mask * cost_mask + self.cost_class * cost_class + self.cost_dice * cost_dice
+ # eliminate infinite values in cost_matrix to avoid the error ``ValueError: cost matrix is infeasible``
+ cost_matrix = torch.minimum(cost_matrix, torch.tensor(1e10))
+ cost_matrix = torch.maximum(cost_matrix, torch.tensor(-1e10))
+ cost_matrix = torch.nan_to_num(cost_matrix, 0)
+ # do the assignment using the hungarian algorithm in scipy
+ assigned_indices: tuple[np.array] = linear_sum_assignment(cost_matrix.cpu())
+ indices.append(assigned_indices)
+
+ # It could be stacked in one tensor
+ matched_indices = [
+ (torch.as_tensor(i, dtype=torch.int64), torch.as_tensor(j, dtype=torch.int64)) for i, j in indices
+ ]
+ return matched_indices
+
+
+def dice_loss(inputs: Tensor, labels: Tensor, num_masks: int) -> Tensor:
+ r"""
+ Compute the DICE loss, similar to generalized IOU for masks as follows:
+
+ $$ \mathcal{L}_{\text{dice}(x, y) = 1 - \frac{2 * x \cap y }{x \cup y + 1}} $$
+
+ In practice, since `labels` is a binary mask, (only 0s and 1s), dice can be computed as follow
+
+ $$ \mathcal{L}_{\text{dice}(x, y) = 1 - \frac{2 * x * y }{x + y + 1}} $$
+
+ Args:
+ inputs (`torch.Tensor`):
+ A tensor representing a mask.
+ labels (`torch.Tensor`):
+ A tensor with the same shape as inputs. Stores the binary classification labels for each element in inputs
+ (0 for the negative class and 1 for the positive class).
+ num_masks (`int`):
+ The number of masks present in the current batch, used for normalization.
+
+ Returns:
+ `torch.Tensor`: The computed loss.
+ """
+ probs = inputs.sigmoid().flatten(1)
+ numerator = 2 * (probs * labels).sum(-1)
+ denominator = probs.sum(-1) + labels.sum(-1)
+ loss = 1 - (numerator + 1) / (denominator + 1)
+ loss = loss.sum() / num_masks
+ return loss
+
+
+def sigmoid_cross_entropy_loss(inputs: torch.Tensor, labels: torch.Tensor, num_masks: int) -> torch.Tensor:
+ r"""
+ Args:
+ inputs (`torch.Tensor`):
+ A float tensor of arbitrary shape.
+ labels (`torch.Tensor`):
+ A tensor with the same shape as inputs. Stores the binary classification labels for each element in inputs
+ (0 for the negative class and 1 for the positive class).
+
+ Returns:
+ loss (`torch.Tensor`): The computed loss.
+ """
+ criterion = nn.BCEWithLogitsLoss(reduction="none")
+ cross_entropy_loss = criterion(inputs, labels)
+
+ loss = cross_entropy_loss.mean(1).sum() / num_masks
+ return loss
+
+
+# Adapted from https://github.com/facebookresearch/EomtDinov3/blob/main/eomt_dinov3/modeling/criterion.py
+class EomtDinov3Loss(nn.Module):
+ def __init__(self, config: EomtDinov3Config, weight_dict: dict[str, float]):
+ """
+ The EomtDinov3 Loss. The loss is computed very similar to DETR. The process happens in two steps: 1) we
+ compute hungarian assignment between ground truth masks and the outputs of the model 2) we supervise each pair
+ of matched ground-truth / prediction (supervise class and mask)
+
+ Args:
+ config (`EomtDinov3Config`):
+ The configuration for EomtDinov3 model also containing loss calculation specific parameters.
+ weight_dict (`dict[str, float]`):
+ A dictionary of weights to be applied to the different losses.
+ """
+ super().__init__()
+ requires_backends(self, ["scipy"])
+ self.num_labels = config.num_labels
+ self.weight_dict = weight_dict
+
+ # Weight to apply to the null class
+ self.eos_coef = config.no_object_weight
+ empty_weight = torch.ones(self.num_labels + 1)
+ empty_weight[-1] = self.eos_coef
+ self.register_buffer("empty_weight", empty_weight)
+
+ # pointwise mask loss parameters
+ self.num_points = config.train_num_points
+ self.oversample_ratio = config.oversample_ratio
+ self.importance_sample_ratio = config.importance_sample_ratio
+
+ self.matcher = EomtDinov3HungarianMatcher(
+ cost_class=config.class_weight,
+ cost_dice=config.dice_weight,
+ cost_mask=config.mask_weight,
+ num_points=self.num_points,
+ )
+
+ def _max_by_axis(self, sizes: list[list[int]]) -> list[int]:
+ maxes = sizes[0]
+ for sublist in sizes[1:]:
+ for index, item in enumerate(sublist):
+ maxes[index] = max(maxes[index], item)
+ return maxes
+
+ # Adapted from nested_tensor_from_tensor_list() in original implementation
+ def _pad_images_to_max_in_batch(self, tensors: list[Tensor]) -> tuple[Tensor, Tensor]:
+ # get the maximum size in the batch
+ max_size = self._max_by_axis([list(tensor.shape) for tensor in tensors])
+ # compute final size
+ batch_shape = [len(tensors)] + max_size
+ batch_size, _, height, width = batch_shape
+ dtype = tensors[0].dtype
+ device = tensors[0].device
+ padded_tensors = torch.zeros(batch_shape, dtype=dtype, device=device)
+ padding_masks = torch.ones((batch_size, height, width), dtype=torch.bool, device=device)
+ # pad the tensors to the size of the biggest one
+ for tensor, padded_tensor, padding_mask in zip(tensors, padded_tensors, padding_masks):
+ padded_tensor[: tensor.shape[0], : tensor.shape[1], : tensor.shape[2]].copy_(tensor)
+ padding_mask[: tensor.shape[1], : tensor.shape[2]] = False
+
+ return padded_tensors, padding_masks
+
+ def loss_labels(
+ self, class_queries_logits: Tensor, class_labels: list[Tensor], indices: tuple[np.array]
+ ) -> dict[str, Tensor]:
+ """Compute the losses related to the labels using cross entropy.
+
+ Args:
+ class_queries_logits (`torch.Tensor`):
+ A tensor of shape `batch_size, num_queries, num_labels`
+ class_labels (`list[torch.Tensor]`):
+ List of class labels of shape `(labels)`.
+ indices (`tuple[np.array])`:
+ The indices computed by the Hungarian matcher.
+
+ Returns:
+ `dict[str, Tensor]`: A dict of `torch.Tensor` containing the following key:
+ - **loss_cross_entropy** -- The loss computed using cross entropy on the predicted and ground truth labels.
+ """
+ pred_logits = class_queries_logits
+ batch_size, num_queries, _ = pred_logits.shape
+ criterion = nn.CrossEntropyLoss(weight=self.empty_weight)
+ idx = self._get_predictions_permutation_indices(indices) # shape of (batch_size, num_queries)
+ target_classes_o = torch.cat(
+ [target[j] for target, (_, j) in zip(class_labels, indices)]
+ ) # shape of (batch_size, num_queries)
+ target_classes = torch.full(
+ (batch_size, num_queries), fill_value=self.num_labels, dtype=torch.int64, device=pred_logits.device
+ )
+ target_classes[idx] = target_classes_o
+ # Permute target_classes (batch_size, num_queries, num_labels) -> (batch_size, num_labels, num_queries)
+ pred_logits_transposed = pred_logits.transpose(1, 2)
+ loss_ce = criterion(pred_logits_transposed, target_classes)
+ losses = {"loss_cross_entropy": loss_ce}
+ return losses
+
+ def loss_masks(
+ self,
+ masks_queries_logits: torch.Tensor,
+ mask_labels: list[torch.Tensor],
+ indices: tuple[np.array],
+ num_masks: int,
+ ) -> dict[str, torch.Tensor]:
+ """Compute the losses related to the masks using sigmoid_cross_entropy_loss and dice loss.
+
+ Args:
+ masks_queries_logits (`torch.Tensor`):
+ A tensor of shape `(batch_size, num_queries, height, width)`.
+ mask_labels (`torch.Tensor`):
+ List of mask labels of shape `(labels, height, width)`.
+ indices (`tuple[np.array])`:
+ The indices computed by the Hungarian matcher.
+ num_masks (`int)`:
+ The number of masks, used for normalization.
+
+ Returns:
+ losses (`dict[str, Tensor]`): A dict of `torch.Tensor` containing two keys:
+ - **loss_mask** -- The loss computed using sigmoid cross entropy loss on the predicted and ground truth.
+ masks.
+ - **loss_dice** -- The loss computed using dice loss on the predicted on the predicted and ground truth,
+ masks.
+ """
+ src_idx = self._get_predictions_permutation_indices(indices)
+ tgt_idx = self._get_targets_permutation_indices(indices)
+ # shape (batch_size * num_queries, height, width)
+ pred_masks = masks_queries_logits[src_idx]
+ # shape (batch_size, num_queries, height, width)
+ # pad all and stack the targets to the num_labels dimension
+ target_masks, _ = self._pad_images_to_max_in_batch(mask_labels)
+ target_masks = target_masks[tgt_idx]
+
+ # No need to upsample predictions as we are using normalized coordinates
+ pred_masks = pred_masks[:, None]
+ target_masks = target_masks[:, None]
+
+ # Sample point coordinates
+ with torch.no_grad():
+ point_coordinates = self.sample_points_using_uncertainty(
+ pred_masks,
+ lambda logits: self.calculate_uncertainty(logits),
+ self.num_points,
+ self.oversample_ratio,
+ self.importance_sample_ratio,
+ )
+
+ point_labels = sample_point(target_masks, point_coordinates, align_corners=False).squeeze(1)
+
+ point_logits = sample_point(pred_masks, point_coordinates, align_corners=False).squeeze(1)
+
+ losses = {
+ "loss_mask": sigmoid_cross_entropy_loss(point_logits, point_labels, num_masks),
+ "loss_dice": dice_loss(point_logits, point_labels, num_masks),
+ }
+
+ del pred_masks
+ del target_masks
+ return losses
+
+ def _get_predictions_permutation_indices(self, indices):
+ # Permute predictions following indices
+ batch_indices = torch.cat([torch.full_like(src, i) for i, (src, _) in enumerate(indices)])
+ predictions_indices = torch.cat([src for (src, _) in indices])
+ return batch_indices, predictions_indices
+
+ def _get_targets_permutation_indices(self, indices):
+ # Permute labels following indices
+ batch_indices = torch.cat([torch.full_like(tgt, i) for i, (_, tgt) in enumerate(indices)])
+ target_indices = torch.cat([tgt for (_, tgt) in indices])
+ return batch_indices, target_indices
+
+ def calculate_uncertainty(self, logits: torch.Tensor) -> torch.Tensor:
+ """
+ In EomtDinov3 paper, uncertainty is estimated as L1 distance between 0.0 and the logit prediction in 'logits'
+ for the foreground class in `classes`.
+
+ Args:
+ logits (`torch.Tensor`):
+ A tensor of shape (R, 1, ...) for class-specific or class-agnostic, where R is the total number of predicted masks in all images and C is:
+ the number of foreground classes. The values are logits.
+
+ Returns:
+ scores (`torch.Tensor`): A tensor of shape (R, 1, ...) that contains uncertainty scores with the most
+ uncertain locations having the highest uncertainty score.
+ """
+ uncertainty_scores = -(torch.abs(logits))
+ return uncertainty_scores
+
+ def sample_points_using_uncertainty(
+ self,
+ logits: torch.Tensor,
+ uncertainty_function,
+ num_points: int,
+ oversample_ratio: int,
+ importance_sample_ratio: float,
+ ) -> torch.Tensor:
+ """
+ This function is meant for sampling points in [0, 1] * [0, 1] coordinate space based on their uncertainty. The
+ uncertainty is calculated for each point using the passed `uncertainty function` that takes points logit
+ prediction as input.
+
+ Args:
+ logits (`float`):
+ Logit predictions for P points.
+ uncertainty_function:
+ A function that takes logit predictions for P points and returns their uncertainties.
+ num_points (`int`):
+ The number of points P to sample.
+ oversample_ratio (`int`):
+ Oversampling parameter.
+ importance_sample_ratio (`float`):
+ Ratio of points that are sampled via importance sampling.
+
+ Returns:
+ point_coordinates (`torch.Tensor`):
+ Coordinates for P sampled points.
+ """
+
+ num_boxes = logits.shape[0]
+ num_points_sampled = int(num_points * oversample_ratio)
+
+ # Get random point coordinates
+ point_coordinates = torch.rand(num_boxes, num_points_sampled, 2, device=logits.device)
+ # Get sampled prediction value for the point coordinates
+ point_logits = sample_point(logits, point_coordinates, align_corners=False)
+ # Calculate the uncertainties based on the sampled prediction values of the points
+ point_uncertainties = uncertainty_function(point_logits)
+
+ num_uncertain_points = int(importance_sample_ratio * num_points)
+ num_random_points = num_points - num_uncertain_points
+
+ idx = torch.topk(point_uncertainties[:, 0, :], k=num_uncertain_points, dim=1)[1]
+ shift = num_points_sampled * torch.arange(num_boxes, dtype=torch.long, device=logits.device)
+ idx += shift[:, None]
+ point_coordinates = point_coordinates.view(-1, 2)[idx.view(-1), :].view(num_boxes, num_uncertain_points, 2)
+
+ if num_random_points > 0:
+ point_coordinates = torch.cat(
+ [point_coordinates, torch.rand(num_boxes, num_random_points, 2, device=logits.device)],
+ dim=1,
+ )
+ return point_coordinates
+
+ def forward(
+ self,
+ masks_queries_logits: torch.Tensor,
+ class_queries_logits: torch.Tensor,
+ mask_labels: list[torch.Tensor],
+ class_labels: list[torch.Tensor],
+ auxiliary_predictions: dict[str, torch.Tensor] | None = None,
+ ) -> dict[str, torch.Tensor]:
+ """
+ This performs the loss computation.
+
+ Args:
+ masks_queries_logits (`torch.Tensor`):
+ A tensor of shape `(batch_size, num_queries, height, width)`.
+ class_queries_logits (`torch.Tensor`):
+ A tensor of shape `(batch_size, num_queries, num_labels)`.
+ mask_labels (`torch.Tensor`):
+ List of mask labels of shape `(labels, height, width)`.
+ class_labels (`list[torch.Tensor]`):
+ List of class labels of shape `(labels)`.
+ auxiliary_predictions (`dict[str, torch.Tensor]`, *optional*):
+ if `use_auxiliary_loss` was set to `true` in [`EomtDinov3Config`], then it contains the logits from
+ the inner layers of the EomtDinov3MaskedAttentionDecoder.
+
+ Returns:
+ losses (`dict[str, Tensor]`): A dict of `torch.Tensor` containing three keys:
+ - **loss_cross_entropy** -- The loss computed using cross entropy on the predicted and ground truth labels.
+ - **loss_mask** -- The loss computed using sigmoid cross_entropy loss on the predicted and ground truth
+ masks.
+ - **loss_dice** -- The loss computed using dice loss on the predicted on the predicted and ground truth
+ masks.
+ if `use_auxiliary_loss` was set to `true` in [`EomtDinov3Config`], the dictionary contains additional
+ losses for each auxiliary predictions.
+ """
+
+ # retrieve the matching between the outputs of the last layer and the labels
+ indices = self.matcher(masks_queries_logits, class_queries_logits, mask_labels, class_labels)
+ # compute the average number of target masks for normalization purposes
+ num_masks = self.get_num_masks(class_labels, device=class_labels[0].device)
+ # get all the losses
+ losses: dict[str, Tensor] = {
+ **self.loss_masks(masks_queries_logits, mask_labels, indices, num_masks),
+ **self.loss_labels(class_queries_logits, class_labels, indices),
+ }
+ # in case of auxiliary losses, we repeat this process with the output of each intermediate layer.
+ if auxiliary_predictions is not None:
+ for idx, aux_outputs in enumerate(auxiliary_predictions):
+ masks_queries_logits = aux_outputs["masks_queries_logits"]
+ class_queries_logits = aux_outputs["class_queries_logits"]
+ loss_dict = self.forward(masks_queries_logits, class_queries_logits, mask_labels, class_labels)
+ loss_dict = {f"{key}_{idx}": value for key, value in loss_dict.items()}
+ losses.update(loss_dict)
+
+ return losses
+
+ def get_num_masks(self, class_labels: torch.Tensor, device: torch.device) -> torch.Tensor:
+ """
+ Computes the average number of target masks across the batch, for normalization purposes.
+ """
+ num_masks = sum(len(classes) for classes in class_labels)
+ num_masks = torch.as_tensor(num_masks, dtype=torch.float, device=device)
+ world_size = 1
+ if is_accelerate_available():
+ if PartialState._shared_state != {}:
+ num_masks = reduce(num_masks)
+ world_size = PartialState().num_processes
+
+ num_masks = torch.clamp(num_masks / world_size, min=1)
+ return num_masks
+
+
+@auto_docstring(
+ custom_intro="""
+ Class for outputs of [`EomtDinov3ForUniversalSegmentationOutput`].
+
+ This output can be directly passed to [`~EomtDinov3ImageProcessor.post_process_semantic_segmentation`] or
+ [`~EomtDinov3ImageProcessor.post_process_instance_segmentation`] or
+ [`~EomtDinov3ImageProcessor.post_process_panoptic_segmentation`] to compute final segmentation maps. Please, see
+ [`~EomtDinov3ImageProcessor] for details regarding usage.
+ """
+)
+@dataclass
+class EomtDinov3ForUniversalSegmentationOutput(ModelOutput):
+ r"""
+ loss (`torch.Tensor`, *optional*):
+ The computed loss, returned when labels are present.
+ class_queries_logits (`torch.FloatTensor`):
+ A tensor of shape `(batch_size, num_queries, num_labels + 1)` representing the proposed classes for each
+ query. Note the `+ 1` is needed because we incorporate the null class.
+ masks_queries_logits (`torch.FloatTensor`):
+ A tensor of shape `(batch_size, num_queries, height, width)` representing the proposed masks for each
+ query.
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
+ Last hidden states (final feature map) of the last layer.
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
+ shape `(batch_size, sequence_length, hidden_size)`. Hidden-states all layers of the model.
+ attentions (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
+ Tuple of `tuple(torch.FloatTensor)` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
+ sequence_length)`. Self and Cross Attentions weights from transformer decoder.
+ patch_offsets (`list[torch.Tensor]`, *optional*):
+ list of tuples indicating the image index and start and end positions of patches for semantic segmentation.
+ """
+
+ loss: torch.FloatTensor | None = None
+ class_queries_logits: torch.FloatTensor | None = None
+ masks_queries_logits: torch.FloatTensor | None = None
+ last_hidden_state: torch.FloatTensor | None = None
+ hidden_states: tuple[torch.FloatTensor] | None = None
+ attentions: tuple[torch.FloatTensor] | None = None
+ patch_offsets: list[torch.Tensor] | None = None
+
+
+@auto_docstring
+class EomtDinov3PreTrainedModel(PreTrainedModel):
+ """
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
+ models.
+ """
+
+ config: EomtDinov3Config
+ base_model_prefix = "eomt_dinov3"
+ main_input_name = "pixel_values"
+ input_modalities = ("image",)
+ supports_gradient_checkpointing = False
+ _no_split_modules = ["EomtDinov3Layer"]
+ _supports_sdpa = True
+ _can_record_outputs = {
+ "hidden_states": EomtDinov3Layer,
+ "attentions": EomtDinov3Attention,
+ }
+ config_class = EomtDinov3Config
+
+ @torch.no_grad()
+ def _init_weights(self, module: nn.Module) -> None:
+ super()._init_weights(module)
+ std = self.config.initializer_range
+ if isinstance(module, EomtDinov3LayerScale):
+ if hasattr(module, "lambda1"):
+ init.constant_(module.lambda1, self.config.layerscale_value)
+ elif isinstance(module, EomtDinov3Embeddings):
+ init.trunc_normal_(module.cls_token, mean=0.0, std=std)
+ init.zeros_(module.register_tokens)
+ elif isinstance(module, EomtDinov3Loss):
+ empty_weight = torch.ones(module.num_labels + 1)
+ empty_weight[-1] = module.eos_coef
+ init.copy_(module.empty_weight, empty_weight)
+ elif isinstance(module, EomtDinov3ForUniversalSegmentation):
+ init.ones_(module.attn_mask_probs)
+
+
+class EomtDinov3LayerNorm2d(nn.LayerNorm):
+ def __init__(self, num_channels, eps=1e-6, affine=True):
+ super().__init__(num_channels, eps=eps, elementwise_affine=affine)
+
+ def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
+ hidden_state = hidden_state.permute(0, 2, 3, 1)
+ hidden_state = F.layer_norm(hidden_state, self.normalized_shape, self.weight, self.bias, self.eps)
+ hidden_state = hidden_state.permute(0, 3, 1, 2)
+ return hidden_state
+
+
+class EomtDinov3ScaleLayer(nn.Module):
+ def __init__(self, config: EomtDinov3Config):
+ super().__init__()
+ hidden_size = config.hidden_size
+ self.conv1 = nn.ConvTranspose2d(hidden_size, hidden_size, kernel_size=2, stride=2)
+ self.activation = ACT2FN[config.hidden_act]
+ self.conv2 = nn.Conv2d(
+ hidden_size,
+ hidden_size,
+ kernel_size=3,
+ padding=1,
+ groups=hidden_size,
+ bias=False,
+ )
+
+ self.layernorm2d = EomtDinov3LayerNorm2d(hidden_size)
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.conv1(hidden_states)
+ hidden_states = self.activation(hidden_states)
+ hidden_states = self.conv2(hidden_states)
+ hidden_states = self.layernorm2d(hidden_states)
+ return hidden_states
+
+
+class EomtDinov3ScaleBlock(nn.Module):
+ def __init__(self, config: EomtDinov3Config):
+ super().__init__()
+ self.num_blocks = config.num_upscale_blocks
+ self.block = nn.ModuleList([EomtDinov3ScaleLayer(config) for _ in range(self.num_blocks)])
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ for block in self.block:
+ hidden_states = block(hidden_states)
+ return hidden_states
+
+
+class EomtDinov3MaskHead(nn.Module):
+ def __init__(self, config: EomtDinov3Config):
+ super().__init__()
+
+ hidden_size = config.hidden_size
+ self.fc1 = nn.Linear(hidden_size, hidden_size)
+ self.fc2 = nn.Linear(hidden_size, hidden_size)
+ self.fc3 = nn.Linear(hidden_size, hidden_size)
+ self.activation = ACT2FN[config.hidden_act]
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.activation(self.fc1(hidden_states))
+ hidden_states = self.activation(self.fc2(hidden_states))
+ hidden_states = self.fc3(hidden_states)
+ return hidden_states
+
+
+@auto_docstring(
+ custom_intro="""
+ The EoMT-DINOv3 model with head on top for instance/semantic/panoptic segmentation.
+ """,
+)
+class EomtDinov3ForUniversalSegmentation(EomtDinov3PreTrainedModel):
+ main_input_name = "pixel_values"
+
+ def __init__(self, config: EomtDinov3Config):
+ super().__init__(config)
+ self.config = config
+ self.num_hidden_layers = config.num_hidden_layers
+ self.embeddings = EomtDinov3Embeddings(config)
+ self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+
+ self.query = nn.Embedding(config.num_queries, config.hidden_size)
+ self.layers = nn.ModuleList([EomtDinov3Layer(config) for _ in range(config.num_hidden_layers)])
+
+ self.upscale_block = EomtDinov3ScaleBlock(config)
+ self.mask_head = EomtDinov3MaskHead(config)
+
+ self.class_predictor = nn.Linear(config.hidden_size, config.num_labels + 1)
+
+ self.grid_size = (config.image_size // config.patch_size, config.image_size // config.patch_size)
+ self.weight_dict: dict[str, float] = {
+ "loss_cross_entropy": config.class_weight,
+ "loss_mask": config.mask_weight,
+ "loss_dice": config.dice_weight,
+ }
+
+ self.criterion = EomtDinov3Loss(config=config, weight_dict=self.weight_dict)
+
+ self.register_buffer("attn_mask_probs", torch.ones(config.num_blocks))
+
+ self.num_prefix_tokens = 1 + config.num_register_tokens
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+ self.embeddings.register_parameter("mask_token", None)
+
+ self.rope_embeddings = EomtDinov3RotaryEmbedding(config)
+
+ self.post_init()
+
+ def get_loss_dict(
+ self,
+ masks_queries_logits: Tensor,
+ class_queries_logits: Tensor,
+ mask_labels: Tensor,
+ class_labels: Tensor,
+ auxiliary_predictions: dict[str, Tensor],
+ ) -> dict[str, Tensor]:
+ loss_dict: dict[str, Tensor] = self.criterion(
+ masks_queries_logits=masks_queries_logits,
+ class_queries_logits=class_queries_logits,
+ mask_labels=mask_labels,
+ class_labels=class_labels,
+ auxiliary_predictions=auxiliary_predictions,
+ )
+
+ # weight each loss by `self.weight_dict[]` including auxiliary losses
+ for key, weight in self.weight_dict.items():
+ for loss_key, loss in loss_dict.items():
+ if key in loss_key:
+ loss *= weight
+
+ return loss_dict
+
+ def get_loss(self, loss_dict: dict[str, Tensor]) -> Tensor:
+ return sum(loss_dict.values())
+
+ @merge_with_config_defaults
+ @capture_outputs
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: Tensor,
+ mask_labels: list[Tensor] | None = None,
+ class_labels: list[Tensor] | None = None,
+ patch_offsets: list[Tensor] | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> EomtDinov3ForUniversalSegmentationOutput:
+ r"""
+ mask_labels (`list[torch.Tensor]`, *optional*):
+ list of mask labels of shape `(num_labels, height, width)` to be fed to a model
+ class_labels (`list[torch.LongTensor]`, *optional*):
+ list of target class labels of shape `(num_labels, height, width)` to be fed to a model. They identify the
+ labels of `mask_labels`, e.g. the label of `mask_labels[i][j]` if `class_labels[i][j]`.
+ patch_offsets (`list[torch.Tensor]`, *optional*):
+ list of tuples indicating the image index and start and end positions of patches for semantic segmentation.
+ """
+ masks_queries_logits_per_layer, class_queries_logits_per_layer = (), ()
+
+ hidden_states = self.dropout(self.embeddings(pixel_values))
+ position_embeddings = self.rope_embeddings(pixel_values.to(hidden_states.dtype))
+ attention_mask = None
+
+ for idx, layer_module in enumerate(self.layers):
+ if idx == self.num_hidden_layers - self.config.num_blocks:
+ query = self.query.weight[None, :, :].expand(hidden_states.shape[0], -1, -1).to(hidden_states.device)
+ hidden_states = torch.cat((query, hidden_states), dim=1)
+
+ if idx >= self.num_hidden_layers - self.config.num_blocks and (
+ self.training or self.attn_mask_probs[idx - self.num_hidden_layers + self.config.num_blocks] > 0
+ ):
+ norm_hidden_states = self.layernorm(hidden_states)
+ masks_queries_logits, class_queries_logits = self.predict(norm_hidden_states)
+
+ masks_queries_logits_per_layer += (masks_queries_logits,)
+ class_queries_logits_per_layer += (class_queries_logits,)
+
+ attention_mask = torch.ones(
+ hidden_states.shape[0],
+ hidden_states.shape[1],
+ hidden_states.shape[1],
+ device=hidden_states.device,
+ dtype=torch.bool,
+ )
+
+ interpolated_logits = F.interpolate(masks_queries_logits, size=self.grid_size, mode="bilinear")
+ interpolated_logits = interpolated_logits.view(
+ interpolated_logits.size(0), interpolated_logits.size(1), -1
+ )
+
+ num_query_tokens = self.config.num_queries
+ encoder_start_tokens = num_query_tokens + self.num_prefix_tokens
+
+ # Set attention mask for queries to focus on encoder tokens based on interpolated logits
+ attention_mask[:, :num_query_tokens, encoder_start_tokens:] = interpolated_logits > 0
+
+ # Disable attention mask for random query tokens.
+ attention_mask = self._disable_attention_mask(
+ attention_mask,
+ prob=self.attn_mask_probs[idx - self.num_hidden_layers + self.config.num_blocks],
+ num_query_tokens=num_query_tokens,
+ encoder_start_tokens=encoder_start_tokens,
+ device=attention_mask.device,
+ )
+
+ # Expand attention mask to 4d mask.
+ attention_mask = attention_mask[:, None, ...].expand(-1, self.config.num_attention_heads, -1, -1)
+ dtype_min = torch.finfo(hidden_states.dtype).min
+ attention_mask = attention_mask.to(hidden_states.dtype).masked_fill(~attention_mask, dtype_min)
+
+ hidden_states = layer_module(
+ hidden_states,
+ attention_mask=attention_mask,
+ position_embeddings=position_embeddings,
+ )
+
+ sequence_output = self.layernorm(hidden_states)
+
+ masks_queries_logits, class_queries_logits = self.predict(sequence_output)
+ masks_queries_logits_per_layer += (masks_queries_logits,)
+ class_queries_logits_per_layer += (class_queries_logits,)
+
+ loss = None
+ if mask_labels is not None and class_labels is not None:
+ loss = 0.0
+ for masks_queries_logits, class_queries_logits in zip(
+ masks_queries_logits_per_layer, class_queries_logits_per_layer
+ ):
+ loss_dict = self.get_loss_dict(
+ masks_queries_logits=masks_queries_logits,
+ class_queries_logits=class_queries_logits,
+ mask_labels=mask_labels,
+ class_labels=class_labels,
+ auxiliary_predictions=None,
+ )
+ loss += self.get_loss(loss_dict)
+
+ return EomtDinov3ForUniversalSegmentationOutput(
+ loss=loss,
+ masks_queries_logits=masks_queries_logits,
+ class_queries_logits=class_queries_logits,
+ last_hidden_state=sequence_output,
+ patch_offsets=patch_offsets,
+ )
+
+ def get_input_embeddings(self):
+ return self.embeddings.patch_embeddings
+
+ def predict(self, logits: torch.Tensor):
+ query_tokens = logits[:, : self.config.num_queries, :]
+ class_logits = self.class_predictor(query_tokens)
+
+ prefix_tokens = logits[:, self.config.num_queries + self.embeddings.num_prefix_tokens :, :]
+ prefix_tokens = prefix_tokens.transpose(1, 2)
+
+ prefix_tokens = prefix_tokens.reshape(prefix_tokens.shape[0], -1, *self.grid_size)
+
+ query_tokens = self.mask_head(query_tokens)
+ prefix_tokens = self.upscale_block(prefix_tokens)
+
+ mask_logits = torch.einsum("bqc, bchw -> bqhw", query_tokens, prefix_tokens)
+
+ return mask_logits, class_logits
+
+ @staticmethod
+ def _disable_attention_mask(attn_mask, prob, num_query_tokens, encoder_start_tokens, device):
+ if prob < 1:
+ # Generate random queries to disable based on the probs
+ random_queries = torch.rand(attn_mask.shape[0], num_query_tokens, device=device) > prob
+
+ # Disable attention to the query tokens, considering the prefix tokens
+ attn_mask[:, :num_query_tokens, encoder_start_tokens:][random_queries] = 1
+
+ return attn_mask
+
+
+__all__ = ["EomtDinov3PreTrainedModel", "EomtDinov3ForUniversalSegmentation"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/eomt_dinov3/modular_eomt_dinov3.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/eomt_dinov3/modular_eomt_dinov3.py
new file mode 100644
index 0000000000000000000000000000000000000000..2b6920a3b75838da9c9abc247d5f38782a365ed4
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/eomt_dinov3/modular_eomt_dinov3.py
@@ -0,0 +1,364 @@
+# Copyright 2026 the HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch EoMT model backed by DINOv3."""
+
+from collections.abc import Callable
+from typing import Optional
+
+import torch
+import torch.nn.functional as F
+from huggingface_hub.dataclasses import strict
+from torch import Tensor, nn
+
+from ... import initialization as init
+from ...modeling_rope_utils import RopeParameters
+from ...modeling_utils import PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import (
+ TransformersKwargs,
+ auto_docstring,
+)
+from ...utils.generic import merge_with_config_defaults
+from ...utils.output_capturing import capture_outputs
+from ..dinov3_vit.modeling_dinov3_vit import (
+ DINOv3ViTAttention,
+ DINOv3ViTEmbeddings,
+ DINOv3ViTLayer,
+ DINOv3ViTLayerScale,
+ DINOv3ViTRopePositionEmbedding,
+)
+from ..eomt.configuration_eomt import EomtConfig
+from ..eomt.modeling_eomt import (
+ EomtForUniversalSegmentation,
+ EomtForUniversalSegmentationOutput,
+ EomtLoss,
+ EomtPreTrainedModel,
+)
+
+
+@auto_docstring(checkpoint="tue-mps/coco_panoptic_eomt_large_640_dinov3")
+@strict
+class EomtDinov3Config(EomtConfig):
+ r"""
+ layerscale_value (`float`, *optional*, defaults to 1.0):
+ Initial value for the LayerScale parameter.
+ num_upscale_blocks (`int`, *optional*, defaults to 2):
+ Number of upsampling blocks used in the decoder or segmentation head.
+ num_blocks (`int`, *optional*, defaults to 4):
+ Number of feature blocks or stages in the architecture.
+ no_object_weight (`float`, *optional*, defaults to 0.1):
+ Loss weight for the "no object" class in panoptic/instance segmentation.
+ train_num_points (`int`, *optional*, defaults to 12544):
+ Number of points to sample for mask loss computation during training.
+ oversample_ratio (`float`, *optional*, defaults to 3.0):
+ Oversampling ratio used in point sampling for mask training.
+ importance_sample_ratio (`float`, *optional*, defaults to 0.75):
+ Ratio of points to sample based on importance during training.
+ num_queries (`int`, *optional*, defaults to 200):
+ Number of object queries in the Transformer.
+ num_register_tokens (`int`, *optional*, defaults to 4):
+ Number of learnable register tokens added to the transformer input.
+ query_bias (`bool`, *optional*, defaults to `True`):
+ Whether to use bias in query projection.
+ key_bias (`bool`, *optional*, defaults to `False`):
+ Whether to use bias in key projection.
+ value_bias (`bool`, *optional*, defaults to `True`):
+ Whether to use bias in value projection.
+ proj_bias (`bool`, *optional*, defaults to `True`):
+ Whether to use bias in output projection.
+ use_gated_mlp (`bool`, *optional*, defaults to `False`):
+ Whether to use gated MLP layers.
+ pos_embed_shift (`float`, *optional*):
+ Shift value for position embeddings.
+ pos_embed_jitter (`float`, *optional*):
+ Jitter value for position embeddings.
+ pos_embed_rescale (`float`, *optional*, defaults to 2.0):
+ Rescale value for position embeddings.
+ """
+
+ model_type = "eomt_dinov3"
+ default_theta = 100.0
+
+ hidden_size: int = 1024
+ num_hidden_layers: int = 24
+ num_attention_heads: int = 16
+ intermediate_size: int = 4096
+ hidden_act: str = "gelu"
+ hidden_dropout_prob: float | int = 0.0
+ initializer_range: float = 0.02
+ layer_norm_eps: float = 1e-6
+ image_size: int | list[int] | tuple[int, int] = 640
+ patch_size: int | list[int] | tuple[int, int] = 16
+ num_channels: int = 3
+ layerscale_value: float = 1.0
+ drop_path_rate: float | int = 0.0
+ num_upscale_blocks: int = 2
+ attention_dropout: float | int = 0.0
+ num_blocks: int = 4
+ no_object_weight: float = 0.1
+ class_weight: float = 2.0
+ mask_weight: float = 5.0
+ dice_weight: float = 5.0
+ train_num_points: int = 12544
+ oversample_ratio: float = 3.0
+ importance_sample_ratio: float = 0.75
+ num_queries: int = 200
+ num_register_tokens: int = 4
+ rope_parameters: RopeParameters | dict | None = None
+ query_bias: bool = True
+ key_bias: bool = False
+ value_bias: bool = True
+ proj_bias: bool = True
+ mlp_bias: bool = True
+ use_gated_mlp: bool = False
+ pos_embed_shift: float | None = None
+ pos_embed_jitter: float | None = None
+ pos_embed_rescale: float | None = 2.0
+
+ mlp_ratio = AttributeError()
+ use_swiglu_ffn = AttributeError()
+
+
+class EomtDinov3Attention(DINOv3ViTAttention):
+ pass
+
+
+class EomtDinov3Embeddings(DINOv3ViTEmbeddings):
+ def __init__(self, config: EomtDinov3Config):
+ super().__init__(config)
+ self.num_prefix_tokens = 1 + config.num_register_tokens
+
+
+class EomtDinov3Layer(DINOv3ViTLayer):
+ pass
+
+
+class EomtDinov3LayerScale(DINOv3ViTLayerScale):
+ pass
+
+
+class EomtDinov3RotaryEmbedding(DINOv3ViTRopePositionEmbedding):
+ inv_freq: Tensor
+
+ def __init__(self, config: EomtDinov3Config, device=None):
+ nn.Module.__init__(self)
+ self.config = config
+
+ self.rope_type = self.config.rope_parameters["rope_type"]
+ rope_init_fn: Callable = self.compute_default_rope_parameters
+ if self.rope_type != "default":
+ raise ValueError("`EomtDinov3` only supports `default` RoPE! Please check your `rope_type`")
+ inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
+
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
+ self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
+
+ @staticmethod
+ def compute_default_rope_parameters(
+ config: EomtDinov3Config | None = None,
+ device: Optional["torch.device"] = None,
+ seq_len: int | None = None,
+ ) -> torch.Tensor:
+ """
+ Computes the inverse frequencies according to the original RoPE implementation
+ Args:
+ config ([`~transformers.PreTrainedConfig`]):
+ The model configuration.
+ device (`torch.device`):
+ The device to use for initialization of the inverse frequencies.
+ seq_len (`int`, *optional*):
+ The current sequence length. Unused for this type of RoPE.
+ Returns:
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
+ """
+ base = config.rope_parameters["rope_theta"]
+ head_dim = config.hidden_size // config.num_attention_heads
+
+ attention_factor = 1.0 # Unused in this type of RoPE
+
+ # Compute the inverse frequencies
+ inv_freq = 1 / base ** torch.arange(0, 1, 4 / head_dim, dtype=torch.float32, device=device)
+ return inv_freq, attention_factor
+
+
+class EomtDinov3Loss(EomtLoss):
+ pass
+
+
+class EomtDinov3ForUniversalSegmentationOutput(EomtForUniversalSegmentationOutput):
+ pass
+
+
+class EomtDinov3PreTrainedModel(EomtPreTrainedModel):
+ config_class = EomtDinov3Config
+ base_model_prefix = "eomt_dinov3"
+ _no_split_modules = ["EomtDinov3Layer"]
+ _can_record_outputs = {
+ "hidden_states": EomtDinov3Layer,
+ "attentions": EomtDinov3Attention,
+ }
+
+ def _init_weights(self, module: nn.Module) -> None:
+ PreTrainedModel._init_weights(module)
+ std = self.config.initializer_range
+ if isinstance(module, EomtDinov3LayerScale):
+ if hasattr(module, "lambda1"):
+ init.constant_(module.lambda1, self.config.layerscale_value)
+ elif isinstance(module, EomtDinov3Embeddings):
+ init.trunc_normal_(module.cls_token, mean=0.0, std=std)
+ init.zeros_(module.register_tokens)
+ elif isinstance(module, EomtDinov3Loss):
+ empty_weight = torch.ones(module.num_labels + 1)
+ empty_weight[-1] = module.eos_coef
+ init.copy_(module.empty_weight, empty_weight)
+ elif isinstance(module, EomtDinov3ForUniversalSegmentation):
+ init.ones_(module.attn_mask_probs)
+
+
+@auto_docstring(
+ custom_intro="""
+ The EoMT-DINOv3 model with head on top for instance/semantic/panoptic segmentation.
+ """,
+)
+class EomtDinov3ForUniversalSegmentation(EomtDinov3PreTrainedModel, EomtForUniversalSegmentation):
+ def __init__(self, config: EomtDinov3Config):
+ super().__init__(config)
+
+ self.num_prefix_tokens = 1 + config.num_register_tokens
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+ self.embeddings = EomtDinov3Embeddings(config)
+ self.embeddings.register_parameter("mask_token", None)
+
+ self.rope_embeddings = EomtDinov3RotaryEmbedding(config)
+ self.layers = nn.ModuleList([EomtDinov3Layer(config) for _ in range(config.num_hidden_layers)])
+
+ self.post_init()
+
+ # We redefine forward here because EoMT-DINOv3 uses DINOv3 backbone components (RoPE embeddings, layers)
+ # which require different integration than the base EoMT model that uses a separate encoder.
+ @merge_with_config_defaults
+ @capture_outputs
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: Tensor,
+ mask_labels: list[Tensor] | None = None,
+ class_labels: list[Tensor] | None = None,
+ patch_offsets: list[Tensor] | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> EomtDinov3ForUniversalSegmentationOutput:
+ r"""
+ mask_labels (`list[torch.Tensor]`, *optional*):
+ list of mask labels of shape `(num_labels, height, width)` to be fed to a model
+ class_labels (`list[torch.LongTensor]`, *optional*):
+ list of target class labels of shape `(num_labels, height, width)` to be fed to a model. They identify the
+ labels of `mask_labels`, e.g. the label of `mask_labels[i][j]` if `class_labels[i][j]`.
+ patch_offsets (`list[torch.Tensor]`, *optional*):
+ list of tuples indicating the image index and start and end positions of patches for semantic segmentation.
+ """
+ masks_queries_logits_per_layer, class_queries_logits_per_layer = (), ()
+
+ hidden_states = self.dropout(self.embeddings(pixel_values))
+ position_embeddings = self.rope_embeddings(pixel_values.to(hidden_states.dtype))
+ attention_mask = None
+
+ for idx, layer_module in enumerate(self.layers):
+ if idx == self.num_hidden_layers - self.config.num_blocks:
+ query = self.query.weight[None, :, :].expand(hidden_states.shape[0], -1, -1).to(hidden_states.device)
+ hidden_states = torch.cat((query, hidden_states), dim=1)
+
+ if idx >= self.num_hidden_layers - self.config.num_blocks and (
+ self.training or self.attn_mask_probs[idx - self.num_hidden_layers + self.config.num_blocks] > 0
+ ):
+ norm_hidden_states = self.layernorm(hidden_states)
+ masks_queries_logits, class_queries_logits = self.predict(norm_hidden_states)
+
+ masks_queries_logits_per_layer += (masks_queries_logits,)
+ class_queries_logits_per_layer += (class_queries_logits,)
+
+ attention_mask = torch.ones(
+ hidden_states.shape[0],
+ hidden_states.shape[1],
+ hidden_states.shape[1],
+ device=hidden_states.device,
+ dtype=torch.bool,
+ )
+
+ interpolated_logits = F.interpolate(masks_queries_logits, size=self.grid_size, mode="bilinear")
+ interpolated_logits = interpolated_logits.view(
+ interpolated_logits.size(0), interpolated_logits.size(1), -1
+ )
+
+ num_query_tokens = self.config.num_queries
+ encoder_start_tokens = num_query_tokens + self.num_prefix_tokens
+
+ # Set attention mask for queries to focus on encoder tokens based on interpolated logits
+ attention_mask[:, :num_query_tokens, encoder_start_tokens:] = interpolated_logits > 0
+
+ # Disable attention mask for random query tokens.
+ attention_mask = self._disable_attention_mask(
+ attention_mask,
+ prob=self.attn_mask_probs[idx - self.num_hidden_layers + self.config.num_blocks],
+ num_query_tokens=num_query_tokens,
+ encoder_start_tokens=encoder_start_tokens,
+ device=attention_mask.device,
+ )
+
+ # Expand attention mask to 4d mask.
+ attention_mask = attention_mask[:, None, ...].expand(-1, self.config.num_attention_heads, -1, -1)
+ dtype_min = torch.finfo(hidden_states.dtype).min
+ attention_mask = attention_mask.to(hidden_states.dtype).masked_fill(~attention_mask, dtype_min)
+
+ hidden_states = layer_module(
+ hidden_states,
+ attention_mask=attention_mask,
+ position_embeddings=position_embeddings,
+ )
+
+ sequence_output = self.layernorm(hidden_states)
+
+ masks_queries_logits, class_queries_logits = self.predict(sequence_output)
+ masks_queries_logits_per_layer += (masks_queries_logits,)
+ class_queries_logits_per_layer += (class_queries_logits,)
+
+ loss = None
+ if mask_labels is not None and class_labels is not None:
+ loss = 0.0
+ for masks_queries_logits, class_queries_logits in zip(
+ masks_queries_logits_per_layer, class_queries_logits_per_layer
+ ):
+ loss_dict = self.get_loss_dict(
+ masks_queries_logits=masks_queries_logits,
+ class_queries_logits=class_queries_logits,
+ mask_labels=mask_labels,
+ class_labels=class_labels,
+ auxiliary_predictions=None,
+ )
+ loss += self.get_loss(loss_dict)
+
+ return EomtDinov3ForUniversalSegmentationOutput(
+ loss=loss,
+ masks_queries_logits=masks_queries_logits,
+ class_queries_logits=class_queries_logits,
+ last_hidden_state=sequence_output,
+ patch_offsets=patch_offsets,
+ )
+
+
+__all__ = [
+ "EomtDinov3Config",
+ "EomtDinov3PreTrainedModel",
+ "EomtDinov3ForUniversalSegmentation",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/ernie/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/ernie/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9068e6b498254b1e66693eac78765b332051cce0
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/ernie/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/ernie/__pycache__/configuration_ernie.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/ernie/__pycache__/configuration_ernie.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..911ea7ed70850d89cf73a378512a4bd0b520090f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/ernie/__pycache__/configuration_ernie.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/ernie/__pycache__/modeling_ernie.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/ernie/__pycache__/modeling_ernie.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d9d7b8fbc6cf15c2ecda50b472d08e65761296ef
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/ernie/__pycache__/modeling_ernie.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/ernie/__pycache__/modular_ernie.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/ernie/__pycache__/modular_ernie.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..69b34d22a8c37aea6b747e154f7f461b5e079a9b
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/ernie/__pycache__/modular_ernie.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/ernie4_5/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/ernie4_5/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..5d6e69432c9a8ac0471c3dd91660eaf912dc149c
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/ernie4_5/__init__.py
@@ -0,0 +1,27 @@
+# Copyright 2025 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_ernie4_5 import *
+ from .modeling_ernie4_5 import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/ernie4_5/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/ernie4_5/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f9ec22edb2984521855d350dfa9890da9179fdb1
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/ernie4_5/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/ernie4_5/__pycache__/configuration_ernie4_5.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/ernie4_5/__pycache__/configuration_ernie4_5.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e5ed2b0a1e28a412b4e7ab3f253a661e18bafc8d
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/ernie4_5/__pycache__/configuration_ernie4_5.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/ernie4_5/__pycache__/modeling_ernie4_5.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/ernie4_5/__pycache__/modeling_ernie4_5.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b9bee98da5d1518baaddb99b98275667f1a33bc1
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/ernie4_5/__pycache__/modeling_ernie4_5.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/ernie4_5/__pycache__/modular_ernie4_5.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/ernie4_5/__pycache__/modular_ernie4_5.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1c1edd4c52a4baec000d55c477fce2412e143b54
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/ernie4_5/__pycache__/modular_ernie4_5.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/ernie4_5/configuration_ernie4_5.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/ernie4_5/configuration_ernie4_5.py
new file mode 100644
index 0000000000000000000000000000000000000000..896fb0b99402fd2c32b5996d2cb9181fe60ec47d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/ernie4_5/configuration_ernie4_5.py
@@ -0,0 +1,91 @@
+# Copyright (c) 2025 Baidu, Inc. and HuggingFace Inc. team. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Ernie 4.5 model configuration"""
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...modeling_rope_utils import RopeParameters
+from ...utils import auto_docstring
+
+
+@auto_docstring(checkpoint="baidu/ERNIE-4.5-0.3B-PT")
+@strict
+class Ernie4_5Config(PreTrainedConfig):
+ r"""
+ use_bias (`bool`, *optional*, defaults to `False`):
+ Whether to use a bias in any of the projections including mlp and attention for example.
+
+ Example:
+
+ ```python
+ >>> from transformers import Ernie4_5Model, Ernie4_5Config
+
+ >>> # Initializing a Ernie4_5 0.3B style configuration
+ >>> configuration = Ernie4_5Config()
+
+ >>> # Initializing a model from the 0.3B style configuration
+ >>> model = Ernie4_5Model(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "ernie4_5"
+ keys_to_ignore_at_inference = ["past_key_values"]
+ default_theta = 500000.0
+ # Default tensor parallel plan for base model `Ernie4_5Model`
+ base_model_tp_plan = {
+ "layers.*.self_attn.q_proj": "colwise",
+ "layers.*.self_attn.k_proj": "colwise",
+ "layers.*.self_attn.v_proj": "colwise",
+ "layers.*.self_attn.o_proj": "rowwise",
+ "layers.*.mlp.gate_proj": "colwise",
+ "layers.*.mlp.up_proj": "colwise",
+ "layers.*.mlp.down_proj": "rowwise",
+ }
+ base_model_pp_plan = {
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
+ "norm": (["hidden_states"], ["hidden_states"]),
+ }
+
+ vocab_size: int = 103424
+ hidden_size: int = 1024
+ intermediate_size: int = 3072
+ num_hidden_layers: int = 18
+ num_attention_heads: int = 16
+ num_key_value_heads: int | None = 2
+ hidden_act: str = "silu"
+ max_position_embeddings: int = 131072
+ initializer_range: float = 0.02
+ rms_norm_eps: float = 1e-05
+ use_cache: bool | None = True
+ pad_token_id: int | None = 0
+ bos_token_id: int | None = 1
+ eos_token_id: int | list[int] | None = 2
+ tie_word_embeddings: bool = True
+ rope_parameters: RopeParameters | dict | None = None
+ use_bias: bool | None = False
+ head_dim: int | None = 128
+
+ def __post_init__(self, **kwargs):
+ if self.num_key_value_heads is None:
+ self.num_key_value_heads = self.num_attention_heads
+
+ self.head_dim = self.head_dim if self.head_dim is not None else self.hidden_size // self.num_attention_heads
+ super().__post_init__(**kwargs)
+
+
+__all__ = ["Ernie4_5Config"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/ernie4_5/modeling_ernie4_5.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/ernie4_5/modeling_ernie4_5.py
new file mode 100644
index 0000000000000000000000000000000000000000..ae533c7c6ef887e1ad2c19caf120c20f15c077b3
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/ernie4_5/modeling_ernie4_5.py
@@ -0,0 +1,485 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/ernie4_5/modular_ernie4_5.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_ernie4_5.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright (c) 2025 Baidu, Inc. and HuggingFace Inc. team. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from collections.abc import Callable
+from typing import Optional
+
+import torch
+from torch import nn
+
+from ...activations import ACT2FN
+from ...cache_utils import Cache, DynamicCache
+from ...generation import GenerationMixin
+from ...integrations import use_kernel_forward_from_hub, use_kernelized_func
+from ...masking_utils import create_causal_mask
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
+from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import TransformersKwargs, auto_docstring, can_return_tuple
+from ...utils.generic import maybe_autocast, merge_with_config_defaults
+from ...utils.output_capturing import capture_outputs
+from .configuration_ernie4_5 import Ernie4_5Config
+
+
+class Ernie4_5RotaryEmbedding(nn.Module):
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
+
+ def __init__(self, config: Ernie4_5Config, device=None):
+ super().__init__()
+ self.max_seq_len_cached = config.max_position_embeddings
+ self.original_max_seq_len = config.max_position_embeddings
+
+ self.config = config
+
+ self.rope_type = self.config.rope_parameters["rope_type"]
+ rope_init_fn: Callable = self.compute_default_rope_parameters
+ if self.rope_type != "default":
+ rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
+ inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
+
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
+ self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
+
+ @staticmethod
+ def compute_default_rope_parameters(
+ config: Ernie4_5Config | None = None,
+ device: Optional["torch.device"] = None,
+ seq_len: int | None = None,
+ ) -> tuple["torch.Tensor", float]:
+ """
+ Computes the inverse frequencies according to the original RoPE implementation
+ Args:
+ config ([`~transformers.PreTrainedConfig`]):
+ The model configuration.
+ device (`torch.device`):
+ The device to use for initialization of the inverse frequencies.
+ seq_len (`int`, *optional*):
+ The current sequence length. Unused for this type of RoPE.
+ Returns:
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
+ """
+ base = config.rope_parameters["rope_theta"]
+ dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
+
+ attention_factor = 1.0 # Unused in this type of RoPE
+
+ # Compute the inverse frequencies
+ inv_freq = 1.0 / (
+ base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
+ )
+ return inv_freq, attention_factor
+
+ @torch.no_grad()
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
+ def forward(self, x, position_ids):
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
+ position_ids_expanded = position_ids[:, None, :].float()
+
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
+ with maybe_autocast(device_type=device_type, enabled=False): # Force float32
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
+ emb = torch.cat((freqs, freqs), dim=-1)
+ cos = emb.cos() * self.attention_scaling
+ sin = emb.sin() * self.attention_scaling
+
+ # keeping it in full precision
+ return cos, sin
+
+
+class Ernie4_5MLP(nn.Module):
+ def __init__(self, config: Ernie4_5Config):
+ super().__init__()
+ self.config = config
+ self.hidden_size = config.hidden_size
+ self.intermediate_size = config.intermediate_size
+
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.use_bias)
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.use_bias)
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.use_bias)
+ self.act_fn = ACT2FN[config.hidden_act]
+
+ def forward(self, x):
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
+ return down_proj
+
+
+def rotate_half(x):
+ """Rotates half the hidden dims of the input."""
+ x1 = x[..., 0::2]
+ x2 = x[..., 1::2]
+ return torch.stack((-x2, x1), dim=-1).flatten(-2)
+
+
+def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
+ """
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
+ """
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
+ if n_rep == 1:
+ return hidden_states
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
+
+
+def eager_attention_forward(
+ module: nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: torch.Tensor | None,
+ scaling: float,
+ dropout: float = 0.0,
+ **kwargs: Unpack[TransformersKwargs],
+):
+ key_states = repeat_kv(key, module.num_key_value_groups)
+ value_states = repeat_kv(value, module.num_key_value_groups)
+
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
+ if attention_mask is not None:
+ attn_weights = attn_weights + attention_mask
+
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
+ attn_output = torch.matmul(attn_weights, value_states)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+
+ return attn_output, attn_weights
+
+
+def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
+ """Applies Rotary Position Embedding to the query and key tensors.
+
+ Args:
+ q (`torch.Tensor`): The query tensor.
+ k (`torch.Tensor`): The key tensor.
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
+ Returns:
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
+ """
+ # glm rope style (with full dim) and full precision
+ original_dtype = q.dtype
+
+ cos = cos.unsqueeze(unsqueeze_dim)
+ sin = sin.unsqueeze(unsqueeze_dim)
+
+ # Interleave them instead of usual shape
+ cos = cos[..., : cos.shape[-1] // 2].repeat_interleave(2, dim=-1)
+ sin = sin[..., : sin.shape[-1] // 2].repeat_interleave(2, dim=-1)
+
+ q_embed = (q.float() * cos) + (rotate_half(q).float() * sin)
+ k_embed = (k.float() * cos) + (rotate_half(k).float() * sin)
+
+ return q_embed.to(original_dtype), k_embed.to(original_dtype)
+
+
+@use_kernelized_func(apply_rotary_pos_emb)
+class Ernie4_5Attention(nn.Module):
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
+
+ def __init__(self, config: Ernie4_5Config, layer_idx: int):
+ super().__init__()
+ self.config = config
+ self.layer_idx = layer_idx
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
+ self.scaling = self.head_dim**-0.5
+
+ self.attention_dropout = 0.0
+ self.is_causal = True
+
+ self.q_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.use_bias)
+ self.k_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.use_bias)
+ self.v_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.use_bias)
+ self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.use_bias)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
+ attention_mask: torch.Tensor | None = None,
+ past_key_values: Cache | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor, torch.Tensor]:
+ input_shape = hidden_states.shape[:-1]
+ hidden_shape = (*input_shape, -1, self.head_dim)
+
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+
+ cos, sin = position_embeddings
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
+
+ if past_key_values is not None:
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_states,
+ key_states,
+ value_states,
+ attention_mask,
+ dropout=0.0 if not self.training else self.attention_dropout,
+ scaling=self.scaling,
+ **kwargs,
+ )
+
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ attn_output = self.o_proj(attn_output)
+ return attn_output, attn_weights
+
+
+@use_kernel_forward_from_hub("RMSNorm")
+class Ernie4_5RMSNorm(nn.Module):
+ def __init__(self, hidden_size, eps: float = 1e-6) -> None:
+ """
+ Ernie4_5RMSNorm is equivalent to T5LayerNorm
+ """
+ super().__init__()
+ self.weight = nn.Parameter(torch.ones(hidden_size))
+ self.variance_epsilon = eps
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ input_dtype = hidden_states.dtype
+ hidden_states = hidden_states.to(torch.float32)
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
+ return self.weight * hidden_states.to(input_dtype)
+
+ def extra_repr(self):
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
+
+
+class Ernie4_5DecoderLayer(GradientCheckpointingLayer):
+ def __init__(self, config: Ernie4_5Config, layer_idx: int):
+ super().__init__()
+ self.hidden_size = config.hidden_size
+
+ self.self_attn = Ernie4_5Attention(config=config, layer_idx=layer_idx)
+
+ self.mlp = Ernie4_5MLP(config)
+ self.input_layernorm = Ernie4_5RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.post_attention_layernorm = Ernie4_5RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ use_cache: bool | None = False,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.Tensor:
+ residual = hidden_states
+ hidden_states = self.input_layernorm(hidden_states)
+ # Self Attention
+ hidden_states, _ = self.self_attn(
+ hidden_states=hidden_states,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ position_embeddings=position_embeddings,
+ **kwargs,
+ )
+ hidden_states = residual + hidden_states
+
+ # Fully Connected
+ residual = hidden_states
+ hidden_states = self.post_attention_layernorm(hidden_states)
+ hidden_states = self.mlp(hidden_states)
+ hidden_states = residual + hidden_states
+ return hidden_states
+
+
+@auto_docstring
+class Ernie4_5PreTrainedModel(PreTrainedModel):
+ config: Ernie4_5Config
+ base_model_prefix = "model"
+ supports_gradient_checkpointing = True
+ _no_split_modules = ["Ernie4_5DecoderLayer"]
+ _skip_keys_device_placement = ["past_key_values"]
+ _supports_flash_attn = True
+ _supports_sdpa = True
+ _supports_flex_attn = True
+
+ _can_compile_fullgraph = True
+ _supports_attention_backend = True
+ _can_record_outputs = {
+ "hidden_states": Ernie4_5DecoderLayer,
+ "attentions": Ernie4_5Attention,
+ }
+
+
+@auto_docstring
+class Ernie4_5Model(Ernie4_5PreTrainedModel):
+ def __init__(self, config: Ernie4_5Config):
+ super().__init__(config)
+ self.padding_idx = config.pad_token_id
+ self.vocab_size = config.vocab_size
+
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
+ self.layers = nn.ModuleList(
+ [Ernie4_5DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
+ )
+ self.norm = Ernie4_5RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.rotary_emb = Ernie4_5RotaryEmbedding(config=config)
+ self.gradient_checkpointing = False
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @merge_with_config_defaults
+ @capture_outputs
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ use_cache: bool | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> BaseModelOutputWithPast:
+ if (input_ids is None) ^ (inputs_embeds is not None):
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
+
+ if inputs_embeds is None:
+ inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)
+
+ if use_cache and past_key_values is None:
+ past_key_values = DynamicCache(config=self.config)
+
+ if position_ids is None:
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
+ position_ids = position_ids.unsqueeze(0)
+
+ causal_mask = create_causal_mask(
+ config=self.config,
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ position_ids=position_ids,
+ )
+
+ hidden_states = inputs_embeds
+ position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
+
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
+ hidden_states = decoder_layer(
+ hidden_states,
+ attention_mask=causal_mask,
+ position_embeddings=position_embeddings,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ **kwargs,
+ )
+
+ hidden_states = self.norm(hidden_states)
+ return BaseModelOutputWithPast(
+ last_hidden_state=hidden_states,
+ past_key_values=past_key_values,
+ )
+
+
+@auto_docstring
+class Ernie4_5ForCausalLM(Ernie4_5PreTrainedModel, GenerationMixin):
+ _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
+ _tp_plan = {"lm_head": "colwise_gather_output"}
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
+
+ def __init__(self, config):
+ super().__init__(config)
+ self.model = Ernie4_5Model(config)
+ self.vocab_size = config.vocab_size
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ use_cache: bool | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> CausalLMOutputWithPast:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
+ """
+ outputs: BaseModelOutputWithPast = self.model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ **kwargs,
+ )
+
+ hidden_states = outputs.last_hidden_state
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
+
+ return CausalLMOutputWithPast(
+ loss=loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+__all__ = ["Ernie4_5ForCausalLM", "Ernie4_5Model", "Ernie4_5PreTrainedModel"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/ernie4_5/modular_ernie4_5.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/ernie4_5/modular_ernie4_5.py
new file mode 100644
index 0000000000000000000000000000000000000000..2f92e1c7d23ea421a554525855783b971fdf81e7
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/ernie4_5/modular_ernie4_5.py
@@ -0,0 +1,122 @@
+# Copyright (c) 2025 Baidu, Inc. and HuggingFace Inc. team. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch Ernie 4.5 model"""
+
+import torch
+from torch import nn
+
+from ...modeling_rope_utils import dynamic_rope_update
+from ...utils import auto_docstring, can_return_tuple
+from ...utils.generic import maybe_autocast
+from ..glm.modeling_glm import rotate_half
+from ..llama.modeling_llama import (
+ LlamaAttention,
+ LlamaForCausalLM,
+ LlamaMLP,
+)
+from ..olmo.modeling_olmo import OlmoRotaryEmbedding
+from .configuration_ernie4_5 import Ernie4_5Config
+
+
+class Ernie4_5RotaryEmbedding(OlmoRotaryEmbedding):
+ @torch.no_grad()
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
+ def forward(self, x, position_ids):
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
+ position_ids_expanded = position_ids[:, None, :].float()
+
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
+ with maybe_autocast(device_type=device_type, enabled=False): # Force float32
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
+ emb = torch.cat((freqs, freqs), dim=-1)
+ cos = emb.cos() * self.attention_scaling
+ sin = emb.sin() * self.attention_scaling
+
+ # keeping it in full precision
+ return cos, sin
+
+
+def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
+ """Applies Rotary Position Embedding to the query and key tensors.
+
+ Args:
+ q (`torch.Tensor`): The query tensor.
+ k (`torch.Tensor`): The key tensor.
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
+ Returns:
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
+ """
+ # glm rope style (with full dim) and full precision
+ original_dtype = q.dtype
+
+ cos = cos.unsqueeze(unsqueeze_dim)
+ sin = sin.unsqueeze(unsqueeze_dim)
+
+ # Interleave them instead of usual shape
+ cos = cos[..., : cos.shape[-1] // 2].repeat_interleave(2, dim=-1)
+ sin = sin[..., : sin.shape[-1] // 2].repeat_interleave(2, dim=-1)
+
+ q_embed = (q.float() * cos) + (rotate_half(q).float() * sin)
+ k_embed = (k.float() * cos) + (rotate_half(k).float() * sin)
+
+ return q_embed.to(original_dtype), k_embed.to(original_dtype)
+
+
+class Ernie4_5MLP(LlamaMLP):
+ def __init__(self, config: Ernie4_5Config):
+ super().__init__(config)
+
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.use_bias)
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.use_bias)
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.use_bias)
+
+
+class Ernie4_5Attention(LlamaAttention):
+ def __init__(self, config: Ernie4_5Config, layer_idx: int):
+ super().__init__(config, layer_idx)
+
+ self.attention_dropout = 0.0
+
+ self.q_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.use_bias)
+ self.k_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.use_bias)
+ self.v_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.use_bias)
+ self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.use_bias)
+
+
+class Ernie4_5ForCausalLM(LlamaForCausalLM):
+ @can_return_tuple
+ @auto_docstring
+ def forward(self, **super_kwargs):
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
+ """
+ super().forward(**super_kwargs)
+
+
+__all__ = [
+ "Ernie4_5ForCausalLM",
+ "Ernie4_5Model", # noqa: F822
+ "Ernie4_5PreTrainedModel", # noqa: F822
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/eurobert/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/eurobert/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..0212ce1dab27973c91b4feeccca8f12f0e24dbfd
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/eurobert/__init__.py
@@ -0,0 +1,27 @@
+# Copyright 2025 Nicolas Boizard, Duarte M. Alves, Hippolyte Gisserot-Boukhlef and the EuroBert team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_eurobert import *
+ from .modeling_eurobert import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/eurobert/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/eurobert/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c70102fe6546124b9d679758ae8f72ceecfeb014
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/eurobert/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/eurobert/__pycache__/configuration_eurobert.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/eurobert/__pycache__/configuration_eurobert.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..59174b57b4c4596490aa6a8107d84093a00221fb
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/eurobert/__pycache__/configuration_eurobert.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/eurobert/__pycache__/modeling_eurobert.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/eurobert/__pycache__/modeling_eurobert.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..eb6f3e2046548d918be76e3233421e3fb0382626
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/eurobert/__pycache__/modeling_eurobert.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/eurobert/__pycache__/modular_eurobert.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/eurobert/__pycache__/modular_eurobert.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bc3e2e92ad49bac9e298270b005b5bb6694297f2
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/eurobert/__pycache__/modular_eurobert.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/eurobert/configuration_eurobert.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/eurobert/configuration_eurobert.py
new file mode 100644
index 0000000000000000000000000000000000000000..f64c4f7e5a115fe4bfd7bcd0433da442fec98ed8
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/eurobert/configuration_eurobert.py
@@ -0,0 +1,111 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/eurobert/modular_eurobert.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_eurobert.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2025 Nicolas Boizard, Duarte M. Alves, Hippolyte Gisserot-Boukhlef and the EuroBert team. All rights reserved.
+#
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+from ...configuration_utils import PreTrainedConfig, strict
+from ...modeling_rope_utils import RopeParameters
+from ...utils import auto_docstring
+
+
+@auto_docstring(checkpoint="EuroBERT/EuroBERT-210m")
+@strict
+class EuroBertConfig(PreTrainedConfig):
+ r"""
+ mask_token_id (`int`, *optional*, defaults to 128002):
+ Mask token id.
+ classifier_pooling (`str`, *optional*, defaults to `"late"`):
+ The pooling strategy to use for the classifier. Can be one of ['bos', 'mean', 'late'].
+
+ ```python
+ >>> from transformers import EuroBertModel, EuroBertConfig
+
+ >>> # Initializing a EuroBert eurobert-base style configuration
+ >>> configuration = EuroBertConfig()
+
+ >>> # Initializing a model from the eurobert-base style configuration
+ >>> model = EuroBertModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "eurobert"
+ keys_to_ignore_at_inference = ["past_key_values"]
+ # Default tensor parallel plan for base model `EuroBertModel`
+ base_model_tp_plan = {
+ "layers.*.self_attn.q_proj": "colwise",
+ "layers.*.self_attn.k_proj": "colwise",
+ "layers.*.self_attn.v_proj": "colwise",
+ "layers.*.self_attn.o_proj": "rowwise",
+ "layers.*.mlp.gate_proj": "colwise",
+ "layers.*.mlp.up_proj": "colwise",
+ "layers.*.mlp.down_proj": "rowwise",
+ }
+ base_model_pp_plan = {
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
+ "norm": (["hidden_states"], ["hidden_states"]),
+ }
+
+ vocab_size: int = 128256
+ hidden_size: int = 768
+ intermediate_size: int = 3072
+ num_hidden_layers: int = 12
+ num_attention_heads: int = 12
+ num_key_value_heads: int | None = None
+ hidden_act: str = "silu"
+ max_position_embeddings: int = 8192
+ initializer_range: float = 0.02
+ rms_norm_eps: float = 1e-05
+ use_cache: bool = True
+ pad_token_id: int | None = 128001
+ bos_token_id: int | None = 128000
+ eos_token_id: int | list[int] | None = 128001
+ pretraining_tp: int = 1
+ tie_word_embeddings: bool = False
+ rope_parameters: RopeParameters | dict | None = None
+ attention_bias: bool = False
+ attention_dropout: int | float = 0.0
+ mlp_bias: bool = False
+ head_dim: int | None = None
+ mask_token_id: int = 128002
+ classifier_pooling: str = "late"
+
+ def __post_init__(self, **kwargs):
+ if self.num_key_value_heads is None:
+ self.num_key_value_heads = self.num_attention_heads
+ if self.head_dim is None:
+ self.head_dim = self.hidden_size // self.num_attention_heads
+ if self.num_key_value_heads is None:
+ self.num_key_value_heads = self.num_attention_heads
+
+ super().__post_init__(**kwargs)
+
+ def validate_architecture(self):
+ """Part of `@strict`-powered validation. Validates the architecture of the config."""
+ if self.hidden_size % self.num_attention_heads != 0:
+ raise ValueError(
+ f"The hidden size ({self.hidden_size}) is not a multiple of the number of attention "
+ f"heads ({self.num_attention_heads})."
+ )
+
+
+__all__ = ["EuroBertConfig"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/eurobert/modeling_eurobert.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/eurobert/modeling_eurobert.py
new file mode 100644
index 0000000000000000000000000000000000000000..b93dd0649f14cb17c80595bb3aa105b5731f547d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/eurobert/modeling_eurobert.py
@@ -0,0 +1,628 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/eurobert/modular_eurobert.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_eurobert.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2025 Nicolas Boizard, Duarte M. Alves, Hippolyte Gisserot-Boukhlef and the EuroBert team. All rights reserved.
+#
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from collections.abc import Callable
+from typing import Optional
+
+import torch
+from torch import nn
+from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
+
+from ...activations import ACT2FN
+from ...cache_utils import Cache
+from ...integrations import use_kernel_forward_from_hub, use_kernel_func_from_hub, use_kernelized_func
+from ...masking_utils import create_bidirectional_mask
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import BaseModelOutput, MaskedLMOutput, SequenceClassifierOutput, TokenClassifierOutput
+from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import auto_docstring
+from ...utils.generic import TransformersKwargs, can_return_tuple, maybe_autocast, merge_with_config_defaults
+from ...utils.output_capturing import capture_outputs
+from .configuration_eurobert import EuroBertConfig
+
+
+@use_kernel_forward_from_hub("RMSNorm")
+class EuroBertRMSNorm(nn.Module):
+ def __init__(self, hidden_size, eps=1e-5) -> None:
+ """
+ EuroBertRMSNorm is equivalent to T5LayerNorm
+ """
+ super().__init__()
+ self.weight = nn.Parameter(torch.ones(hidden_size))
+ self.variance_epsilon = eps
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ input_dtype = hidden_states.dtype
+ hidden_states = hidden_states.to(torch.float32)
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
+ return self.weight * hidden_states.to(input_dtype)
+
+ def extra_repr(self):
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
+
+
+def rotate_half(x):
+ """Rotates half the hidden dims of the input."""
+ x1 = x[..., : x.shape[-1] // 2]
+ x2 = x[..., x.shape[-1] // 2 :]
+ return torch.cat((-x2, x1), dim=-1)
+
+
+@use_kernel_func_from_hub("rotary_pos_emb")
+def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
+ """Applies Rotary Position Embedding to the query and key tensors.
+
+ Args:
+ q (`torch.Tensor`): The query tensor.
+ k (`torch.Tensor`): The key tensor.
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
+ Returns:
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
+ """
+ cos = cos.unsqueeze(unsqueeze_dim)
+ sin = sin.unsqueeze(unsqueeze_dim)
+ q_embed = (q * cos) + (rotate_half(q) * sin)
+ k_embed = (k * cos) + (rotate_half(k) * sin)
+ return q_embed, k_embed
+
+
+def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
+ """
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
+ """
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
+ if n_rep == 1:
+ return hidden_states
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
+
+
+def eager_attention_forward(
+ module: nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: torch.Tensor | None,
+ scaling: float,
+ dropout: float = 0.0,
+ **kwargs: Unpack[TransformersKwargs],
+):
+ key_states = repeat_kv(key, module.num_key_value_groups)
+ value_states = repeat_kv(value, module.num_key_value_groups)
+
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
+ if attention_mask is not None:
+ attn_weights = attn_weights + attention_mask
+
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
+ attn_output = torch.matmul(attn_weights, value_states)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+
+ return attn_output, attn_weights
+
+
+@use_kernelized_func(apply_rotary_pos_emb)
+class EuroBertAttention(nn.Module):
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
+
+ def __init__(self, config: EuroBertConfig, layer_idx: int):
+ super().__init__()
+ self.config = config
+ self.layer_idx = layer_idx
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
+ self.scaling = self.head_dim**-0.5
+ self.attention_dropout = config.attention_dropout
+ self.is_causal = False
+
+ self.q_proj = nn.Linear(
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
+ )
+ self.k_proj = nn.Linear(
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
+ )
+ self.v_proj = nn.Linear(
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
+ )
+ self.o_proj = nn.Linear(
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
+ )
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
+ attention_mask: torch.Tensor | None = None,
+ past_key_values: Cache | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor, torch.Tensor]:
+ input_shape = hidden_states.shape[:-1]
+ hidden_shape = (*input_shape, -1, self.head_dim)
+
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+
+ cos, sin = position_embeddings
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
+
+ if past_key_values is not None:
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_states,
+ key_states,
+ value_states,
+ attention_mask,
+ dropout=0.0 if not self.training else self.attention_dropout,
+ scaling=self.scaling,
+ **kwargs,
+ )
+
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ attn_output = self.o_proj(attn_output)
+ return attn_output, attn_weights
+
+
+class EuroBertMLP(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.hidden_size = config.hidden_size
+ self.intermediate_size = config.intermediate_size
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
+ self.act_fn = ACT2FN[config.hidden_act]
+
+ def forward(self, x):
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
+ return down_proj
+
+
+class EuroBertDecoderLayer(GradientCheckpointingLayer):
+ def __init__(self, config: EuroBertConfig, layer_idx: int):
+ super().__init__()
+ self.hidden_size = config.hidden_size
+
+ self.self_attn = EuroBertAttention(config=config, layer_idx=layer_idx)
+
+ self.mlp = EuroBertMLP(config)
+ self.input_layernorm = EuroBertRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.post_attention_layernorm = EuroBertRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ use_cache: bool | None = False,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.Tensor:
+ residual = hidden_states
+ hidden_states = self.input_layernorm(hidden_states)
+ # Self Attention
+ hidden_states, _ = self.self_attn(
+ hidden_states=hidden_states,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ position_embeddings=position_embeddings,
+ **kwargs,
+ )
+ hidden_states = residual + hidden_states
+
+ # Fully Connected
+ residual = hidden_states
+ hidden_states = self.post_attention_layernorm(hidden_states)
+ hidden_states = self.mlp(hidden_states)
+ hidden_states = residual + hidden_states
+ return hidden_states
+
+
+@auto_docstring
+class EuroBertPreTrainedModel(PreTrainedModel):
+ config: EuroBertConfig
+ base_model_prefix = "model"
+ supports_gradient_checkpointing = True
+ _no_split_modules = ["EuroBertDecoderLayer"]
+ _skip_keys_device_placement = ["past_key_values"]
+ _supports_flash_attn = True
+ _supports_sdpa = True
+ _supports_flex_attn = True
+
+ _can_compile_fullgraph = True
+ _supports_attention_backend = True
+ _can_record_outputs = {
+ "hidden_states": EuroBertDecoderLayer,
+ "attentions": EuroBertAttention,
+ }
+
+
+class EuroBertRotaryEmbedding(nn.Module):
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
+
+ def __init__(self, config: EuroBertConfig, device=None):
+ super().__init__()
+ self.max_seq_len_cached = config.max_position_embeddings
+ self.original_max_seq_len = config.max_position_embeddings
+
+ self.config = config
+
+ self.rope_type = self.config.rope_parameters["rope_type"]
+ rope_init_fn: Callable = self.compute_default_rope_parameters
+ if self.rope_type != "default":
+ rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
+ inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
+
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
+ self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
+
+ @staticmethod
+ def compute_default_rope_parameters(
+ config: EuroBertConfig | None = None,
+ device: Optional["torch.device"] = None,
+ seq_len: int | None = None,
+ ) -> tuple["torch.Tensor", float]:
+ """
+ Computes the inverse frequencies according to the original RoPE implementation
+ Args:
+ config ([`~transformers.PreTrainedConfig`]):
+ The model configuration.
+ device (`torch.device`):
+ The device to use for initialization of the inverse frequencies.
+ seq_len (`int`, *optional*):
+ The current sequence length. Unused for this type of RoPE.
+ Returns:
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
+ """
+ base = config.rope_parameters["rope_theta"]
+ dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
+
+ attention_factor = 1.0 # Unused in this type of RoPE
+
+ # Compute the inverse frequencies
+ inv_freq = 1.0 / (
+ base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
+ )
+ return inv_freq, attention_factor
+
+ @torch.no_grad()
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
+ def forward(self, x, position_ids):
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
+ position_ids_expanded = position_ids[:, None, :].float()
+
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
+ with maybe_autocast(device_type=device_type, enabled=False): # Force float32
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
+ emb = torch.cat((freqs, freqs), dim=-1)
+ cos = emb.cos() * self.attention_scaling
+ sin = emb.sin() * self.attention_scaling
+
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
+
+
+@auto_docstring
+class EuroBertModel(EuroBertPreTrainedModel):
+ def __init__(self, config: EuroBertConfig):
+ super().__init__(config)
+ self.padding_idx = config.pad_token_id
+ self.vocab_size = config.vocab_size
+
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
+ self.layers = nn.ModuleList(
+ [EuroBertDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
+ )
+ self.norm = EuroBertRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.rotary_emb = EuroBertRotaryEmbedding(config=config)
+ self.gradient_checkpointing = False
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @merge_with_config_defaults
+ @capture_outputs
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutput:
+ if (input_ids is None) ^ (inputs_embeds is not None):
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
+
+ if inputs_embeds is None:
+ inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)
+
+ if position_ids is None:
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
+
+ bidirectional_mask = create_bidirectional_mask(
+ config=self.config,
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ )
+
+ hidden_states = inputs_embeds
+ position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
+
+ for encoder_layer in self.layers[: self.config.num_hidden_layers]:
+ hidden_states = encoder_layer(
+ hidden_states,
+ attention_mask=bidirectional_mask,
+ position_embeddings=position_embeddings,
+ position_ids=position_ids,
+ **kwargs,
+ )
+
+ hidden_states = self.norm(hidden_states)
+ return BaseModelOutput(
+ last_hidden_state=hidden_states,
+ )
+
+
+@auto_docstring
+class EuroBertForMaskedLM(EuroBertPreTrainedModel):
+ _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
+ _tp_plan = {"lm_head": "colwise_gather_output"}
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
+
+ def __init__(self, config: EuroBertConfig):
+ super().__init__(config)
+ self.model = EuroBertModel(config)
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, config.mlp_bias)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | MaskedLMOutput:
+ r"""
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, EuroBertForMaskedLM
+
+ >>> model = EuroBertForMaskedLM.from_pretrained("EuroBERT/EuroBERT-210m")
+ >>> tokenizer = AutoTokenizer.from_pretrained("EuroBERT/EuroBERT-210m")
+
+ >>> text = "The capital of France is <|mask|>."
+ >>> inputs = tokenizer(text, return_tensors="pt")
+ >>> outputs = model(**inputs)
+
+ >>> # To get predictions for the mask:
+ >>> masked_index = inputs["input_ids"][0].tolist().index(tokenizer.mask_token_id)
+ >>> predicted_token_id = outputs.logits[0, masked_index].argmax(axis=-1)
+ >>> predicted_token = tokenizer.decode(predicted_token_id)
+ >>> print("Predicted token:", predicted_token)
+ Predicted token: Paris
+ ```"""
+ outputs: BaseModelOutput = self.model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ **kwargs,
+ )
+
+ logits = self.lm_head(outputs.last_hidden_state)
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
+
+ return MaskedLMOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+class EuroBertForSequenceClassification(EuroBertPreTrainedModel):
+ def __init__(self, config: EuroBertConfig):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+ self.classifier_pooling = config.classifier_pooling
+
+ self.model = EuroBertModel(config)
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.activation = nn.GELU()
+ self.classifier = nn.Linear(config.hidden_size, self.num_labels)
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | SequenceClassifierOutput:
+ encoder_output = self.model(
+ input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ **kwargs,
+ )
+ last_hidden_state = encoder_output[0]
+
+ if self.classifier_pooling in ["bos", "mean"]:
+ if self.classifier_pooling == "bos":
+ pooled_output = last_hidden_state[:, 0]
+
+ elif self.classifier_pooling == "mean":
+ if attention_mask is None:
+ pooled_output = last_hidden_state.mean(dim=1)
+ else:
+ attention_mask = attention_mask.to(last_hidden_state.device)
+ pooled_output = (last_hidden_state * attention_mask.unsqueeze(-1)).sum(dim=1)
+ pooled_output /= attention_mask.sum(dim=1, keepdim=True)
+
+ pooled_output = self.dense(pooled_output)
+ pooled_output = self.activation(pooled_output)
+ logits = self.classifier(pooled_output)
+
+ elif self.classifier_pooling == "late":
+ x = self.dense(last_hidden_state)
+ x = self.activation(x)
+ logits = self.classifier(x)
+ if attention_mask is None:
+ logits = logits.mean(dim=1)
+ else:
+ attention_mask = attention_mask.to(logits.device)
+ logits = (logits * attention_mask.unsqueeze(-1)).sum(dim=1)
+ logits /= attention_mask.sum(dim=1, keepdim=True)
+
+ loss = None
+ if labels is not None:
+ labels = labels.to(logits.device)
+ if self.config.problem_type is None:
+ if self.num_labels == 1:
+ self.config.problem_type = "regression"
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
+ self.config.problem_type = "single_label_classification"
+ else:
+ self.config.problem_type = "multi_label_classification"
+
+ if self.config.problem_type == "regression":
+ loss_fct = MSELoss()
+ if self.num_labels == 1:
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
+ else:
+ loss = loss_fct(logits, labels)
+ elif self.config.problem_type == "single_label_classification":
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+ elif self.config.problem_type == "multi_label_classification":
+ loss_fct = BCEWithLogitsLoss()
+ loss = loss_fct(logits, labels)
+
+ return SequenceClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=encoder_output.hidden_states,
+ attentions=encoder_output.attentions,
+ )
+
+
+@auto_docstring
+class EuroBertForTokenClassification(EuroBertPreTrainedModel):
+ def __init__(self, config: EuroBertConfig):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+ self.model = EuroBertModel(config)
+
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.model.embed_tokens
+
+ def set_input_embeddings(self, value):
+ self.model.embed_tokens = value
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | TokenClassifierOutput:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+ outputs = self.model(
+ input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ **kwargs,
+ )
+ sequence_output = outputs[0]
+ logits = self.classifier(sequence_output)
+
+ loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+
+ return TokenClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+__all__ = [
+ "EuroBertPreTrainedModel",
+ "EuroBertModel",
+ "EuroBertForMaskedLM",
+ "EuroBertForSequenceClassification",
+ "EuroBertForTokenClassification",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/eurobert/modular_eurobert.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/eurobert/modular_eurobert.py
new file mode 100644
index 0000000000000000000000000000000000000000..19f965c84f737dfaef237fff8acdbf26130d0e3c
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/eurobert/modular_eurobert.py
@@ -0,0 +1,362 @@
+# Copyright 2025 Nicolas Boizard, Duarte M. Alves, Hippolyte Gisserot-Boukhlef and the EuroBert team. All rights reserved.
+#
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import torch
+from torch import nn
+from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
+
+from ...configuration_utils import strict
+from ...masking_utils import create_bidirectional_mask
+from ...modeling_outputs import BaseModelOutput, MaskedLMOutput, SequenceClassifierOutput, TokenClassifierOutput
+from ...modeling_rope_utils import RopeParameters
+from ...processing_utils import Unpack
+from ...utils import auto_docstring
+from ...utils.generic import TransformersKwargs, can_return_tuple
+from ..llama.configuration_llama import LlamaConfig
+from ..llama.modeling_llama import LlamaAttention, LlamaModel, LlamaPreTrainedModel, LlamaRMSNorm
+
+
+@auto_docstring(checkpoint="EuroBERT/EuroBERT-210m")
+@strict
+class EuroBertConfig(LlamaConfig):
+ r"""
+ mask_token_id (`int`, *optional*, defaults to 128002):
+ Mask token id.
+ classifier_pooling (`str`, *optional*, defaults to `"late"`):
+ The pooling strategy to use for the classifier. Can be one of ['bos', 'mean', 'late'].
+
+ ```python
+ >>> from transformers import EuroBertModel, EuroBertConfig
+
+ >>> # Initializing a EuroBert eurobert-base style configuration
+ >>> configuration = EuroBertConfig()
+
+ >>> # Initializing a model from the eurobert-base style configuration
+ >>> model = EuroBertModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "eurobert"
+
+ vocab_size: int = 128256
+ hidden_size: int = 768
+ intermediate_size: int = 3072
+ num_hidden_layers: int = 12
+ num_attention_heads: int = 12
+ num_key_value_heads: int | None = None
+ hidden_act: str = "silu"
+ max_position_embeddings: int = 8192
+ initializer_range: float = 0.02
+ rms_norm_eps: float = 1e-05
+ bos_token_id: int | None = 128000
+ eos_token_id: int | list[int] | None = 128001
+ pad_token_id: int | None = 128001
+ mask_token_id: int = 128002
+ pretraining_tp: int = 1
+ tie_word_embeddings: bool = False
+ rope_parameters: RopeParameters | dict | None = None
+ attention_bias: bool = False
+ attention_dropout: int | float = 0.0
+ mlp_bias: bool = False
+ head_dim: int | None = None
+ classifier_pooling: str = "late"
+
+ def __post_init__(self, **kwargs):
+ if self.num_key_value_heads is None:
+ self.num_key_value_heads = self.num_attention_heads
+ super().__post_init__(**kwargs)
+
+
+class EuroBertRMSNorm(LlamaRMSNorm):
+ def __init__(self, hidden_size, eps=1e-5):
+ super().__init__(hidden_size, eps)
+
+
+class EuroBertAttention(LlamaAttention):
+ def __init__(self, config: EuroBertConfig, layer_idx: int):
+ super().__init__(config, layer_idx)
+ self.is_causal = False
+
+
+class EuroBertPreTrainedModel(LlamaPreTrainedModel):
+ pass
+
+
+class EuroBertModel(LlamaModel):
+ def forward(
+ self,
+ input_ids: torch.LongTensor = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutput:
+ if (input_ids is None) ^ (inputs_embeds is not None):
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
+
+ if inputs_embeds is None:
+ inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)
+
+ if position_ids is None:
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
+
+ bidirectional_mask = create_bidirectional_mask(
+ config=self.config,
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ )
+
+ hidden_states = inputs_embeds
+ position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
+
+ for encoder_layer in self.layers[: self.config.num_hidden_layers]:
+ hidden_states = encoder_layer(
+ hidden_states,
+ attention_mask=bidirectional_mask,
+ position_embeddings=position_embeddings,
+ position_ids=position_ids,
+ **kwargs,
+ )
+
+ hidden_states = self.norm(hidden_states)
+ return BaseModelOutput(
+ last_hidden_state=hidden_states,
+ )
+
+
+@auto_docstring
+class EuroBertForMaskedLM(EuroBertPreTrainedModel):
+ _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
+ _tp_plan = {"lm_head": "colwise_gather_output"}
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
+
+ def __init__(self, config: EuroBertConfig):
+ super().__init__(config)
+ self.model = EuroBertModel(config)
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, config.mlp_bias)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | MaskedLMOutput:
+ r"""
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, EuroBertForMaskedLM
+
+ >>> model = EuroBertForMaskedLM.from_pretrained("EuroBERT/EuroBERT-210m")
+ >>> tokenizer = AutoTokenizer.from_pretrained("EuroBERT/EuroBERT-210m")
+
+ >>> text = "The capital of France is <|mask|>."
+ >>> inputs = tokenizer(text, return_tensors="pt")
+ >>> outputs = model(**inputs)
+
+ >>> # To get predictions for the mask:
+ >>> masked_index = inputs["input_ids"][0].tolist().index(tokenizer.mask_token_id)
+ >>> predicted_token_id = outputs.logits[0, masked_index].argmax(axis=-1)
+ >>> predicted_token = tokenizer.decode(predicted_token_id)
+ >>> print("Predicted token:", predicted_token)
+ Predicted token: Paris
+ ```"""
+ outputs: BaseModelOutput = self.model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ **kwargs,
+ )
+
+ logits = self.lm_head(outputs.last_hidden_state)
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
+
+ return MaskedLMOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+class EuroBertForSequenceClassification(EuroBertPreTrainedModel):
+ def __init__(self, config: EuroBertConfig):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+ self.classifier_pooling = config.classifier_pooling
+
+ self.model = EuroBertModel(config)
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.activation = nn.GELU()
+ self.classifier = nn.Linear(config.hidden_size, self.num_labels)
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | SequenceClassifierOutput:
+ encoder_output = self.model(
+ input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ **kwargs,
+ )
+ last_hidden_state = encoder_output[0]
+
+ if self.classifier_pooling in ["bos", "mean"]:
+ if self.classifier_pooling == "bos":
+ pooled_output = last_hidden_state[:, 0]
+
+ elif self.classifier_pooling == "mean":
+ if attention_mask is None:
+ pooled_output = last_hidden_state.mean(dim=1)
+ else:
+ attention_mask = attention_mask.to(last_hidden_state.device)
+ pooled_output = (last_hidden_state * attention_mask.unsqueeze(-1)).sum(dim=1)
+ pooled_output /= attention_mask.sum(dim=1, keepdim=True)
+
+ pooled_output = self.dense(pooled_output)
+ pooled_output = self.activation(pooled_output)
+ logits = self.classifier(pooled_output)
+
+ elif self.classifier_pooling == "late":
+ x = self.dense(last_hidden_state)
+ x = self.activation(x)
+ logits = self.classifier(x)
+ if attention_mask is None:
+ logits = logits.mean(dim=1)
+ else:
+ attention_mask = attention_mask.to(logits.device)
+ logits = (logits * attention_mask.unsqueeze(-1)).sum(dim=1)
+ logits /= attention_mask.sum(dim=1, keepdim=True)
+
+ loss = None
+ if labels is not None:
+ labels = labels.to(logits.device)
+ if self.config.problem_type is None:
+ if self.num_labels == 1:
+ self.config.problem_type = "regression"
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
+ self.config.problem_type = "single_label_classification"
+ else:
+ self.config.problem_type = "multi_label_classification"
+
+ if self.config.problem_type == "regression":
+ loss_fct = MSELoss()
+ if self.num_labels == 1:
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
+ else:
+ loss = loss_fct(logits, labels)
+ elif self.config.problem_type == "single_label_classification":
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+ elif self.config.problem_type == "multi_label_classification":
+ loss_fct = BCEWithLogitsLoss()
+ loss = loss_fct(logits, labels)
+
+ return SequenceClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=encoder_output.hidden_states,
+ attentions=encoder_output.attentions,
+ )
+
+
+@auto_docstring
+class EuroBertForTokenClassification(EuroBertPreTrainedModel):
+ def __init__(self, config: EuroBertConfig):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+ self.model = EuroBertModel(config)
+
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.model.embed_tokens
+
+ def set_input_embeddings(self, value):
+ self.model.embed_tokens = value
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | TokenClassifierOutput:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+ outputs = self.model(
+ input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ **kwargs,
+ )
+ sequence_output = outputs[0]
+ logits = self.classifier(sequence_output)
+
+ loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+
+ return TokenClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+__all__ = [
+ "EuroBertConfig",
+ "EuroBertPreTrainedModel",
+ "EuroBertModel",
+ "EuroBertForMaskedLM",
+ "EuroBertForSequenceClassification",
+ "EuroBertForTokenClassification",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/evolla/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/evolla/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..09be74f03397074c49bf0df9a34b67f695856131
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/evolla/__init__.py
@@ -0,0 +1,28 @@
+# Copyright 2025 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_evolla import *
+ from .modeling_evolla import *
+ from .processing_evolla import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/evolla/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/evolla/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bf383b6ec03c786c64c06900d92b98ea00e355e5
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/evolla/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/evolla/__pycache__/configuration_evolla.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/evolla/__pycache__/configuration_evolla.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..25b2df6fbed154073fcaa0744e9473b50d879dcf
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/evolla/__pycache__/configuration_evolla.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/evolla/__pycache__/modeling_evolla.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/evolla/__pycache__/modeling_evolla.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d12272872165625e59b1e49962faead15210aaf6
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/evolla/__pycache__/modeling_evolla.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/evolla/__pycache__/modular_evolla.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/evolla/__pycache__/modular_evolla.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1da3c1673081c8d257457db9a7d24a1908177119
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/evolla/__pycache__/modular_evolla.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/evolla/__pycache__/processing_evolla.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/evolla/__pycache__/processing_evolla.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..936a73de8be001dd8e733f66f6b656c0765b3f3b
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/evolla/__pycache__/processing_evolla.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/evolla/configuration_evolla.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/evolla/configuration_evolla.py
new file mode 100644
index 0000000000000000000000000000000000000000..3b683bb5240dc991edbcc85642f1cac4fcd3e0ea
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/evolla/configuration_evolla.py
@@ -0,0 +1,147 @@
+# Copyright 2025 Westlake Representational Learning Lab (Fajie Yuan Lab) team and the HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Evolla model configuration"""
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...modeling_rope_utils import RopeParameters
+from ...utils import auto_docstring, logging
+
+
+logger = logging.get_logger(__name__)
+
+
+@auto_docstring(checkpoint="westlake-repl/Evolla-10B-hf")
+@strict
+class SaProtConfig(PreTrainedConfig):
+ r"""
+ mask_token_id (`int`, *optional*, defaults to 4):
+ The id of the *mask* token in the protein sequence model.
+ position_embedding_type (`str`, *optional*, defaults to `"rotary"`):
+ The type of position embedding to use in the protein sequence model. Currently only `"rotary"` is supported.
+ rope_theta (`float`, *optional*, defaults to 10000.0):
+ The base period of the RoPE embeddings.
+ emb_layer_norm_before (`bool`, *optional*, defaults to `False`):
+ Whether to apply layer normalization before the position embedding in the protein sequence model.
+ token_dropout (`bool`, *optional*, defaults to `True`):
+ Whether to apply dropout to the tokens in the protein sequence model.
+ """
+
+ vocab_size: int = 446
+ mask_token_id: int = 4
+ pad_token_id: int = 1
+ hidden_size: int = 1280
+ num_hidden_layers: int = 33
+ num_attention_heads: int = 20
+ intermediate_size: int = 5120
+ hidden_dropout_prob: float | int = 0.1
+ attention_probs_dropout_prob: float | int = 0.1
+ max_position_embeddings: int = 1026
+ initializer_range: float = 0.02
+ layer_norm_eps: float = 1e-05
+ position_embedding_type: str = "rotary"
+ rope_theta: float = 10000.0
+ emb_layer_norm_before: bool = False
+ token_dropout: bool = True
+ is_decoder: bool = False
+ add_cross_attention: bool = False
+
+
+@auto_docstring(checkpoint="westlake-repl/Evolla-10B-hf")
+@strict
+class EvollaConfig(PreTrainedConfig):
+ r"""
+ protein_encoder_config (`dict`, *optional*):
+ Dictionary of configuration options used to initialize [`SaProtConfig`].
+ aligner_ffn_mult (`int`, *optional*, defaults to 4):
+ The FFN multiplier for the aligner layer.
+ aligner_enable_bias (`bool`, *optional*, defaults to `True`):
+ Whether to use bias in the aligner layer.
+ aligner_attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
+ The dropout ratio for the attention probabilities in the aligner layer.
+ aligner_num_add_layers (`int`, *optional*, defaults to 8):
+ The number of additional layers for the aligner layer.
+ resampler_depth (`int`, *optional*, defaults to 6):
+ The depth of the resampler layer in the llama model.
+ resampler_dim_head (`int`, *optional*, defaults to 64):
+ The dimension of the heads in the resampler layer in the llama model.
+ resampler_heads (`int`, *optional*, defaults to 8):
+ The number of heads in the resampler layer in the llama model.
+ resampler_num_latents (`int`, *optional*, defaults to 64):
+ The number of latents in the resampler layer in the llama model.
+ resampler_ff_mult (`int`, *optional*, defaults to 4):
+ The FFN multiplier for the resampler layer.
+
+ Example:
+
+ ```python
+ >>> from transformers import EvollaModel, EvollaConfig
+
+ >>> # Initializing a Evolla evolla-10b style configuration
+ >>> configuration = EvollaConfig()
+
+ >>> # Initializing a model from the evolla-10b style configuration
+ >>> model = EvollaModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "evolla"
+ sub_configs = {"protein_encoder_config": SaProtConfig}
+ default_theta = 500000.0
+
+ protein_encoder_config: dict | PreTrainedConfig | None = None
+ vocab_size: int = 128256 # llama vocab size
+ hidden_size: int = 4096 # llama hidden size
+ intermediate_size: int = 14336 # llama intermediate size
+ num_hidden_layers: int = 32 # llama num layers
+ num_attention_heads: int = 32 # llama num heads
+ num_key_value_heads: int | None = 8 # llama num key-value heads
+ hidden_act: str = "silu" # llama activation function
+ max_position_embeddings: int = 8192 # llama rope max length
+ rms_norm_eps: float = 1e-05
+ rope_parameters: RopeParameters | dict | None = None
+ attention_bias: bool = False
+ attention_dropout: float | int | None = 0.0
+ mlp_bias: bool = False
+ aligner_ffn_mult: int | None = 4
+ aligner_enable_bias: bool | None = True
+ aligner_attention_probs_dropout_prob: float | None = 0.1
+ aligner_num_add_layers: int | None = 8
+ resampler_depth: int | None = 6
+ resampler_dim_head: int | None = 64
+ resampler_heads: int | None = 8
+ resampler_num_latents: int | None = 64
+ resampler_ff_mult: int | None = 4
+ initializer_range: float = 0.02
+ pad_token_id: int | None = None
+ bos_token_id: int | None = 128000
+ eos_token_id: int | list[int] | None = 128009
+ use_cache: bool = False
+ tie_word_embeddings: bool = False
+ is_decoder: bool | None = False
+ add_cross_attention: bool | None = False
+
+ def __post_init__(self, **kwargs):
+ if self.protein_encoder_config is None:
+ self.protein_encoder_config = SaProtConfig()
+ logger.info("`protein_encoder_config` is `None`. Initializing the `SaProtConfig` with default values.")
+ elif isinstance(self.protein_encoder_config, dict):
+ self.protein_encoder_config = SaProtConfig(**self.protein_encoder_config)
+ super().__post_init__(**kwargs)
+
+
+__all__ = ["EvollaConfig"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/evolla/modeling_evolla.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/evolla/modeling_evolla.py
new file mode 100644
index 0000000000000000000000000000000000000000..e3e67d6f51e7c83564d1a722b8073abb960e5bb4
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/evolla/modeling_evolla.py
@@ -0,0 +1,1517 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/evolla/modular_evolla.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_evolla.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2025 Westlake Representational Learning Lab (Fajie Yuan Lab) team and the HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import math
+from collections.abc import Callable
+from dataclasses import dataclass
+from typing import Optional
+
+import torch
+from torch import nn
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...cache_utils import Cache, DynamicCache
+from ...generation import GenerationMixin
+from ...integrations import use_kernel_forward_from_hub, use_kernel_func_from_hub, use_kernelized_func
+from ...masking_utils import create_bidirectional_mask, create_causal_mask
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import (
+ BaseModelOutputWithCrossAttentions,
+ BaseModelOutputWithPast,
+ BaseModelOutputWithPoolingAndCrossAttentions,
+ CausalLMOutputWithPast,
+ ModelOutput,
+)
+from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import TransformersKwargs, auto_docstring, can_return_tuple
+from ...utils.generic import maybe_autocast, merge_with_config_defaults
+from ...utils.output_capturing import OutputRecorder, capture_outputs
+from .configuration_evolla import EvollaConfig, SaProtConfig
+
+
+def create_position_ids_from_input_ids(input_ids, padding_idx):
+ """
+ Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols
+ are ignored. This is modified from fairseq's `utils.make_positions`.
+
+ Args:
+ x: torch.Tensor x:
+
+ Returns: torch.Tensor
+ """
+ # The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA.
+ mask = input_ids.ne(padding_idx).int()
+ incremental_indices = torch.cumsum(mask, dim=1).type_as(mask) * mask
+ return incremental_indices.long() + padding_idx
+
+
+class EvollaSaProtEmbeddings(nn.Module):
+ """
+ Same as BertEmbeddings with a tiny tweak for positional embeddings indexing.
+ """
+
+ def __init__(self, config):
+ super().__init__()
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
+
+ if config.emb_layer_norm_before:
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ else:
+ self.layer_norm = None
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
+ self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
+ self.register_buffer(
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
+ )
+
+ self.padding_idx = config.pad_token_id
+ if self.position_embedding_type == "absolute":
+ self.position_embeddings = nn.Embedding(
+ config.max_position_embeddings, config.hidden_size, padding_idx=self.padding_idx
+ )
+ self.token_dropout = config.token_dropout
+ self.mask_token_id = config.mask_token_id
+ # remove the position_ids in EsmEmbeddings
+ self.position_ids = None
+
+ def forward(
+ self,
+ input_ids=None,
+ attention_mask=None,
+ position_ids=None,
+ inputs_embeds=None,
+ ):
+ if position_ids is None:
+ if input_ids is not None:
+ # Create the position ids from the input token ids. Any padded tokens remain padded.
+ position_ids = create_position_ids_from_input_ids(input_ids, self.padding_idx)
+ else:
+ position_ids = self.create_position_ids_from_inputs_embeds(inputs_embeds)
+
+ if inputs_embeds is None:
+ inputs_embeds = self.word_embeddings(input_ids)
+
+ # Note that if we want to support EVOLLA_SA_PROT-1 (not 1b!) in future then we need to support an
+ # embedding_scale factor here.
+ embeddings = inputs_embeds
+
+ # Matt: EVOLLA_SA_PROT has the option to handle masking in MLM in a slightly unusual way. If the token_dropout
+ # flag is False then it is handled in the same was as BERT/RoBERTa. If it is set to True, however,
+ # masked tokens are treated as if they were selected for input dropout and zeroed out.
+ # This "mask-dropout" is compensated for when masked tokens are not present, by scaling embeddings by
+ # a factor of (fraction of unmasked tokens during training) / (fraction of unmasked tokens in sample).
+ # This is analogous to the way that dropout layers scale down outputs during evaluation when not
+ # actually dropping out values (or, equivalently, scale up their un-dropped outputs in training).
+ if self.token_dropout and input_ids is not None:
+ embeddings = embeddings.masked_fill((input_ids == self.mask_token_id).unsqueeze(-1), 0.0)
+ mask_ratio_train = 0.15 * 0.8 # Hardcoded as the ratio used in all EVOLLA_SA_PROT model training runs
+ src_lengths = attention_mask.sum(-1) if attention_mask is not None else input_ids.shape[1]
+ mask_ratio_observed = (input_ids == self.mask_token_id).sum(-1).float() / src_lengths
+ embeddings = (embeddings * (1 - mask_ratio_train) / (1 - mask_ratio_observed)[:, None, None]).to(
+ embeddings.dtype
+ )
+
+ if self.position_embedding_type == "absolute":
+ position_embeddings = self.position_embeddings(position_ids)
+ embeddings = embeddings + position_embeddings
+
+ if self.layer_norm is not None:
+ embeddings = self.layer_norm(embeddings)
+ if attention_mask is not None:
+ embeddings = (embeddings * attention_mask.unsqueeze(-1)).to(embeddings.dtype)
+ # Matt: I think this line was copied incorrectly from BERT, disabling it for now.
+ # embeddings = self.dropout(embeddings)
+ return embeddings
+
+ def create_position_ids_from_inputs_embeds(self, inputs_embeds):
+ """
+ We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids.
+
+ Args:
+ inputs_embeds: torch.Tensor
+
+ Returns: torch.Tensor
+ """
+ input_shape = inputs_embeds.size()[:-1]
+ sequence_length = input_shape[1]
+
+ position_ids = torch.arange(
+ self.padding_idx + 1, sequence_length + self.padding_idx + 1, dtype=torch.long, device=inputs_embeds.device
+ )
+ return position_ids.unsqueeze(0).expand(input_shape)
+
+
+class EvollaSaProtRotaryEmbedding(nn.Module):
+ """
+ Rotary position embeddings.
+ Implementation based on [ModernBERT's RotaryEmbedding](https://github.com/huggingface/transformers/blob/aad13b87ed59f2afcfaebc985f403301887a35fc/src/transformers/models/modernbert/modeling_modernbert.py#L94).
+ """
+
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
+
+ def __init__(self, config: SaProtConfig, device=None):
+ super().__init__()
+
+ self.config = config
+ self.rope_type = {}
+
+ curr_inv_freq, curr_attention_scaling = self.compute_default_rope_parameters(self.config, device)
+ self.register_buffer("inv_freq", curr_inv_freq)
+ setattr(self, "attention_scaling", curr_attention_scaling)
+
+ @staticmethod
+ def compute_default_rope_parameters(
+ config: SaProtConfig | None = None,
+ device: "torch.device | None" = None,
+ seq_len: int | None = None,
+ ) -> tuple["torch.Tensor", float]:
+ """
+ Computes the inverse frequencies according to the original RoPE implementation
+ Args:
+ config ([`~transformers.PreTrainedConfig`]):
+ The model configuration.
+ device (`torch.device`):
+ The device to use for initialization of the inverse frequencies.
+ seq_len (`int`, *optional*):
+ The current sequence length. Unused for this type of RoPE.
+
+ Returns:
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
+ """
+ base = config.rope_theta
+ dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
+
+ attention_factor = 1.0 # Unused in this type of RoPE
+
+ # Compute the inverse frequencies
+ inv_freq = 1.0 / (
+ base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
+ )
+ return inv_freq, attention_factor
+
+ @torch.no_grad()
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
+ def forward(self, x, position_ids, layer_type=None):
+ inv_freq = getattr(self, "inv_freq")
+ attention_scaling = getattr(self, "attention_scaling")
+
+ inv_freq_expanded = inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
+ position_ids_expanded = position_ids[:, None, :].float()
+
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
+ with maybe_autocast(device_type=device_type, enabled=False): # Force float32
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
+ emb = torch.cat((freqs, freqs), dim=-1)
+ cos = emb.cos() * attention_scaling
+ sin = emb.sin() * attention_scaling
+
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
+
+
+def rotate_half(x):
+ """Rotates half the hidden dims of the input."""
+ x1 = x[..., : x.shape[-1] // 2]
+ x2 = x[..., x.shape[-1] // 2 :]
+ return torch.cat((-x2, x1), dim=-1)
+
+
+@use_kernel_func_from_hub("rotary_pos_emb")
+def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
+ """Applies Rotary Position Embedding to the query and key tensors.
+
+ Args:
+ q (`torch.Tensor`): The query tensor.
+ k (`torch.Tensor`): The key tensor.
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
+ Returns:
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
+ """
+ original_dtype = q.dtype
+ cos = cos.unsqueeze(unsqueeze_dim)
+ sin = sin.unsqueeze(unsqueeze_dim)
+ q_embed = (q.float() * cos) + (rotate_half(q.float()) * sin)
+ k_embed = (k.float() * cos) + (rotate_half(k.float()) * sin)
+ return q_embed.to(original_dtype), k_embed.to(original_dtype)
+
+
+def eager_attention_forward(
+ module: nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: torch.Tensor | None,
+ scaling: float | None = None,
+ dropout: float = 0.0,
+ **kwargs: Unpack[TransformersKwargs],
+):
+ if scaling is None:
+ scaling = query.size(-1) ** -0.5
+
+ # Take the dot product between "query" and "key" to get the raw attention scores.
+ attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
+
+ if attention_mask is not None:
+ attn_weights = attn_weights + attention_mask
+
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
+
+ attn_output = torch.matmul(attn_weights, value)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+
+ return attn_output, attn_weights
+
+
+@use_kernelized_func(apply_rotary_pos_emb)
+class EvollaSaProtSelfAttention(nn.Module):
+ def __init__(self, config, position_embedding_type=None, layer_idx=None, is_cross_attention=False):
+ super().__init__()
+ self.config = config
+
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
+ raise ValueError(
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
+ f"heads ({config.num_attention_heads})"
+ )
+
+ self.num_attention_heads = config.num_attention_heads
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
+
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
+
+ self.dropout = config.attention_probs_dropout_prob
+
+ self.position_embedding_type = position_embedding_type or getattr(
+ config, "position_embedding_type", "absolute"
+ )
+ self.scaling = 1.0 # For BC we apply scaling before RoPE
+ self.is_decoder = config.is_decoder
+ self.layer_idx = layer_idx
+ self.is_causal = self.is_decoder and not is_cross_attention
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.FloatTensor | None = None,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ encoder_attention_mask: torch.FloatTensor | None = None,
+ position_embeddings: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor]:
+ input_shape = hidden_states.shape[:-1]
+ hidden_shape = (*input_shape, -1, self.attention_head_size)
+
+ query_layer = self.query(hidden_states).view(hidden_shape).transpose(1, 2)
+
+ is_cross_attention = encoder_hidden_states is not None
+ current_states = encoder_hidden_states if is_cross_attention else hidden_states
+ attention_mask = encoder_attention_mask if is_cross_attention else attention_mask
+ key_layer = self.key(current_states).view(hidden_shape).transpose(1, 2)
+ value_layer = self.value(current_states).view(hidden_shape).transpose(1, 2)
+
+ # Matt: Our BERT model (which this code was derived from) scales attention logits down by sqrt(head_dim).
+ # EVOLLA_SA_PROT scales the query down by the same factor instead. Modulo numerical stability these are equivalent,
+ # but not when rotary embeddings get involved. Therefore, we scale the query here to match the original
+ # EVOLLA_SA_PROT code and fix rotary embeddings.
+ query_layer = query_layer * self.attention_head_size**-0.5
+
+ if self.position_embedding_type == "rotary":
+ cos, sin = position_embeddings
+ query_layer, key_layer = apply_rotary_pos_emb(query_layer, key_layer, cos, sin, unsqueeze_dim=1)
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_layer,
+ key_layer,
+ value_layer,
+ attention_mask,
+ dropout=0.0 if not self.training else self.dropout,
+ scaling=self.scaling,
+ **kwargs,
+ )
+
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ return attn_output, attn_weights
+
+
+class EvollaSaProtSelfOutput(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(self, hidden_states, input_tensor):
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = hidden_states + input_tensor
+ return hidden_states
+
+
+class EvollaSaProtAttention(nn.Module):
+ def __init__(self, config, layer_idx=None, is_cross_attention=False):
+ super().__init__()
+ self.self = EvollaSaProtSelfAttention(config, layer_idx=layer_idx, is_cross_attention=is_cross_attention)
+ self.output = EvollaSaProtSelfOutput(config)
+
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+
+ def forward(
+ self,
+ hidden_states,
+ attention_mask=None,
+ encoder_hidden_states=None,
+ encoder_attention_mask=None,
+ position_embeddings: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ):
+ hidden_states_ln = self.LayerNorm(hidden_states)
+ attn_output, _ = self.self(
+ hidden_states_ln,
+ attention_mask=attention_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ position_embeddings=position_embeddings,
+ **kwargs,
+ )
+ attn_output = self.output(attn_output, hidden_states)
+ return attn_output
+
+
+def gelu(x):
+ """
+ This is the gelu implementation from the original EVOLLA_SA_PROT repo. Using F.gelu yields subtly wrong results.
+ """
+ return x * 0.5 * (1.0 + torch.erf(x / math.sqrt(2.0)))
+
+
+class EvollaSaProtIntermediate(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = gelu(hidden_states)
+ return hidden_states
+
+
+class EvollaSaProtOutput(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(self, hidden_states, input_tensor):
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = hidden_states + input_tensor
+ return hidden_states
+
+
+class EvollaSaProtLayer(GradientCheckpointingLayer):
+ def __init__(self, config):
+ super().__init__()
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
+ self.seq_len_dim = 1
+ self.attention = EvollaSaProtAttention(config)
+ self.is_decoder = config.is_decoder
+ self.add_cross_attention = config.add_cross_attention
+ if self.add_cross_attention:
+ if not self.is_decoder:
+ raise RuntimeError(f"{self} should be used as a decoder model if cross attention is added")
+ self.crossattention = EvollaSaProtAttention(config, is_cross_attention=True)
+ self.intermediate = EvollaSaProtIntermediate(config)
+ self.output = EvollaSaProtOutput(config)
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+
+ def forward(
+ self,
+ hidden_states,
+ attention_mask=None,
+ encoder_hidden_states=None,
+ encoder_attention_mask=None,
+ position_embeddings: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ):
+ attention_output = self.attention(
+ hidden_states,
+ attention_mask=attention_mask,
+ position_embeddings=position_embeddings,
+ **kwargs,
+ )
+
+ if self.is_decoder and encoder_hidden_states is not None:
+ if not hasattr(self, "crossattention"):
+ raise AttributeError(
+ f"If `encoder_hidden_states` are passed, {self} has to be instantiated"
+ " with cross-attention layers by setting `config.add_cross_attention=True`"
+ )
+
+ attention_output = self.crossattention(
+ attention_output,
+ attention_mask=attention_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ position_embeddings=position_embeddings,
+ **kwargs,
+ )
+
+ layer_output = self.feed_forward_chunk(attention_output)
+ return layer_output
+
+ def feed_forward_chunk(self, attention_output):
+ attention_output_ln = self.LayerNorm(attention_output)
+ intermediate_output = self.intermediate(attention_output_ln)
+ layer_output = self.output(intermediate_output, attention_output)
+ return layer_output
+
+
+class EvollaSaProtEncoder(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.layer = nn.ModuleList([EvollaSaProtLayer(config) for _ in range(config.num_hidden_layers)])
+ self.emb_layer_norm_after = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.gradient_checkpointing = False
+
+ @can_return_tuple
+ def forward(
+ self,
+ hidden_states,
+ attention_mask=None,
+ encoder_hidden_states=None,
+ encoder_attention_mask=None,
+ position_embeddings: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ):
+ for i, layer_module in enumerate(self.layer):
+ hidden_states = layer_module(
+ hidden_states,
+ attention_mask=attention_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ position_embeddings=position_embeddings,
+ **kwargs,
+ )
+
+ if self.emb_layer_norm_after:
+ hidden_states = self.emb_layer_norm_after(hidden_states)
+
+ return BaseModelOutputWithCrossAttentions(last_hidden_state=hidden_states)
+
+
+class EvollaSaProtPooler(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.activation = nn.Tanh()
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ # We "pool" the model by simply taking the hidden state corresponding
+ # to the first token.
+ first_token_tensor = hidden_states[:, 0]
+ pooled_output = self.dense(first_token_tensor)
+ pooled_output = self.activation(pooled_output)
+ return pooled_output
+
+
+@auto_docstring
+class EvollaSaProtPreTrainedModel(PreTrainedModel):
+ config: SaProtConfig
+ _no_split_modules = ["EvollaSaProtLayer"]
+ _supports_flash_attn = True
+ _supports_sdpa = True
+ _supports_flex_attn = True
+ _supports_attention_backend = True
+
+ _can_record_outputs = {
+ "hidden_states": EvollaSaProtLayer,
+ "attentions": [OutputRecorder(EvollaSaProtSelfAttention, index=1, layer_name="attention")],
+ "cross_attentions": [
+ OutputRecorder(EvollaSaProtSelfAttention, index=1, layer_name="crossattention"),
+ ],
+ }
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ super()._init_weights(module)
+ if isinstance(module, EvollaSaProtRotaryEmbedding):
+ curr_inv_freq, _ = module.compute_default_rope_parameters(module.config)
+ init.copy_(getattr(module, "inv_freq"), curr_inv_freq)
+
+
+class EvollaSaProtProteinEncoder(EvollaSaProtPreTrainedModel):
+ def __init__(self, config: SaProtConfig):
+ super().__init__(config)
+ self.embeddings = EvollaSaProtEmbeddings(config)
+ self.rotary_embeddings = EvollaSaProtRotaryEmbedding(config=config)
+ self.encoder = EvollaSaProtEncoder(config)
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.embeddings.word_embeddings
+
+ def set_input_embeddings(self, value):
+ self.embeddings.word_embeddings = value
+
+ @merge_with_config_defaults
+ @capture_outputs
+ def forward(
+ self,
+ input_ids: torch.Tensor | None,
+ attention_mask: torch.Tensor | None = None,
+ **kwargs,
+ ) -> tuple[torch.Tensor] | BaseModelOutputWithPoolingAndCrossAttentions:
+ input_shape = input_ids.size()
+ batch_size, seq_length = input_shape
+
+ device = input_ids.device
+ if attention_mask is None:
+ attention_mask = torch.ones(((batch_size, seq_length)), device=device)
+ inputs_embeds = self.embeddings(input_ids=input_ids, attention_mask=attention_mask)
+
+ attention_mask = create_bidirectional_mask(
+ config=self.config,
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ )
+
+ position_ids = torch.arange(seq_length, device=device).unsqueeze(0)
+ position_embeddings = self.rotary_embeddings(inputs_embeds, position_ids)
+
+ encoder_outputs = self.encoder(
+ inputs_embeds, attention_mask=attention_mask, position_embeddings=position_embeddings, **kwargs
+ )
+ sequence_output = encoder_outputs[0]
+
+ return BaseModelOutputWithPoolingAndCrossAttentions(
+ last_hidden_state=sequence_output,
+ hidden_states=encoder_outputs.hidden_states,
+ attentions=encoder_outputs.attentions,
+ cross_attentions=encoder_outputs.cross_attentions,
+ )
+
+
+class EvollaSequenceCompressorAttention(nn.Module):
+ def __init__(self, dim, dim_head=64, heads=8):
+ super().__init__()
+ self.scale = dim_head**-0.5
+ self.heads = heads
+ inner_dim = dim_head * heads
+
+ self.norm_media = nn.LayerNorm(dim)
+ self.norm_latents = nn.LayerNorm(dim)
+
+ self.to_q = nn.Linear(dim, inner_dim, bias=False)
+ self.to_kv = nn.Linear(dim, inner_dim * 2, bias=False)
+ self.to_out = nn.Linear(inner_dim, dim, bias=False)
+
+ def forward(self, x, latents, mask):
+ """
+ Args:
+ x (torch.Tensor): image features
+ shape (b, n1, D)
+ latent (torch.Tensor): latent features
+ shape (b, n2, D); n2: num of latent tokens
+ """
+ x = self.norm_media(x)
+ latents = self.norm_latents(latents)
+
+ h = self.heads
+
+ q = self.to_q(latents)
+ kv_input = torch.cat((x, latents), dim=-2)
+ k, v = self.to_kv(kv_input).chunk(
+ 2, dim=-1
+ ) # each: batch_size, max_protein_length+num_latents, dim_head*num_heads
+
+ q = q.view(q.size(0), q.size(1), h, -1).permute(0, 2, 1, 3)
+ k = k.view(k.size(0), k.size(1), h, -1).permute(0, 2, 1, 3)
+ v = v.view(v.size(0), v.size(1), h, -1).permute(0, 2, 1, 3)
+ q = q * self.scale # batch_size, num_heads, num_latents, dim_head
+
+ # attention
+ sim = torch.matmul(q, k.transpose(-1, -2))
+ sim = sim - sim.amax(dim=-1, keepdim=True).detach()
+ bs, nh, skd, okd = sim.shape
+ ones = torch.ones(nh, skd).to(mask.device) # Create a tensor of ones with shape (nh, skd)
+ mask_exp = mask[:, None, None, :]
+ ones_exp = ones[None, :, :, None]
+ mask = mask_exp * ones_exp
+
+ sim = sim.masked_fill((1 - mask).bool(), -1e4)
+ attn = sim.softmax(dim=-1)
+ out = torch.matmul(attn, v)
+ out = out.permute(0, 2, 1, 3)
+
+ # [batch, seq, head, features] -> [batch, seq, head*features]
+ out = out.reshape(out.size(0), out.size(1), -1)
+
+ return self.to_out(out)
+
+
+class EvollaFeedForward(nn.Module):
+ def __init__(self, dim, mult=4):
+ super().__init__()
+ inner_dim = int(dim * mult)
+
+ self.norm = nn.LayerNorm(dim)
+ self.fc1 = nn.Linear(dim, inner_dim, bias=False)
+ self.activation = nn.GELU()
+ self.fc2 = nn.Linear(inner_dim, dim, bias=False)
+
+ def forward(self, x):
+ return self.fc2(self.activation(self.fc1(self.norm(x))))
+
+
+class EvollaSequenceCompressorResampler(nn.Module):
+ def __init__(self, config: EvollaConfig):
+ super().__init__()
+ protein_repr_dim = config.protein_encoder_config.hidden_size
+ self.num_latents = config.resampler_num_latents
+ self.latents = nn.Parameter(torch.randn(self.num_latents, protein_repr_dim), requires_grad=True)
+ self.layers = nn.ModuleList([])
+ for _ in range(config.resampler_depth):
+ self.layers.append(
+ nn.ModuleList(
+ [
+ EvollaSequenceCompressorAttention(
+ dim=protein_repr_dim, dim_head=config.resampler_dim_head, heads=config.resampler_heads
+ ),
+ EvollaFeedForward(dim=protein_repr_dim, mult=config.resampler_ff_mult),
+ ]
+ )
+ )
+
+ self.norm = nn.LayerNorm(config.hidden_size)
+ self.protein_projector = nn.Linear(protein_repr_dim, config.hidden_size)
+
+ def forward(self, embeds, mask):
+ b = embeds.shape[0]
+
+ bs, _ = mask.shape # bs, max_protein_length
+ latent_mask = torch.ones(bs, self.num_latents).to(mask.device)
+ mask = torch.cat((mask, latent_mask), dim=1) # bs, max_protein_length + num_latents
+
+ # blocks
+ ones = torch.ones(b).to(self.latents.device)
+ latents = self.latents[None] * ones.view(-1, 1, 1) # [b,n,d]
+ latents = latents.to(embeds.dtype)
+ for attn, ff in self.layers:
+ latents = attn(embeds, latents, mask) + latents
+ latents = ff(latents) + latents
+
+ transformed_feature = self.protein_projector(latents)
+
+ return self.norm(transformed_feature)
+
+
+@auto_docstring
+@dataclass
+class EvollaProteinEncoderModelOutput(ModelOutput):
+ r"""
+ sequence_compressor_output (`torch.FloatTensor` of shape `(batch_size, compressed_seq_len, hidden_size)`, *optional*):
+ Compressed sequence representation produced by the sequence compressor module. The sequence length is
+ reduced from the original input length to `compressed_seq_len` via learned compression.
+ """
+
+ sequence_compressor_output: torch.FloatTensor | None = None
+ last_hidden_state: torch.FloatTensor | None = None
+ hidden_states: tuple[torch.FloatTensor, ...] | None = None
+ attentions: tuple[torch.FloatTensor, ...] | None = None
+
+
+class EvollaProteinEncoder(nn.Module):
+ def __init__(self, config: EvollaConfig):
+ super().__init__()
+ self.model = EvollaSaProtProteinEncoder(config=config.protein_encoder_config)
+ self.sequence_compressor_resampler = EvollaSequenceCompressorResampler(config=config)
+
+ @can_return_tuple
+ def forward(self, input_ids: torch.LongTensor, attention_mask: torch.FloatTensor, **kwargs):
+ protein_output = self.model(input_ids=input_ids, attention_mask=attention_mask)
+ protein_embeds = protein_output.last_hidden_state
+ sequence_repr = self.sequence_compressor_resampler(protein_embeds, attention_mask)
+
+ return EvollaProteinEncoderModelOutput(
+ sequence_compressor_output=sequence_repr,
+ last_hidden_state=protein_output.last_hidden_state,
+ )
+
+
+class EvollaSequenceAlignerCrossAttention(nn.Module):
+ def __init__(
+ self,
+ config,
+ protein_encoder_dim: int | None = None,
+ structure_encoder_dim: int | None = None,
+ msa_encoder_dim: int | None = None,
+ ):
+ super().__init__()
+
+ self.hidden_size = config.hidden_size
+ self.num_attention_heads = config.num_attention_heads
+ self.scale = self.num_attention_heads**-0.5
+ self.attention_head_size = int(self.hidden_size / self.num_attention_heads)
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
+
+ attention_probs_dropout_prob = config.aligner_attention_probs_dropout_prob
+ enable_bias = config.aligner_enable_bias
+ ffn_mult = config.aligner_ffn_mult
+
+ self.query = nn.Linear(self.hidden_size, self.all_head_size)
+ if protein_encoder_dim is not None:
+ self.key_protein = nn.Linear(protein_encoder_dim, self.all_head_size)
+ self.value_protein = nn.Linear(protein_encoder_dim, self.all_head_size)
+ else:
+ self.key_protein = None
+ self.value_protein = None
+
+ if structure_encoder_dim is not None:
+ self.key_structure = nn.Linear(structure_encoder_dim, self.all_head_size)
+ self.value_structure = nn.Linear(structure_encoder_dim, self.all_head_size)
+ else:
+ self.key_structure = None
+ self.value_structure = None
+
+ if msa_encoder_dim is not None:
+ self.key_msa = nn.Linear(msa_encoder_dim, self.all_head_size)
+ self.value_msa = nn.Linear(msa_encoder_dim, self.all_head_size)
+ else:
+ self.key_msa = None
+ self.value_msa = None
+
+ self.attention_norm = EvollaRMSNorm(self.hidden_size)
+
+ self.dropout = nn.Dropout(attention_probs_dropout_prob)
+
+ self.out_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=enable_bias)
+
+ self.ff = EvollaFeedForward(self.hidden_size, ffn_mult)
+ self.gate_attention = nn.Parameter(torch.tensor([0.0]))
+ self.gate_ffw = nn.Parameter(torch.tensor([0.0]))
+
+ def cross_attention(
+ self,
+ query_states,
+ protein_key_value_states,
+ structure_key_value_states,
+ msa_key_value_states,
+ query_attn_mask,
+ protein_kv_attn_mask,
+ structure_kv_attn_mask,
+ msa_kv_attn_mask,
+ ):
+ """
+ query_states: text
+ key_value_states: protein
+ query_states: [bs, query_seq_len, dim]
+ key_value_states: [bs, kv_seq_len, dim]
+ query_attn_mask: [bs, query_seq_len]
+ kv_attn_mask: [bs, kv_seq_len]
+ """
+
+ # Concatenate protein and structure
+ kv_attn_mask = [protein_kv_attn_mask, structure_kv_attn_mask, msa_kv_attn_mask]
+ kv_attn_mask = [_ for _ in kv_attn_mask if _ is not None]
+ if not kv_attn_mask:
+ raise ValueError("At least one modality should be provided for cross attention.")
+ kv_attn_mask = torch.cat(kv_attn_mask, dim=1)
+
+ query_layer = self.attention_norm(query_states)
+
+ # Warning: This place might cause issues, refers to
+ # https://discuss.pytorch.org/t/cuda-error-cublas-status-not-supported-when-calling-cublasltmatmul-from-torch-nn-functional-linear/170214/13
+ # Solution: add `DISABLE_ADDMM_CUDA_LT=1` as environment variable
+ # Apply linear transformation to input_query, input_key, and input_value
+ query_layer = self.query(query_layer) # [bs, querylength, dim]
+
+ if self.key_protein is not None and self.value_protein is not None:
+ protein_key_value_states = protein_key_value_states.to(query_states)
+ key_layer_protein = self.key_protein(protein_key_value_states) # [bs, keylength, dim]
+ value_layer_protein = self.value_protein(protein_key_value_states) # [bs, keylength, dim]
+ else:
+ key_layer_protein = None
+ value_layer_protein = None
+
+ if self.key_structure is not None and self.value_structure is not None:
+ structure_key_value_states = structure_key_value_states.to(query_states)
+ key_layer_structure = self.key_structure(structure_key_value_states) # [bs, keylength, dim]
+ value_layer_structure = self.value_structure(structure_key_value_states) # [bs, keylength, dim]
+ else:
+ key_layer_structure = None
+ value_layer_structure = None
+
+ if self.key_msa is not None and self.value_msa is not None:
+ msa_key_value_states = msa_key_value_states.to(query_states)
+ key_layer_msa = self.key_msa(msa_key_value_states) # [bs, keylength, dim]
+ value_layer_msa = self.value_msa(msa_key_value_states) # [bs, keylength, dim]
+ else:
+ key_layer_msa = None
+ value_layer_msa = None
+
+ key_layer = [key_layer_protein, key_layer_structure, key_layer_msa]
+ key_layer = [_ for _ in key_layer if _ is not None]
+ key_layer = torch.cat(key_layer, dim=1)
+
+ value_layer = [value_layer_protein, value_layer_structure, value_layer_msa]
+ value_layer = [_ for _ in value_layer if _ is not None]
+ value_layer = torch.cat(value_layer, dim=1)
+
+ new_query_layer_shape = query_layer.size()[:-1] + (
+ self.num_attention_heads,
+ self.attention_head_size,
+ )
+ query_layer = query_layer.view(*new_query_layer_shape).permute(0, 2, 1, 3)
+
+ new_key_layer_shape = key_layer.size()[:-1] + (
+ self.num_attention_heads,
+ self.attention_head_size,
+ )
+ key_layer = key_layer.view(*new_key_layer_shape).permute(0, 2, 1, 3)
+
+ new_value_layer_shape = value_layer.size()[:-1] + (
+ self.num_attention_heads,
+ self.attention_head_size,
+ )
+ value_layer = value_layer.view(*new_value_layer_shape).permute(0, 2, 1, 3)
+
+ query_layer = query_layer * self.scale
+
+ # attention_mask: [bs, 1, querylength, keylength]
+ if query_attn_mask is None:
+ query_attn_mask = torch.ones(query_states.size(0), query_states.size(1)).to(query_states.device)
+ attention_mask = query_attn_mask[:, None, :, None] * kv_attn_mask[:, None, None, :]
+ # Compute the scaled dot-product attention scores
+ attn_weights = torch.matmul(query_layer, key_layer.transpose(-1, -2)) # [bs, numheads, querylength, keylength]
+ attn_weights = attn_weights - attn_weights.amax(dim=-1, keepdim=True).detach() # To stabilize score
+ attention_scores = attn_weights.masked_fill(
+ (1 - attention_mask).bool(), torch.finfo(attn_weights.dtype).min
+ ) # [bs, numheads, querylength, keylength]
+
+ attention_probs = nn.Softmax(dim=-1)(attention_scores)
+
+ # attention_probs_dropped = self.dropout(attention_probs)
+
+ context_layer = torch.matmul(attention_probs, value_layer) # [bs, numheads, querylength, dim/numheads]
+
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
+ context_layer = context_layer.view(*new_context_layer_shape)
+
+ context_layer = self.out_proj(context_layer)
+
+ return context_layer
+
+ def forward(
+ self,
+ query_states,
+ protein_kv_states,
+ structure_kv_states,
+ msa_kv_states,
+ query_attn_mask,
+ protein_kv_attn_mask=None,
+ structure_kv_attn_mask=None,
+ msa_kv_attn_mask=None,
+ protein_batch_mask=None,
+ structure_batch_mask=None,
+ msa_batch_mask=None,
+ past_key_values=None,
+ ):
+ if protein_kv_states is not None:
+ bs, protein_kv_seq_len, dim = protein_kv_states.shape
+ if protein_kv_attn_mask is None:
+ protein_kv_attn_mask = (
+ torch.ones(bs, protein_kv_seq_len).to(protein_batch_mask.device)
+ * protein_batch_mask.expand(size=(protein_kv_seq_len, bs)).T
+ ).to(protein_kv_states.device)
+ else:
+ protein_kv_attn_mask = None
+
+ if structure_kv_states is not None:
+ bs, structure_kv_seq_len, dim = structure_kv_states.shape
+ if structure_kv_attn_mask is None:
+ structure_kv_attn_mask = (
+ torch.ones(bs, structure_kv_seq_len).to(protein_batch_mask.device)
+ * structure_batch_mask.expand(size=(structure_kv_seq_len, bs)).T
+ ).to(structure_kv_states.device)
+ else:
+ structure_kv_attn_mask = None
+
+ if msa_kv_states is not None:
+ bs, msa_kv_seq_len, dim = msa_kv_states.shape
+ if msa_kv_attn_mask is None:
+ msa_kv_attn_mask = (
+ torch.ones(bs, msa_kv_seq_len).to(protein_batch_mask.device)
+ * msa_batch_mask.expand(size=(msa_kv_seq_len, bs)).T
+ ).to(msa_kv_states.device)
+ else:
+ msa_kv_attn_mask = None
+ hidden_states = query_states
+ # only when there's at least one valid modality, crossattention will be performed
+ if (
+ (protein_kv_states is not None and protein_kv_attn_mask.any())
+ or (structure_kv_states is not None and structure_kv_attn_mask.any())
+ or (msa_kv_states is not None and msa_kv_attn_mask.any())
+ ):
+ residual = hidden_states
+ hidden_states = self.cross_attention(
+ query_states=hidden_states,
+ protein_key_value_states=protein_kv_states,
+ structure_key_value_states=structure_kv_states,
+ msa_key_value_states=msa_kv_states,
+ query_attn_mask=query_attn_mask,
+ protein_kv_attn_mask=protein_kv_attn_mask,
+ structure_kv_attn_mask=structure_kv_attn_mask,
+ msa_kv_attn_mask=msa_kv_attn_mask,
+ ) # [bs, query_seq_len, dim]
+ # tanh gate
+ hidden_states = torch.tanh(self.gate_attention) * hidden_states
+
+ hidden_states = residual + hidden_states # input_query
+
+ residual = hidden_states
+ hidden_states = self.ff(hidden_states) * torch.tanh(self.gate_ffw)
+ hidden_states = residual + hidden_states
+
+ return hidden_states
+
+
+@use_kernel_forward_from_hub("RMSNorm")
+class EvollaRMSNorm(nn.Module):
+ def __init__(self, hidden_size, eps: float = 1e-6) -> None:
+ """
+ EvollaRMSNorm is equivalent to T5LayerNorm
+ """
+ super().__init__()
+ self.weight = nn.Parameter(torch.ones(hidden_size))
+ self.variance_epsilon = eps
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ input_dtype = hidden_states.dtype
+ hidden_states = hidden_states.to(torch.float32)
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
+ return self.weight * hidden_states.to(input_dtype)
+
+ def extra_repr(self):
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
+
+
+class EvollaRotaryEmbedding(nn.Module):
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
+
+ def __init__(self, config: EvollaConfig, device=None):
+ super().__init__()
+ self.max_seq_len_cached = config.max_position_embeddings
+ self.original_max_seq_len = config.max_position_embeddings
+
+ self.config = config
+
+ self.rope_type = self.config.rope_parameters["rope_type"]
+ rope_init_fn: Callable = self.compute_default_rope_parameters
+ if self.rope_type != "default":
+ rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
+ inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
+
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
+ self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
+
+ @staticmethod
+ def compute_default_rope_parameters(
+ config: EvollaConfig | None = None,
+ device: Optional["torch.device"] = None,
+ seq_len: int | None = None,
+ ) -> tuple["torch.Tensor", float]:
+ """
+ Computes the inverse frequencies according to the original RoPE implementation
+ Args:
+ config ([`~transformers.PreTrainedConfig`]):
+ The model configuration.
+ device (`torch.device`):
+ The device to use for initialization of the inverse frequencies.
+ seq_len (`int`, *optional*):
+ The current sequence length. Unused for this type of RoPE.
+ Returns:
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
+ """
+ base = config.rope_parameters["rope_theta"]
+ dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
+
+ attention_factor = 1.0 # Unused in this type of RoPE
+
+ # Compute the inverse frequencies
+ inv_freq = 1.0 / (
+ base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
+ )
+ return inv_freq, attention_factor
+
+ @torch.no_grad()
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
+ def forward(self, x, position_ids):
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
+ position_ids_expanded = position_ids[:, None, :].float()
+
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
+ with maybe_autocast(device_type=device_type, enabled=False): # Force float32
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
+ emb = torch.cat((freqs, freqs), dim=-1)
+ cos = emb.cos() * self.attention_scaling
+ sin = emb.sin() * self.attention_scaling
+
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
+
+
+class EvollaMLP(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.hidden_size = config.hidden_size
+ self.intermediate_size = config.intermediate_size
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
+ self.act_fn = ACT2FN[config.hidden_act]
+
+ def forward(self, x):
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
+ return down_proj
+
+
+def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
+ """
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
+ """
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
+ if n_rep == 1:
+ return hidden_states
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
+
+
+@use_kernelized_func(apply_rotary_pos_emb)
+class EvollaAttention(nn.Module):
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
+
+ def __init__(self, config: EvollaConfig, layer_idx: int):
+ super().__init__()
+ self.config = config
+ self.layer_idx = layer_idx
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
+ self.scaling = self.head_dim**-0.5
+ self.attention_dropout = config.attention_dropout
+ self.is_causal = True
+
+ self.q_proj = nn.Linear(
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
+ )
+ self.k_proj = nn.Linear(
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
+ )
+ self.v_proj = nn.Linear(
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
+ )
+ self.o_proj = nn.Linear(
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
+ )
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
+ attention_mask: torch.Tensor | None = None,
+ past_key_values: Cache | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor, torch.Tensor]:
+ input_shape = hidden_states.shape[:-1]
+ hidden_shape = (*input_shape, -1, self.head_dim)
+
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+
+ cos, sin = position_embeddings
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
+
+ if past_key_values is not None:
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_states,
+ key_states,
+ value_states,
+ attention_mask,
+ dropout=0.0 if not self.training else self.attention_dropout,
+ scaling=self.scaling,
+ **kwargs,
+ )
+
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ attn_output = self.o_proj(attn_output)
+ return attn_output, attn_weights
+
+
+class EvollaDecoderLayer(GradientCheckpointingLayer):
+ def __init__(self, config: EvollaConfig, layer_idx: int):
+ super().__init__()
+ self.hidden_size = config.hidden_size
+
+ self.self_attn = EvollaAttention(config=config, layer_idx=layer_idx)
+
+ self.mlp = EvollaMLP(config)
+ self.input_layernorm = EvollaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.post_attention_layernorm = EvollaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ if (layer_idx + 1) % max(config.num_hidden_layers // config.aligner_num_add_layers, 1) == 0:
+ self.adapter = EvollaSequenceAlignerCrossAttention(
+ config,
+ protein_encoder_dim=config.hidden_size,
+ )
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ use_cache: bool | None = False,
+ protein_kv_states: torch.Tensor | None = None,
+ structure_kv_states: torch.Tensor | None = None,
+ msa_kv_states: torch.Tensor | None = None,
+ protein_batch_mask: torch.Tensor | None = None,
+ structure_batch_mask: torch.Tensor | None = None,
+ msa_batch_mask: torch.Tensor | None = None,
+ query_attn_mask: torch.Tensor | None = None,
+ **kwargs,
+ ) -> torch.Tensor:
+ residual = hidden_states
+
+ hidden_states = self.input_layernorm(hidden_states)
+
+ # Self Attention
+ hidden_states, _ = self.self_attn(
+ hidden_states=hidden_states,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ position_embeddings=position_embeddings,
+ **kwargs,
+ )
+ hidden_states = residual + hidden_states
+
+ # Fully Connected
+ residual = hidden_states
+ hidden_states = self.post_attention_layernorm(hidden_states)
+ hidden_states = self.mlp(hidden_states)
+ hidden_states = residual + hidden_states
+
+ if hasattr(self, "adapter"):
+ hidden_states = self.adapter(
+ query_states=hidden_states,
+ protein_kv_states=protein_kv_states,
+ structure_kv_states=structure_kv_states,
+ msa_kv_states=msa_kv_states,
+ query_attn_mask=query_attn_mask,
+ protein_batch_mask=protein_batch_mask,
+ structure_batch_mask=structure_batch_mask,
+ msa_batch_mask=msa_batch_mask,
+ )
+
+ return hidden_states
+
+
+@auto_docstring
+class EvollaPreTrainedModel(PreTrainedModel):
+ config: EvollaConfig
+ base_model_prefix = "model"
+ supports_gradient_checkpointing = True
+ _no_split_modules = [
+ "EvollaDecoderLayer",
+ "EvollaSaProtLayer",
+ "EvollaSequenceCompressorResampler",
+ "EvollaSequenceAlignerCrossAttention",
+ ]
+ _skip_keys_device_placement = ["past_key_values"]
+ _supports_flash_attn = False # see dependency on `EvollaSequenceCompressorResampler`
+ _supports_sdpa = True
+ _supports_flex_attn = False # see dependency on `EvollaSequenceCompressorResampler`
+
+ _can_compile_fullgraph = True
+ _supports_attention_backend = False
+ _can_record_outputs = {
+ "hidden_states": EvollaDecoderLayer,
+ "attentions": EvollaAttention,
+ }
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ std = self.config.initializer_range
+ super()._init_weights(module)
+ if isinstance(module, EvollaSequenceAlignerCrossAttention):
+ init.zeros_(module.gate_attention)
+ init.zeros_(module.gate_ffw)
+ init.ones_(module.attention_norm.weight)
+ elif isinstance(module, EvollaSequenceCompressorResampler):
+ init.normal_(module.latents, mean=0.0, std=std)
+
+
+class EvollaModel(EvollaPreTrainedModel):
+ def __init__(self, config: EvollaConfig):
+ super().__init__(config)
+ self.padding_idx = config.pad_token_id
+ self.vocab_size = config.vocab_size
+ self.embed_tokens = nn.Embedding(self.vocab_size, config.hidden_size, self.padding_idx)
+ self.protein_encoder = EvollaProteinEncoder(config=config)
+ self.layers = nn.ModuleList(
+ [
+ EvollaDecoderLayer(
+ config=config,
+ layer_idx=layer_idx,
+ )
+ for layer_idx in range(config.num_hidden_layers)
+ ]
+ )
+
+ self.norm = EvollaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.gradient_checkpointing = getattr(config, "gradient_checkpointing", False)
+ self.rotary_emb = EvollaRotaryEmbedding(config=config)
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.embed_tokens
+
+ def set_input_embeddings(self, value):
+ self.embed_tokens = value
+
+ @auto_docstring
+ @merge_with_config_defaults
+ @capture_outputs
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ use_cache: bool | None = None,
+ protein_input_ids: torch.LongTensor | None = None,
+ protein_attention_mask: torch.Tensor | None = None,
+ structure_feats: torch.FloatTensor | None = None,
+ msa_feats: torch.FloatTensor | None = None,
+ structure_batch_mask: torch.Tensor | None = None,
+ msa_batch_mask: torch.Tensor | None = None,
+ **kwargs,
+ ) -> tuple | BaseModelOutputWithPast:
+ r"""
+ protein_input_ids (torch.LongTensor):
+ The input IDs for the protein sequence in structure-aware tokens. Should be of shape `(batch_size, protein_seq_length)` and type `torch.LongTensor`.
+ protein_attention_mask (torch.Tensor):
+ The attention mask for the protein sequence. Should be of shape `(batch_size, protein_seq_length)` and type `torch.Tensor`.
+ structure_feats (torch.FloatTensor):
+ The input IDs for purely structure-based features. Should be of shape `(batch_size, structure_seq_length, structure_feat_dim)` and type `torch.FloatTensor`. Dummy input for now.
+ msa_feats (torch.FloatTensor):
+ The input IDs for purely MSA-based features. Should be of shape `(batch_size, msa_seq_length, msa_feat_dim)` and type `torch.FloatTensor`. Dummy input for now.
+ structure_batch_mask (torch.Tensor):
+ The batch mask to decide which protein sequences are purely structure-based. Should be of shape `(batch_size)` and type `torch.Tensor`. Should be paired with `structure_feats`. Dummpy input for now.
+ msa_batch_mask (torch.Tensor):
+ The batch mask to decide which protein sequences are purely MSA-based. Should be of shape `(batch_size)` and type `torch.Tensor`. Should be paired with `msa_feats`. Dummpy input for now.
+ """
+ if (input_ids is None) ^ (inputs_embeds is not None):
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
+
+ if inputs_embeds is None:
+ inputs_embeds = self.embed_tokens(input_ids)
+
+ if use_cache and past_key_values is None:
+ past_key_values = DynamicCache(config=self.config)
+
+ if position_ids is None:
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
+ position_ids = position_ids.unsqueeze(0)
+
+ protein_feats = None
+ protein_batch_mask = None
+ # If provided, actually compute them
+ if protein_input_ids is not None and protein_attention_mask is not None:
+ protein_outputs = self.protein_encoder(
+ input_ids=protein_input_ids,
+ attention_mask=protein_attention_mask,
+ )
+ protein_feats = protein_outputs.sequence_compressor_output
+ protein_batch_mask = torch.ones(
+ protein_input_ids.shape[0],
+ device=protein_input_ids.device,
+ dtype=torch.bool,
+ )
+
+ causal_mask = create_causal_mask(
+ config=self.config,
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ )
+
+ hidden_states = inputs_embeds
+ position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
+
+ for decoder_layer in self.layers:
+ hidden_states = decoder_layer(
+ hidden_states,
+ attention_mask=causal_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ protein_kv_states=protein_feats,
+ structure_kv_states=structure_feats,
+ msa_kv_states=msa_feats,
+ protein_batch_mask=protein_batch_mask,
+ structure_batch_mask=structure_batch_mask,
+ msa_batch_mask=msa_batch_mask,
+ query_attn_mask=attention_mask,
+ position_embeddings=position_embeddings,
+ **kwargs,
+ )
+
+ hidden_states = self.norm(hidden_states)
+
+ output = BaseModelOutputWithPast(
+ last_hidden_state=hidden_states,
+ past_key_values=past_key_values,
+ )
+ return output
+
+
+class EvollaForProteinText2Text(EvollaPreTrainedModel, GenerationMixin):
+ def __init__(self, config):
+ super().__init__(config)
+ self.model = EvollaModel(config)
+ self.vocab_size = config.vocab_size
+ self.lm_head = nn.Linear(config.hidden_size, self.vocab_size, bias=False)
+
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.model.get_input_embeddings()
+
+ def set_input_embeddings(self, value):
+ return self.model.set_input_embeddings(value)
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None, # text input ids
+ attention_mask: torch.Tensor | None = None, # text attention mask
+ inputs_embeds: torch.FloatTensor | None = None, # text input embeddings
+ labels: torch.LongTensor | None = None,
+ protein_input_ids: torch.LongTensor | None = None,
+ protein_attention_mask: torch.Tensor | None = None,
+ use_cache: bool | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ **kwargs,
+ ):
+ r"""
+ protein_input_ids (torch.LongTensor):
+ The input IDs for the protein sequence. Should be of shape `(batch_size, protein_seq_length)` and type `torch.LongTensor`.
+ protein_attention_mask (torch.Tensor):
+ The attention mask for the protein sequence. Should be of shape `(batch_size, protein_seq_length)` and type `torch.Tensor`.
+
+ Example:
+
+ ```python
+ >>> from transformers import EvollaProcessor, EvollaForProteinText2Text
+ >>> model = EvollaForProteinText2Text.from_pretrained("westlake/Evolla-10B-hf")
+ >>> processor = EvollaProcessor.from_pretrained("westlake/Evolla-10B-hf")
+
+ >>> protein_information = {
+ "aa_seq": "your amino acid sequence",
+ "foldseek": "your foldseek sequence",
+ }
+ >>> question = "What is the function of this protein?"
+ >>> message = [
+ {"role": "system", "content": "You are an AI expert that can answer any questions about protein."},
+ {"role": "user", "content": question},
+ ]
+
+ >>> inputs = processor(proteins=[protein_information], messages_list=[message], return_tensors="pt", padding="longest")
+ >>> outputs = model.generate(**inputs)
+
+ >>> print(processor.batch_decode(outputs, skip_special_tokens=True))
+ ```"""
+ outputs: BaseModelOutputWithPast = self.model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ inputs_embeds=inputs_embeds,
+ protein_input_ids=protein_input_ids,
+ protein_attention_mask=protein_attention_mask,
+ use_cache=use_cache,
+ **kwargs,
+ )
+
+ hidden_states = outputs.last_hidden_state
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.vocab_size, **kwargs)
+
+ lm_outputs = CausalLMOutputWithPast(
+ loss=loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+ return lm_outputs
+
+
+__all__ = ["EvollaForProteinText2Text", "EvollaModel", "EvollaPreTrainedModel"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/evolla/modular_evolla.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/evolla/modular_evolla.py
new file mode 100644
index 0000000000000000000000000000000000000000..e4043a3ab63eaf9e6fb0d1423aab469d70d88f0c
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/evolla/modular_evolla.py
@@ -0,0 +1,893 @@
+# Copyright 2025 Westlake Representational Learning Lab (Fajie Yuan Lab) team and the HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from dataclasses import dataclass
+
+import torch
+from torch import nn
+
+from ... import initialization as init
+from ...cache_utils import Cache, DynamicCache
+from ...generation import GenerationMixin
+from ...masking_utils import create_bidirectional_mask, create_causal_mask
+from ...modeling_outputs import (
+ BaseModelOutputWithPast,
+ BaseModelOutputWithPoolingAndCrossAttentions,
+ CausalLMOutputWithPast,
+ ModelOutput,
+)
+from ...modeling_utils import PreTrainedModel
+from ...utils import (
+ auto_docstring,
+ can_return_tuple,
+ logging,
+)
+from ...utils.generic import merge_with_config_defaults
+from ...utils.output_capturing import OutputRecorder, capture_outputs
+from ..esm.modeling_esm import (
+ EsmAttention,
+ EsmEmbeddings,
+ EsmEncoder,
+ EsmIntermediate,
+ EsmLayer,
+ EsmOutput,
+ EsmPooler,
+ EsmRotaryEmbedding,
+ EsmSelfAttention,
+ EsmSelfOutput,
+)
+from ..llama.modeling_llama import (
+ LlamaAttention,
+ LlamaDecoderLayer,
+ LlamaMLP,
+ LlamaPreTrainedModel,
+ LlamaRMSNorm,
+ LlamaRotaryEmbedding,
+)
+from .configuration_evolla import EvollaConfig, SaProtConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+class EvollaSaProtEmbeddings(EsmEmbeddings):
+ def __init__(self, config):
+ super().__init__(config)
+ # remove the position_ids in EsmEmbeddings
+ self.position_ids = None
+
+
+class EvollaSaProtRotaryEmbedding(EsmRotaryEmbedding):
+ def __init__(self, config: SaProtConfig, device=None):
+ super().__init__(config, device)
+
+ @staticmethod
+ def compute_default_rope_parameters(
+ config: SaProtConfig | None = None,
+ device: "torch.device | None" = None,
+ seq_len: int | None = None,
+ ) -> tuple["torch.Tensor", float]:
+ return super().compute_default_rope_parameters(config, device, seq_len)
+
+
+class EvollaSaProtSelfAttention(EsmSelfAttention):
+ pass
+
+
+class EvollaSaProtSelfOutput(EsmSelfOutput):
+ pass
+
+
+class EvollaSaProtAttention(EsmAttention):
+ pass
+
+
+class EvollaSaProtIntermediate(EsmIntermediate):
+ pass
+
+
+class EvollaSaProtOutput(EsmOutput):
+ pass
+
+
+class EvollaSaProtLayer(EsmLayer):
+ pass
+
+
+class EvollaSaProtEncoder(EsmEncoder):
+ pass
+
+
+class EvollaSaProtPooler(EsmPooler):
+ pass
+
+
+@auto_docstring
+class EvollaSaProtPreTrainedModel(PreTrainedModel):
+ config: SaProtConfig
+ _no_split_modules = ["EvollaSaProtLayer"]
+ _supports_flash_attn = True
+ _supports_sdpa = True
+ _supports_flex_attn = True
+ _supports_attention_backend = True
+
+ _can_record_outputs = {
+ "hidden_states": EvollaSaProtLayer,
+ "attentions": [OutputRecorder(EvollaSaProtSelfAttention, index=1, layer_name="attention")],
+ "cross_attentions": [
+ OutputRecorder(EvollaSaProtSelfAttention, index=1, layer_name="crossattention"),
+ ],
+ }
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ super()._init_weights(module)
+ if isinstance(module, EvollaSaProtRotaryEmbedding):
+ curr_inv_freq, _ = module.compute_default_rope_parameters(module.config)
+ init.copy_(getattr(module, "inv_freq"), curr_inv_freq)
+
+
+class EvollaSaProtProteinEncoder(EvollaSaProtPreTrainedModel):
+ def __init__(self, config: SaProtConfig):
+ super().__init__(config)
+ self.embeddings = EvollaSaProtEmbeddings(config)
+ self.rotary_embeddings = EvollaSaProtRotaryEmbedding(config=config)
+ self.encoder = EvollaSaProtEncoder(config)
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.embeddings.word_embeddings
+
+ def set_input_embeddings(self, value):
+ self.embeddings.word_embeddings = value
+
+ @merge_with_config_defaults
+ @capture_outputs
+ def forward(
+ self,
+ input_ids: torch.Tensor | None,
+ attention_mask: torch.Tensor | None = None,
+ **kwargs,
+ ) -> tuple[torch.Tensor] | BaseModelOutputWithPoolingAndCrossAttentions:
+ input_shape = input_ids.size()
+ batch_size, seq_length = input_shape
+
+ device = input_ids.device
+ if attention_mask is None:
+ attention_mask = torch.ones(((batch_size, seq_length)), device=device)
+ inputs_embeds = self.embeddings(input_ids=input_ids, attention_mask=attention_mask)
+
+ attention_mask = create_bidirectional_mask(
+ config=self.config,
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ )
+
+ position_ids = torch.arange(seq_length, device=device).unsqueeze(0)
+ position_embeddings = self.rotary_embeddings(inputs_embeds, position_ids)
+
+ encoder_outputs = self.encoder(
+ inputs_embeds, attention_mask=attention_mask, position_embeddings=position_embeddings, **kwargs
+ )
+ sequence_output = encoder_outputs[0]
+
+ return BaseModelOutputWithPoolingAndCrossAttentions(
+ last_hidden_state=sequence_output,
+ hidden_states=encoder_outputs.hidden_states,
+ attentions=encoder_outputs.attentions,
+ cross_attentions=encoder_outputs.cross_attentions,
+ )
+
+
+class EvollaSequenceCompressorAttention(nn.Module):
+ def __init__(self, dim, dim_head=64, heads=8):
+ super().__init__()
+ self.scale = dim_head**-0.5
+ self.heads = heads
+ inner_dim = dim_head * heads
+
+ self.norm_media = nn.LayerNorm(dim)
+ self.norm_latents = nn.LayerNorm(dim)
+
+ self.to_q = nn.Linear(dim, inner_dim, bias=False)
+ self.to_kv = nn.Linear(dim, inner_dim * 2, bias=False)
+ self.to_out = nn.Linear(inner_dim, dim, bias=False)
+
+ def forward(self, x, latents, mask):
+ """
+ Args:
+ x (torch.Tensor): image features
+ shape (b, n1, D)
+ latent (torch.Tensor): latent features
+ shape (b, n2, D); n2: num of latent tokens
+ """
+ x = self.norm_media(x)
+ latents = self.norm_latents(latents)
+
+ h = self.heads
+
+ q = self.to_q(latents)
+ kv_input = torch.cat((x, latents), dim=-2)
+ k, v = self.to_kv(kv_input).chunk(
+ 2, dim=-1
+ ) # each: batch_size, max_protein_length+num_latents, dim_head*num_heads
+
+ q = q.view(q.size(0), q.size(1), h, -1).permute(0, 2, 1, 3)
+ k = k.view(k.size(0), k.size(1), h, -1).permute(0, 2, 1, 3)
+ v = v.view(v.size(0), v.size(1), h, -1).permute(0, 2, 1, 3)
+ q = q * self.scale # batch_size, num_heads, num_latents, dim_head
+
+ # attention
+ sim = torch.matmul(q, k.transpose(-1, -2))
+ sim = sim - sim.amax(dim=-1, keepdim=True).detach()
+ bs, nh, skd, okd = sim.shape
+ ones = torch.ones(nh, skd).to(mask.device) # Create a tensor of ones with shape (nh, skd)
+ mask_exp = mask[:, None, None, :]
+ ones_exp = ones[None, :, :, None]
+ mask = mask_exp * ones_exp
+
+ sim = sim.masked_fill((1 - mask).bool(), -1e4)
+ attn = sim.softmax(dim=-1)
+ out = torch.matmul(attn, v)
+ out = out.permute(0, 2, 1, 3)
+
+ # [batch, seq, head, features] -> [batch, seq, head*features]
+ out = out.reshape(out.size(0), out.size(1), -1)
+
+ return self.to_out(out)
+
+
+class EvollaFeedForward(nn.Module):
+ def __init__(self, dim, mult=4):
+ super().__init__()
+ inner_dim = int(dim * mult)
+
+ self.norm = nn.LayerNorm(dim)
+ self.fc1 = nn.Linear(dim, inner_dim, bias=False)
+ self.activation = nn.GELU()
+ self.fc2 = nn.Linear(inner_dim, dim, bias=False)
+
+ def forward(self, x):
+ return self.fc2(self.activation(self.fc1(self.norm(x))))
+
+
+class EvollaSequenceCompressorResampler(nn.Module):
+ def __init__(self, config: EvollaConfig):
+ super().__init__()
+ protein_repr_dim = config.protein_encoder_config.hidden_size
+ self.num_latents = config.resampler_num_latents
+ self.latents = nn.Parameter(torch.randn(self.num_latents, protein_repr_dim), requires_grad=True)
+ self.layers = nn.ModuleList([])
+ for _ in range(config.resampler_depth):
+ self.layers.append(
+ nn.ModuleList(
+ [
+ EvollaSequenceCompressorAttention(
+ dim=protein_repr_dim, dim_head=config.resampler_dim_head, heads=config.resampler_heads
+ ),
+ EvollaFeedForward(dim=protein_repr_dim, mult=config.resampler_ff_mult),
+ ]
+ )
+ )
+
+ self.norm = nn.LayerNorm(config.hidden_size)
+ self.protein_projector = nn.Linear(protein_repr_dim, config.hidden_size)
+
+ def forward(self, embeds, mask):
+ b = embeds.shape[0]
+
+ bs, _ = mask.shape # bs, max_protein_length
+ latent_mask = torch.ones(bs, self.num_latents).to(mask.device)
+ mask = torch.cat((mask, latent_mask), dim=1) # bs, max_protein_length + num_latents
+
+ # blocks
+ ones = torch.ones(b).to(self.latents.device)
+ latents = self.latents[None] * ones.view(-1, 1, 1) # [b,n,d]
+ latents = latents.to(embeds.dtype)
+ for attn, ff in self.layers:
+ latents = attn(embeds, latents, mask) + latents
+ latents = ff(latents) + latents
+
+ transformed_feature = self.protein_projector(latents)
+
+ return self.norm(transformed_feature)
+
+
+@auto_docstring
+@dataclass
+class EvollaProteinEncoderModelOutput(ModelOutput):
+ r"""
+ sequence_compressor_output (`torch.FloatTensor` of shape `(batch_size, compressed_seq_len, hidden_size)`, *optional*):
+ Compressed sequence representation produced by the sequence compressor module. The sequence length is
+ reduced from the original input length to `compressed_seq_len` via learned compression.
+ """
+
+ sequence_compressor_output: torch.FloatTensor | None = None
+ last_hidden_state: torch.FloatTensor | None = None
+ hidden_states: tuple[torch.FloatTensor, ...] | None = None
+ attentions: tuple[torch.FloatTensor, ...] | None = None
+
+
+class EvollaProteinEncoder(nn.Module):
+ def __init__(self, config: EvollaConfig):
+ super().__init__()
+ self.model = EvollaSaProtProteinEncoder(config=config.protein_encoder_config)
+ self.sequence_compressor_resampler = EvollaSequenceCompressorResampler(config=config)
+
+ @can_return_tuple
+ def forward(self, input_ids: torch.LongTensor, attention_mask: torch.FloatTensor, **kwargs):
+ protein_output = self.model(input_ids=input_ids, attention_mask=attention_mask)
+ protein_embeds = protein_output.last_hidden_state
+ sequence_repr = self.sequence_compressor_resampler(protein_embeds, attention_mask)
+
+ return EvollaProteinEncoderModelOutput(
+ sequence_compressor_output=sequence_repr,
+ last_hidden_state=protein_output.last_hidden_state,
+ )
+
+
+class EvollaSequenceAlignerCrossAttention(nn.Module):
+ def __init__(
+ self,
+ config,
+ protein_encoder_dim: int | None = None,
+ structure_encoder_dim: int | None = None,
+ msa_encoder_dim: int | None = None,
+ ):
+ super().__init__()
+
+ self.hidden_size = config.hidden_size
+ self.num_attention_heads = config.num_attention_heads
+ self.scale = self.num_attention_heads**-0.5
+ self.attention_head_size = int(self.hidden_size / self.num_attention_heads)
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
+
+ attention_probs_dropout_prob = config.aligner_attention_probs_dropout_prob
+ enable_bias = config.aligner_enable_bias
+ ffn_mult = config.aligner_ffn_mult
+
+ self.query = nn.Linear(self.hidden_size, self.all_head_size)
+ if protein_encoder_dim is not None:
+ self.key_protein = nn.Linear(protein_encoder_dim, self.all_head_size)
+ self.value_protein = nn.Linear(protein_encoder_dim, self.all_head_size)
+ else:
+ self.key_protein = None
+ self.value_protein = None
+
+ if structure_encoder_dim is not None:
+ self.key_structure = nn.Linear(structure_encoder_dim, self.all_head_size)
+ self.value_structure = nn.Linear(structure_encoder_dim, self.all_head_size)
+ else:
+ self.key_structure = None
+ self.value_structure = None
+
+ if msa_encoder_dim is not None:
+ self.key_msa = nn.Linear(msa_encoder_dim, self.all_head_size)
+ self.value_msa = nn.Linear(msa_encoder_dim, self.all_head_size)
+ else:
+ self.key_msa = None
+ self.value_msa = None
+
+ self.attention_norm = EvollaRMSNorm(self.hidden_size)
+
+ self.dropout = nn.Dropout(attention_probs_dropout_prob)
+
+ self.out_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=enable_bias)
+
+ self.ff = EvollaFeedForward(self.hidden_size, ffn_mult)
+ self.gate_attention = nn.Parameter(torch.tensor([0.0]))
+ self.gate_ffw = nn.Parameter(torch.tensor([0.0]))
+
+ def cross_attention(
+ self,
+ query_states,
+ protein_key_value_states,
+ structure_key_value_states,
+ msa_key_value_states,
+ query_attn_mask,
+ protein_kv_attn_mask,
+ structure_kv_attn_mask,
+ msa_kv_attn_mask,
+ ):
+ """
+ query_states: text
+ key_value_states: protein
+ query_states: [bs, query_seq_len, dim]
+ key_value_states: [bs, kv_seq_len, dim]
+ query_attn_mask: [bs, query_seq_len]
+ kv_attn_mask: [bs, kv_seq_len]
+ """
+
+ # Concatenate protein and structure
+ kv_attn_mask = [protein_kv_attn_mask, structure_kv_attn_mask, msa_kv_attn_mask]
+ kv_attn_mask = [_ for _ in kv_attn_mask if _ is not None]
+ if not kv_attn_mask:
+ raise ValueError("At least one modality should be provided for cross attention.")
+ kv_attn_mask = torch.cat(kv_attn_mask, dim=1)
+
+ query_layer = self.attention_norm(query_states)
+
+ # Warning: This place might cause issues, refers to
+ # https://discuss.pytorch.org/t/cuda-error-cublas-status-not-supported-when-calling-cublasltmatmul-from-torch-nn-functional-linear/170214/13
+ # Solution: add `DISABLE_ADDMM_CUDA_LT=1` as environment variable
+ # Apply linear transformation to input_query, input_key, and input_value
+ query_layer = self.query(query_layer) # [bs, querylength, dim]
+
+ if self.key_protein is not None and self.value_protein is not None:
+ protein_key_value_states = protein_key_value_states.to(query_states)
+ key_layer_protein = self.key_protein(protein_key_value_states) # [bs, keylength, dim]
+ value_layer_protein = self.value_protein(protein_key_value_states) # [bs, keylength, dim]
+ else:
+ key_layer_protein = None
+ value_layer_protein = None
+
+ if self.key_structure is not None and self.value_structure is not None:
+ structure_key_value_states = structure_key_value_states.to(query_states)
+ key_layer_structure = self.key_structure(structure_key_value_states) # [bs, keylength, dim]
+ value_layer_structure = self.value_structure(structure_key_value_states) # [bs, keylength, dim]
+ else:
+ key_layer_structure = None
+ value_layer_structure = None
+
+ if self.key_msa is not None and self.value_msa is not None:
+ msa_key_value_states = msa_key_value_states.to(query_states)
+ key_layer_msa = self.key_msa(msa_key_value_states) # [bs, keylength, dim]
+ value_layer_msa = self.value_msa(msa_key_value_states) # [bs, keylength, dim]
+ else:
+ key_layer_msa = None
+ value_layer_msa = None
+
+ key_layer = [key_layer_protein, key_layer_structure, key_layer_msa]
+ key_layer = [_ for _ in key_layer if _ is not None]
+ key_layer = torch.cat(key_layer, dim=1)
+
+ value_layer = [value_layer_protein, value_layer_structure, value_layer_msa]
+ value_layer = [_ for _ in value_layer if _ is not None]
+ value_layer = torch.cat(value_layer, dim=1)
+
+ new_query_layer_shape = query_layer.size()[:-1] + (
+ self.num_attention_heads,
+ self.attention_head_size,
+ )
+ query_layer = query_layer.view(*new_query_layer_shape).permute(0, 2, 1, 3)
+
+ new_key_layer_shape = key_layer.size()[:-1] + (
+ self.num_attention_heads,
+ self.attention_head_size,
+ )
+ key_layer = key_layer.view(*new_key_layer_shape).permute(0, 2, 1, 3)
+
+ new_value_layer_shape = value_layer.size()[:-1] + (
+ self.num_attention_heads,
+ self.attention_head_size,
+ )
+ value_layer = value_layer.view(*new_value_layer_shape).permute(0, 2, 1, 3)
+
+ query_layer = query_layer * self.scale
+
+ # attention_mask: [bs, 1, querylength, keylength]
+ if query_attn_mask is None:
+ query_attn_mask = torch.ones(query_states.size(0), query_states.size(1)).to(query_states.device)
+ attention_mask = query_attn_mask[:, None, :, None] * kv_attn_mask[:, None, None, :]
+ # Compute the scaled dot-product attention scores
+ attn_weights = torch.matmul(query_layer, key_layer.transpose(-1, -2)) # [bs, numheads, querylength, keylength]
+ attn_weights = attn_weights - attn_weights.amax(dim=-1, keepdim=True).detach() # To stabilize score
+ attention_scores = attn_weights.masked_fill(
+ (1 - attention_mask).bool(), torch.finfo(attn_weights.dtype).min
+ ) # [bs, numheads, querylength, keylength]
+
+ attention_probs = nn.Softmax(dim=-1)(attention_scores)
+
+ # attention_probs_dropped = self.dropout(attention_probs)
+
+ context_layer = torch.matmul(attention_probs, value_layer) # [bs, numheads, querylength, dim/numheads]
+
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
+ context_layer = context_layer.view(*new_context_layer_shape)
+
+ context_layer = self.out_proj(context_layer)
+
+ return context_layer
+
+ def forward(
+ self,
+ query_states,
+ protein_kv_states,
+ structure_kv_states,
+ msa_kv_states,
+ query_attn_mask,
+ protein_kv_attn_mask=None,
+ structure_kv_attn_mask=None,
+ msa_kv_attn_mask=None,
+ protein_batch_mask=None,
+ structure_batch_mask=None,
+ msa_batch_mask=None,
+ past_key_values=None,
+ ):
+ if protein_kv_states is not None:
+ bs, protein_kv_seq_len, dim = protein_kv_states.shape
+ if protein_kv_attn_mask is None:
+ protein_kv_attn_mask = (
+ torch.ones(bs, protein_kv_seq_len).to(protein_batch_mask.device)
+ * protein_batch_mask.expand(size=(protein_kv_seq_len, bs)).T
+ ).to(protein_kv_states.device)
+ else:
+ protein_kv_attn_mask = None
+
+ if structure_kv_states is not None:
+ bs, structure_kv_seq_len, dim = structure_kv_states.shape
+ if structure_kv_attn_mask is None:
+ structure_kv_attn_mask = (
+ torch.ones(bs, structure_kv_seq_len).to(protein_batch_mask.device)
+ * structure_batch_mask.expand(size=(structure_kv_seq_len, bs)).T
+ ).to(structure_kv_states.device)
+ else:
+ structure_kv_attn_mask = None
+
+ if msa_kv_states is not None:
+ bs, msa_kv_seq_len, dim = msa_kv_states.shape
+ if msa_kv_attn_mask is None:
+ msa_kv_attn_mask = (
+ torch.ones(bs, msa_kv_seq_len).to(protein_batch_mask.device)
+ * msa_batch_mask.expand(size=(msa_kv_seq_len, bs)).T
+ ).to(msa_kv_states.device)
+ else:
+ msa_kv_attn_mask = None
+ hidden_states = query_states
+ # only when there's at least one valid modality, crossattention will be performed
+ if (
+ (protein_kv_states is not None and protein_kv_attn_mask.any())
+ or (structure_kv_states is not None and structure_kv_attn_mask.any())
+ or (msa_kv_states is not None and msa_kv_attn_mask.any())
+ ):
+ residual = hidden_states
+ hidden_states = self.cross_attention(
+ query_states=hidden_states,
+ protein_key_value_states=protein_kv_states,
+ structure_key_value_states=structure_kv_states,
+ msa_key_value_states=msa_kv_states,
+ query_attn_mask=query_attn_mask,
+ protein_kv_attn_mask=protein_kv_attn_mask,
+ structure_kv_attn_mask=structure_kv_attn_mask,
+ msa_kv_attn_mask=msa_kv_attn_mask,
+ ) # [bs, query_seq_len, dim]
+ # tanh gate
+ hidden_states = torch.tanh(self.gate_attention) * hidden_states
+
+ hidden_states = residual + hidden_states # input_query
+
+ residual = hidden_states
+ hidden_states = self.ff(hidden_states) * torch.tanh(self.gate_ffw)
+ hidden_states = residual + hidden_states
+
+ return hidden_states
+
+
+class EvollaRMSNorm(LlamaRMSNorm):
+ pass
+
+
+class EvollaRotaryEmbedding(LlamaRotaryEmbedding):
+ pass
+
+
+class EvollaMLP(LlamaMLP):
+ pass
+
+
+class EvollaAttention(LlamaAttention):
+ pass
+
+
+class EvollaDecoderLayer(LlamaDecoderLayer):
+ def __init__(self, config: EvollaConfig, layer_idx: int):
+ super().__init__(config, layer_idx)
+ if (layer_idx + 1) % max(config.num_hidden_layers // config.aligner_num_add_layers, 1) == 0:
+ self.adapter = EvollaSequenceAlignerCrossAttention(
+ config,
+ protein_encoder_dim=config.hidden_size,
+ )
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ use_cache: bool | None = False,
+ protein_kv_states: torch.Tensor | None = None,
+ structure_kv_states: torch.Tensor | None = None,
+ msa_kv_states: torch.Tensor | None = None,
+ protein_batch_mask: torch.Tensor | None = None,
+ structure_batch_mask: torch.Tensor | None = None,
+ msa_batch_mask: torch.Tensor | None = None,
+ query_attn_mask: torch.Tensor | None = None,
+ **kwargs,
+ ):
+ residual = hidden_states
+
+ hidden_states = self.input_layernorm(hidden_states)
+
+ # Self Attention
+ hidden_states, _ = self.self_attn(
+ hidden_states=hidden_states,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ position_embeddings=position_embeddings,
+ **kwargs,
+ )
+ hidden_states = residual + hidden_states
+
+ # Fully Connected
+ residual = hidden_states
+ hidden_states = self.post_attention_layernorm(hidden_states)
+ hidden_states = self.mlp(hidden_states)
+ hidden_states = residual + hidden_states
+
+ if hasattr(self, "adapter"):
+ hidden_states = self.adapter(
+ query_states=hidden_states,
+ protein_kv_states=protein_kv_states,
+ structure_kv_states=structure_kv_states,
+ msa_kv_states=msa_kv_states,
+ query_attn_mask=query_attn_mask,
+ protein_batch_mask=protein_batch_mask,
+ structure_batch_mask=structure_batch_mask,
+ msa_batch_mask=msa_batch_mask,
+ )
+
+ return hidden_states
+
+
+class EvollaPreTrainedModel(LlamaPreTrainedModel):
+ _supports_flash_attn = False # see dependency on `EvollaSequenceCompressorResampler`
+ _supports_flex_attn = False # see dependency on `EvollaSequenceCompressorResampler`
+ _supports_attention_backend = False
+ _no_split_modules = [
+ "EvollaDecoderLayer",
+ "EvollaSaProtLayer",
+ "EvollaSequenceCompressorResampler",
+ "EvollaSequenceAlignerCrossAttention",
+ ]
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ std = self.config.initializer_range
+ PreTrainedModel._init_weights(self, module)
+ if isinstance(module, EvollaSequenceAlignerCrossAttention):
+ init.zeros_(module.gate_attention)
+ init.zeros_(module.gate_ffw)
+ init.ones_(module.attention_norm.weight)
+ elif isinstance(module, EvollaSequenceCompressorResampler):
+ init.normal_(module.latents, mean=0.0, std=std)
+
+
+class EvollaModel(EvollaPreTrainedModel):
+ def __init__(self, config: EvollaConfig):
+ super().__init__(config)
+ self.padding_idx = config.pad_token_id
+ self.vocab_size = config.vocab_size
+ self.embed_tokens = nn.Embedding(self.vocab_size, config.hidden_size, self.padding_idx)
+ self.protein_encoder = EvollaProteinEncoder(config=config)
+ self.layers = nn.ModuleList(
+ [
+ EvollaDecoderLayer(
+ config=config,
+ layer_idx=layer_idx,
+ )
+ for layer_idx in range(config.num_hidden_layers)
+ ]
+ )
+
+ self.norm = EvollaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.gradient_checkpointing = getattr(config, "gradient_checkpointing", False)
+ self.rotary_emb = EvollaRotaryEmbedding(config=config)
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.embed_tokens
+
+ def set_input_embeddings(self, value):
+ self.embed_tokens = value
+
+ @auto_docstring
+ @merge_with_config_defaults
+ @capture_outputs
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ use_cache: bool | None = None,
+ protein_input_ids: torch.LongTensor | None = None,
+ protein_attention_mask: torch.Tensor | None = None,
+ structure_feats: torch.FloatTensor | None = None,
+ msa_feats: torch.FloatTensor | None = None,
+ structure_batch_mask: torch.Tensor | None = None,
+ msa_batch_mask: torch.Tensor | None = None,
+ **kwargs,
+ ) -> tuple | BaseModelOutputWithPast:
+ r"""
+ protein_input_ids (torch.LongTensor):
+ The input IDs for the protein sequence in structure-aware tokens. Should be of shape `(batch_size, protein_seq_length)` and type `torch.LongTensor`.
+ protein_attention_mask (torch.Tensor):
+ The attention mask for the protein sequence. Should be of shape `(batch_size, protein_seq_length)` and type `torch.Tensor`.
+ structure_feats (torch.FloatTensor):
+ The input IDs for purely structure-based features. Should be of shape `(batch_size, structure_seq_length, structure_feat_dim)` and type `torch.FloatTensor`. Dummy input for now.
+ msa_feats (torch.FloatTensor):
+ The input IDs for purely MSA-based features. Should be of shape `(batch_size, msa_seq_length, msa_feat_dim)` and type `torch.FloatTensor`. Dummy input for now.
+ structure_batch_mask (torch.Tensor):
+ The batch mask to decide which protein sequences are purely structure-based. Should be of shape `(batch_size)` and type `torch.Tensor`. Should be paired with `structure_feats`. Dummpy input for now.
+ msa_batch_mask (torch.Tensor):
+ The batch mask to decide which protein sequences are purely MSA-based. Should be of shape `(batch_size)` and type `torch.Tensor`. Should be paired with `msa_feats`. Dummpy input for now.
+ """
+ if (input_ids is None) ^ (inputs_embeds is not None):
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
+
+ if inputs_embeds is None:
+ inputs_embeds = self.embed_tokens(input_ids)
+
+ if use_cache and past_key_values is None:
+ past_key_values = DynamicCache(config=self.config)
+
+ if position_ids is None:
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
+ position_ids = position_ids.unsqueeze(0)
+
+ protein_feats = None
+ protein_batch_mask = None
+ # If provided, actually compute them
+ if protein_input_ids is not None and protein_attention_mask is not None:
+ protein_outputs = self.protein_encoder(
+ input_ids=protein_input_ids,
+ attention_mask=protein_attention_mask,
+ )
+ protein_feats = protein_outputs.sequence_compressor_output
+ protein_batch_mask = torch.ones(
+ protein_input_ids.shape[0],
+ device=protein_input_ids.device,
+ dtype=torch.bool,
+ )
+
+ causal_mask = create_causal_mask(
+ config=self.config,
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ )
+
+ hidden_states = inputs_embeds
+ position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
+
+ for decoder_layer in self.layers:
+ hidden_states = decoder_layer(
+ hidden_states,
+ attention_mask=causal_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ protein_kv_states=protein_feats,
+ structure_kv_states=structure_feats,
+ msa_kv_states=msa_feats,
+ protein_batch_mask=protein_batch_mask,
+ structure_batch_mask=structure_batch_mask,
+ msa_batch_mask=msa_batch_mask,
+ query_attn_mask=attention_mask,
+ position_embeddings=position_embeddings,
+ **kwargs,
+ )
+
+ hidden_states = self.norm(hidden_states)
+
+ output = BaseModelOutputWithPast(
+ last_hidden_state=hidden_states,
+ past_key_values=past_key_values,
+ )
+ return output
+
+
+class EvollaForProteinText2Text(EvollaPreTrainedModel, GenerationMixin):
+ def __init__(self, config):
+ super().__init__(config)
+ self.model = EvollaModel(config)
+ self.vocab_size = config.vocab_size
+ self.lm_head = nn.Linear(config.hidden_size, self.vocab_size, bias=False)
+
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.model.get_input_embeddings()
+
+ def set_input_embeddings(self, value):
+ return self.model.set_input_embeddings(value)
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None, # text input ids
+ attention_mask: torch.Tensor | None = None, # text attention mask
+ inputs_embeds: torch.FloatTensor | None = None, # text input embeddings
+ labels: torch.LongTensor | None = None,
+ protein_input_ids: torch.LongTensor | None = None,
+ protein_attention_mask: torch.Tensor | None = None,
+ use_cache: bool | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ **kwargs,
+ ):
+ r"""
+ protein_input_ids (torch.LongTensor):
+ The input IDs for the protein sequence. Should be of shape `(batch_size, protein_seq_length)` and type `torch.LongTensor`.
+ protein_attention_mask (torch.Tensor):
+ The attention mask for the protein sequence. Should be of shape `(batch_size, protein_seq_length)` and type `torch.Tensor`.
+
+ Example:
+
+ ```python
+ >>> from transformers import EvollaProcessor, EvollaForProteinText2Text
+ >>> model = EvollaForProteinText2Text.from_pretrained("westlake/Evolla-10B-hf")
+ >>> processor = EvollaProcessor.from_pretrained("westlake/Evolla-10B-hf")
+
+ >>> protein_information = {
+ "aa_seq": "your amino acid sequence",
+ "foldseek": "your foldseek sequence",
+ }
+ >>> question = "What is the function of this protein?"
+ >>> message = [
+ {"role": "system", "content": "You are an AI expert that can answer any questions about protein."},
+ {"role": "user", "content": question},
+ ]
+
+ >>> inputs = processor(proteins=[protein_information], messages_list=[message], return_tensors="pt", padding="longest")
+ >>> outputs = model.generate(**inputs)
+
+ >>> print(processor.batch_decode(outputs, skip_special_tokens=True))
+ ```"""
+ outputs: BaseModelOutputWithPast = self.model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ inputs_embeds=inputs_embeds,
+ protein_input_ids=protein_input_ids,
+ protein_attention_mask=protein_attention_mask,
+ use_cache=use_cache,
+ **kwargs,
+ )
+
+ hidden_states = outputs.last_hidden_state
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.vocab_size, **kwargs)
+
+ lm_outputs = CausalLMOutputWithPast(
+ loss=loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+ return lm_outputs
+
+
+__all__ = ["EvollaForProteinText2Text", "EvollaModel", "EvollaPreTrainedModel"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/evolla/processing_evolla.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/evolla/processing_evolla.py
new file mode 100644
index 0000000000000000000000000000000000000000..74a2def12093377bfe9aac6f369ccd7d8fdab5c0
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/evolla/processing_evolla.py
@@ -0,0 +1,187 @@
+# Copyright 2025 The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""
+Processor class for EVOLLA.
+"""
+
+from ...feature_extraction_utils import BatchFeature
+from ...processing_utils import (
+ ProcessorMixin,
+)
+from ...utils import auto_docstring
+
+
+PROTEIN_VALID_KEYS = ["aa_seq", "foldseek", "msa"]
+
+
+@auto_docstring
+class EvollaProcessor(ProcessorMixin):
+ def __init__(self, protein_tokenizer, tokenizer=None, protein_max_length=1024, text_max_length=512, **kwargs):
+ r"""
+ protein_tokenizer (`EsmTokenizer`):
+ An instance of [`EsmTokenizer`]. The protein tokenizer is a required input.
+ protein_max_length (`int`, *optional*, defaults to 1024):
+ The maximum length of the sequence to be generated.
+ text_max_length (`int`, *optional*, defaults to 512):
+ The maximum length of the text to be generated.
+ """
+ if protein_tokenizer is None:
+ raise ValueError("You need to specify an `protein_tokenizer`.")
+ if tokenizer is None:
+ raise ValueError("You need to specify a `tokenizer`.")
+
+ super().__init__(protein_tokenizer, tokenizer)
+
+ self.tokenizer.pad_token = "<|reserved_special_token_0|>"
+ self.protein_max_length = protein_max_length
+ self.text_max_length = text_max_length
+
+ def process_proteins(self, proteins, protein_max_length=1024):
+ sa_sequences = []
+ for protein in proteins:
+ aa_seq = protein.get("aa_seq")
+ foldseek = protein.get("foldseek")
+ sa_sequence = "".join([s.upper() + f.lower() for s, f in zip(aa_seq, foldseek)])
+ sa_sequences.append(sa_sequence)
+
+ sa_tokens = self.protein_tokenizer(
+ sa_sequences, return_tensors="pt", truncation=True, max_length=protein_max_length, padding=True
+ )
+ return sa_tokens
+
+ def process_text(
+ self,
+ texts,
+ text_max_length: int = 512,
+ ):
+ prompts = []
+ for messages in texts:
+ prompt = self.tokenizer.apply_chat_template(
+ messages,
+ tokenize=False,
+ add_generation_prompt=True,
+ )
+ prompts.append(prompt)
+
+ prompt_inputs = self.tokenizer(
+ prompts,
+ add_special_tokens=False,
+ return_tensors="pt",
+ padding="longest",
+ truncation=True,
+ max_length=text_max_length,
+ )
+ return prompt_inputs
+
+ @auto_docstring
+ def __call__(
+ self,
+ proteins: list[dict] | dict | None = None,
+ messages_list: list[list[dict]] | list[dict] | None = None,
+ protein_max_length: int | None = None,
+ text_max_length: int | None = None,
+ **kwargs,
+ ):
+ r"""
+ proteins (`Union[List[dict], dict]`):
+ A list of dictionaries or a single dictionary containing the following keys:
+ - `"aa_seq"` (`str`) -- The amino acid sequence of the protein.
+ - `"foldseek"` (`str`) -- The foldseek string of the protein.
+ messages_list (`Union[List[List[dict]], List[dict]]`):
+ A list of lists of dictionaries or a list of dictionaries containing the following keys:
+ - `"role"` (`str`) -- The role of the message.
+ - `"content"` (`str`) -- The content of the message.
+ protein_max_length (`int`, *optional*, defaults to 1024):
+ The maximum length of the sequence to be generated.
+ text_max_length (`int`, *optional*, defaults to 512):
+ The maximum length of the text.
+
+ Return:
+ a dict with following keys:
+ - `protein_input_ids` (`torch.Tensor` of shape `(batch_size, sequence_length)`) -- The input IDs for the protein sequence.
+ - `protein_attention_mask` (`torch.Tensor` of shape `(batch_size, sequence_length)`) -- The attention mask for the protein sequence.
+ - `text_input_ids` (`torch.Tensor` of shape `(batch_size, sequence_length)`) -- The input IDs for the text sequence.
+ - `text_attention_mask` (`torch.Tensor` of shape `(batch_size, sequence_length)`) -- The attention mask for the text sequence.
+ """
+ # proteins and messages_list should be provided
+ if proteins is None or messages_list is None:
+ raise ValueError("You need to specify `messages_list` and `proteins`.")
+
+ protein_max_length = protein_max_length if protein_max_length is not None else self.protein_max_length
+ text_max_length = text_max_length if text_max_length is not None else self.text_max_length
+
+ # proteins should be List[dict]
+ if isinstance(proteins, dict):
+ proteins = [proteins]
+ # messages_list should be List[List[dict]]
+ if isinstance(messages_list, (list, tuple)) and not isinstance(messages_list[0], (list, tuple)):
+ messages_list = [messages_list]
+ # Check if batched proteins are in the correct format
+ if isinstance(proteins, (list, tuple)) and not all(isinstance(p, dict) for p in proteins):
+ raise ValueError("The proteins should be a list of dictionaries, but not all elements are dictionaries.")
+ if isinstance(proteins, (list, tuple)) and not all(
+ all(k in PROTEIN_VALID_KEYS for k in p.keys()) for p in proteins
+ ):
+ raise ValueError(
+ "There should be a list of dictionaries with keys: "
+ f"{', '.join(PROTEIN_VALID_KEYS)} for each protein."
+ f"But got: {proteins}"
+ )
+ # Check if batched messages_list is in the correct format
+ if isinstance(messages_list, (list, tuple)):
+ for messages in messages_list:
+ if not isinstance(messages, (list, tuple)):
+ raise TypeError(f"Each messages in messages_list should be a list instead of {type(messages)}.")
+ if not all(isinstance(m, dict) for m in messages):
+ raise ValueError(
+ "Each message in messages_list should be a list of dictionaries, but not all elements are dictionaries."
+ )
+ if any(len(m.keys()) != 2 for m in messages) or any(
+ set(m.keys()) != {"role", "content"} for m in messages
+ ):
+ raise ValueError(
+ "Each message in messages_list should be a list of dictionaries with two keys: 'role' and 'content'."
+ f"But got: {messages}"
+ )
+ else:
+ raise ValueError(
+ f"The messages_list should be a list of lists of dictionaries, but it's {type(messages_list)}."
+ )
+ sa_tokens = self.process_proteins(proteins, protein_max_length)
+
+ text_tokens = self.process_text(messages_list, text_max_length)
+
+ return BatchFeature(
+ data={
+ "protein_input_ids": sa_tokens["input_ids"],
+ "protein_attention_mask": sa_tokens["attention_mask"],
+ "input_ids": text_tokens["input_ids"],
+ "attention_mask": text_tokens["attention_mask"],
+ }
+ )
+
+ def batch_decode(self, *args, **kwargs):
+ return self.tokenizer.batch_decode(*args, **kwargs)
+
+ def decode(self, *args, **kwargs):
+ return self.tokenizer.decode(*args, **kwargs)
+
+ def protein_batch_decode(self, *args, **kwargs):
+ return self.protein_tokenizer.batch_decode(*args, **kwargs)
+
+ def protein_decode(self, *args, **kwargs):
+ return self.protein_tokenizer.decode(*args, **kwargs)
+
+
+__all__ = ["EvollaProcessor"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/falcon_h1/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/falcon_h1/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2e35aa1f85d0dada7efe8d0e65bd04fc9c6a58b9
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/falcon_h1/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/falcon_h1/__pycache__/configuration_falcon_h1.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/falcon_h1/__pycache__/configuration_falcon_h1.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..be8cc8bd44be298ba2b12d5da362401a2e0a4418
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/falcon_h1/__pycache__/configuration_falcon_h1.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/falcon_h1/__pycache__/modeling_falcon_h1.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/falcon_h1/__pycache__/modeling_falcon_h1.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..44064e6ad0ac9ffceba320fb50b3ce610fb1e271
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/falcon_h1/__pycache__/modeling_falcon_h1.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/falcon_h1/__pycache__/modular_falcon_h1.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/falcon_h1/__pycache__/modular_falcon_h1.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7adb92c00bfc8ca029cefb74319a9b3b409da252
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/falcon_h1/__pycache__/modular_falcon_h1.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/fast_vlm/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/fast_vlm/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..949f087650dd99ea1b04cb052708b9123b08b557
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/fast_vlm/__init__.py
@@ -0,0 +1,27 @@
+# Copyright 2025 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_fast_vlm import *
+ from .modeling_fast_vlm import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/fast_vlm/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/fast_vlm/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0537b854e24ee9e22722ad92135c51519a5fbba0
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/fast_vlm/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/fast_vlm/__pycache__/configuration_fast_vlm.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/fast_vlm/__pycache__/configuration_fast_vlm.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1eedd0f8ca9c4980cfa64c6869fa48db50de9dfd
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/fast_vlm/__pycache__/configuration_fast_vlm.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/fast_vlm/__pycache__/modeling_fast_vlm.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/fast_vlm/__pycache__/modeling_fast_vlm.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..18de55ae883ae6f8abdefb862e9950dd8c3496ce
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/fast_vlm/__pycache__/modeling_fast_vlm.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/fast_vlm/__pycache__/modular_fast_vlm.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/fast_vlm/__pycache__/modular_fast_vlm.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7af75770226a37721c4b2fa1fc8d8e5b2d8ce76f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/fast_vlm/__pycache__/modular_fast_vlm.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/fast_vlm/configuration_fast_vlm.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/fast_vlm/configuration_fast_vlm.py
new file mode 100644
index 0000000000000000000000000000000000000000..25c61da6507f248a8594cc0d10c1354358d6be31
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/fast_vlm/configuration_fast_vlm.py
@@ -0,0 +1,111 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/fast_vlm/modular_fast_vlm.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_fast_vlm.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2025 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring
+from ..auto import CONFIG_MAPPING, AutoConfig
+
+
+@auto_docstring(checkpoint="KamilaMila/FastVLM-7B")
+@strict
+class FastVlmConfig(PreTrainedConfig):
+ r"""
+ Example:
+
+ ```python
+ >>> from transformers import FastVlmForConditionalGeneration, FastVlmConfig
+
+ >>> # Initializing a FastVLM-7B style configuration
+ >>> configuration = FastVlmConfig()
+
+ >>> # Initializing a model from the FastVLM-7B style configuration
+ >>> model = FastVlmForConditionalGeneration(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "fast_vlm"
+ attribute_map = {
+ "image_token_id": "image_token_index",
+ }
+ sub_configs = {"text_config": AutoConfig, "vision_config": AutoConfig}
+
+ vision_config: dict | PreTrainedConfig | None = None
+ text_config: dict | PreTrainedConfig | None = None
+ image_token_index: int = 151646
+ image_seq_length: int = 576
+ projector_hidden_act: str = "gelu"
+ vision_feature_select_strategy: str = "full"
+ vision_feature_layer: int | list[int] = -1
+ multimodal_projector_bias: bool = True
+ tie_word_embeddings: bool = False
+
+ def __post_init__(self, **kwargs):
+ if isinstance(self.vision_config, dict):
+ self.vision_config["model_type"] = self.vision_config.get("model_type", "timm_wrapper")
+ self.vision_config = CONFIG_MAPPING[self.vision_config["model_type"]](**self.vision_config)
+ elif self.vision_config is None:
+ self.vision_config = CONFIG_MAPPING["timm_wrapper"](
+ architecture="fastvit_mci3",
+ do_pooling=True,
+ global_pool="avg",
+ hidden_size=3072,
+ initializer_range=0.02,
+ model_args={"inference_mode": True},
+ )
+
+ if isinstance(self.text_config, dict):
+ self.text_config["model_type"] = self.text_config.get("model_type", "qwen2")
+ self.text_config = CONFIG_MAPPING[self.text_config["model_type"]](**self.text_config)
+ elif self.text_config is None:
+ self.text_config = CONFIG_MAPPING["qwen2"](
+ hidden_size=3584,
+ vocab_size=152128,
+ intermediate_size=18944,
+ num_attention_heads=28,
+ num_key_value_heads=4,
+ num_hidden_layers=28,
+ )
+ # The default value is `False` but this config is used with many model types
+ # Attr `tie_word_embeddings` was saved in text config for those models, so we
+ # need an ugly workaround and forward-pass the attr from text config
+ if not self.tie_word_embeddings and self.text_config.tie_word_embeddings:
+ self.tie_word_embeddings = self.text_config.tie_word_embeddings
+
+ super().__post_init__(**kwargs)
+
+ def validate_architecture(self):
+ """Part of `@strict`-powered validation. Validates the architecture of the config."""
+ if self.vision_feature_select_strategy != "full":
+ raise ValueError(
+ f"Unexpected select feature strategy: {self.vision_feature_select_strategy}. Only 'full' is supported in FastVLM."
+ )
+
+ if self.vision_feature_layer != -1:
+ raise ValueError(
+ f"Unexpected vision feature layer: {self.vision_feature_layer}. Only -1 is supported in FastVLM."
+ )
+
+
+__all__ = ["FastVlmConfig"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/fast_vlm/modeling_fast_vlm.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/fast_vlm/modeling_fast_vlm.py
new file mode 100644
index 0000000000000000000000000000000000000000..8262024137bfbd28d5f5eabe4860f568cf68a163
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/fast_vlm/modeling_fast_vlm.py
@@ -0,0 +1,413 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/fast_vlm/modular_fast_vlm.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_fast_vlm.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2025 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+from dataclasses import dataclass
+
+import torch
+from torch import nn
+
+from ...activations import ACT2FN
+from ...cache_utils import Cache
+from ...generation import GenerationMixin
+from ...modeling_outputs import BaseModelOutputWithPast, BaseModelOutputWithPooling, ModelOutput
+from ...modeling_utils import PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import TransformersKwargs, auto_docstring, torch_compilable_check
+from ...utils.generic import can_return_tuple, merge_with_config_defaults
+from ..auto import AutoModel
+from .configuration_fast_vlm import FastVlmConfig
+
+
+class FastVlmMultiModalProjector(nn.Module):
+ def __init__(self, config: FastVlmConfig):
+ super().__init__()
+ self.linear_1 = nn.Linear(
+ config.vision_config.hidden_size,
+ config.text_config.hidden_size,
+ bias=config.multimodal_projector_bias,
+ )
+ self.act = ACT2FN[config.projector_hidden_act]
+ self.linear_2 = nn.Linear(
+ config.text_config.hidden_size, config.text_config.hidden_size, bias=config.multimodal_projector_bias
+ )
+
+ def forward(self, image_features):
+ hidden_states = self.linear_1(image_features)
+ hidden_states = self.act(hidden_states)
+ hidden_states = self.linear_2(hidden_states)
+ return hidden_states
+
+
+@auto_docstring
+class FastVlmPreTrainedModel(PreTrainedModel):
+ config: FastVlmConfig
+ base_model_prefix = "model"
+ input_modalities = ("image", "text")
+ supports_gradient_checkpointing = True
+ _skip_keys_device_placement = ["past_key_values"]
+
+ _supports_flash_attn = True
+ _supports_sdpa = True
+
+ _can_compile_fullgraph = True
+ _supports_flex_attn = True
+ _supports_attention_backend = True
+
+
+@auto_docstring(
+ custom_intro="""
+ Base class for FastVlm outputs, with hidden states and attentions.
+ """
+)
+@dataclass
+class FastVlmModelOutputWithPast(BaseModelOutputWithPast):
+ r"""
+ past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
+ It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
+
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
+ `past_key_values` input) to speed up sequential decoding.
+ image_hidden_states (`torch.FloatTensor`, *optional*):
+ A `torch.FloatTensor` of size `(batch_size, num_images, sequence_length, hidden_size)`.
+ image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
+ """
+
+ image_hidden_states: torch.FloatTensor | None = None
+
+
+@auto_docstring(
+ custom_intro="""
+ The FastVlm model which consists of a vision backbone and a language model, without a language modeling head.
+ """
+)
+class FastVlmModel(FastVlmPreTrainedModel):
+ def __init__(self, config: FastVlmConfig):
+ super().__init__(config)
+ self.vision_tower = AutoModel.from_config(config.vision_config)
+
+ self.multi_modal_projector = FastVlmMultiModalProjector(config)
+ self.language_model = AutoModel.from_config(config.text_config)
+ self.post_init()
+
+ @merge_with_config_defaults
+ @can_return_tuple
+ @auto_docstring(
+ custom_intro="Obtains image last hidden states from the vision tower and apply multimodal projection."
+ )
+ def get_image_features(
+ self,
+ pixel_values: torch.FloatTensor,
+ vision_feature_layer: int | list[int] | list[int] | None = None,
+ vision_feature_select_strategy: str | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutputWithPooling:
+ r"""
+ pixel_values (`torch.FloatTensor]` of shape `(batch_size, channels, height, width)`):
+ The tensors corresponding to the input images.
+ vision_feature_layer (`Union[int, list[int]]`, *optional*):
+ The index/indices of the layer to select the vision feature. Only -1 supported.
+ vision_feature_select_strategy (`str`, *optional*):
+ The feature selection strategy used to select the vision feature from the vision backbone.
+ Only "full" supported.
+ """
+ kwargs = {k: v for k, v in kwargs.items() if v is not None}
+ image_outputs = self.vision_tower(pixel_values, return_dict=True, **kwargs)
+
+ # since the vision tower is hybrid in FastVLM, its output needs to be handled differently from Llava
+ selected_image_feature = image_outputs.last_hidden_state
+ selected_image_feature = selected_image_feature.flatten(2).permute(0, 2, 1)
+ image_features = self.multi_modal_projector(selected_image_feature)
+ image_outputs.pooler_output = list(image_features)
+
+ return image_outputs
+
+ def get_placeholder_mask(
+ self, input_ids: torch.LongTensor, inputs_embeds: torch.FloatTensor, image_features: torch.FloatTensor
+ ):
+ """
+ Obtains multimodal placeholder mask from `input_ids` or `inputs_embeds`, and checks that the placeholder token count is
+ equal to the length of multimodal features. If the lengths are different, an error is raised.
+ """
+ if input_ids is None:
+ special_image_mask = inputs_embeds == self.get_input_embeddings()(
+ torch.tensor(self.config.image_token_id, dtype=torch.long, device=inputs_embeds.device)
+ )
+ special_image_mask = special_image_mask.all(-1)
+ else:
+ special_image_mask = input_ids == self.config.image_token_id
+
+ n_image_tokens = special_image_mask.sum()
+ n_image_features = image_features.shape[0] * image_features.shape[1]
+ special_image_mask = special_image_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
+ torch_compilable_check(
+ inputs_embeds[special_image_mask].numel() == image_features.numel(),
+ f"Image features and image tokens do not match, tokens: {n_image_tokens}, features: {n_image_features}",
+ )
+ return special_image_mask
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ pixel_values: torch.FloatTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ vision_feature_layer: int | list[int] | list[int] | None = None,
+ vision_feature_select_strategy: str | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | FastVlmModelOutputWithPast:
+ r"""
+ vision_feature_layer (`Union[int, list[int], NoneType]`, *optional*):
+ The index of the layer to select the vision feature. If multiple indices are provided, the vision feature of the
+ corresponding indices will be concatenated to form the vision features. Only -1 supported.
+ vision_feature_select_strategy (`str`, *optional*):
+ The feature selection strategy used to select the vision feature from the vision backbone. Only "full" supported.
+ """
+ if (input_ids is None) ^ (inputs_embeds is not None):
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
+
+ if inputs_embeds is None:
+ inputs_embeds = self.get_input_embeddings()(input_ids)
+
+ if pixel_values is not None:
+ image_features = self.get_image_features(
+ pixel_values=pixel_values,
+ vision_feature_layer=vision_feature_layer,
+ vision_feature_select_strategy=vision_feature_select_strategy,
+ return_dict=True,
+ ).pooler_output
+ image_features = torch.cat(image_features, dim=0).to(inputs_embeds.device, inputs_embeds.dtype)
+ special_image_mask = self.get_placeholder_mask(
+ input_ids, inputs_embeds=inputs_embeds, image_features=image_features
+ )
+ inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)
+
+ outputs = self.language_model(
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ **kwargs,
+ )
+
+ return FastVlmModelOutputWithPast(
+ last_hidden_state=outputs.last_hidden_state,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ image_hidden_states=image_features if pixel_values is not None else None,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ Base class for FastVlm causal language model (or autoregressive) outputs.
+ """
+)
+@dataclass
+class FastVlmCausalLMOutputWithPast(ModelOutput):
+ r"""
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
+ Language modeling loss (for next-token prediction).
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
+ past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
+ It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
+
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
+ `past_key_values` input) to speed up sequential decoding.
+ image_hidden_states (`torch.FloatTensor`, *optional*):
+ A `torch.FloatTensor` of size `(batch_size, num_images, sequence_length, hidden_size)`.
+ image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
+ """
+
+ loss: torch.FloatTensor | None = None
+ logits: torch.FloatTensor | None = None
+ past_key_values: Cache | None = None
+ hidden_states: tuple[torch.FloatTensor] | None = None
+ attentions: tuple[torch.FloatTensor] | None = None
+ image_hidden_states: torch.FloatTensor | None = None
+
+
+@auto_docstring(
+ custom_intro="""
+ The FastVlm model which consists of a vision backbone and a language model.
+ """
+)
+class FastVlmForConditionalGeneration(FastVlmPreTrainedModel, GenerationMixin):
+ _tied_weights_keys = {"lm_head.weight": "model.language_model.embed_tokens.weight"}
+
+ def __init__(self, config: FastVlmConfig):
+ super().__init__(config)
+ self.model = FastVlmModel(config)
+ self.lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.vocab_size, bias=False)
+ self.post_init()
+
+ def get_output_embeddings(self) -> nn.Module:
+ return self.lm_head
+
+ @auto_docstring
+ def get_image_features(
+ self,
+ pixel_values: torch.FloatTensor,
+ vision_feature_layer: int | list[int] | list[int] | None = None,
+ vision_feature_select_strategy: str | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutputWithPooling:
+ return self.model.get_image_features(
+ pixel_values=pixel_values,
+ vision_feature_layer=vision_feature_layer,
+ vision_feature_select_strategy=vision_feature_select_strategy,
+ **kwargs,
+ )
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ pixel_values: torch.FloatTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ vision_feature_layer: int | list[int] | list[int] | None = None,
+ vision_feature_select_strategy: str | None = None,
+ labels: torch.LongTensor | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | FastVlmCausalLMOutputWithPast:
+ r"""
+ vision_feature_layer (`Union[int, list[int], NoneType]`, *optional*):
+ The index of the layer to select the vision feature. If multiple indices are provided, the vision feature of the
+ corresponding indices will be concatenated to form the vision features. Only -1 supported.
+ vision_feature_select_strategy (`str`, *optional*):
+ The feature selection strategy used to select the vision feature from the vision backbone. Only "full" supported.
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
+
+ Example:
+
+ ```python
+ >>> from PIL import Image
+ >>> import httpx
+ >>> from io import BytesIO
+ >>> from transformers import AutoProcessor, AutoModelForImageTextToText
+ >>> import torch
+
+ >>> device = "cuda" if torch.cuda.is_available() else "cpu"
+
+ >>> model = AutoModelForImageTextToText.from_pretrained("KamilaMila/FastVLM-0.5B").to(device)
+ >>> processor = AutoProcessor.from_pretrained("KamilaMila/FastVLM-0.5B")
+
+ >>> conversation = [
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "What are these?"},
+ {"type": "image"}
+ ]
+ }
+ ]
+
+ >>> prompt = processor.apply_chat_template(conversation, add_generation_prompt=True)
+ >>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
+ >>> with httpx.stream("GET", url) as response:
+ ... image = Image.open(BytesIO(response.read()))
+
+ >>> inputs = processor(images=image, text=prompt, return_tensors="pt").to(device)
+
+ >>> # Generate
+ >>> generated_ids = model.generate(**inputs, max_new_tokens=15)
+ >>> print(processor.batch_decode(generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0])
+ system\n You are a helpful assistant.\n user\n What are these?\n assistant\n The image depicts a traditional Chinese street...
+ ```"""
+ outputs = self.model(
+ input_ids=input_ids,
+ pixel_values=pixel_values,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ vision_feature_layer=vision_feature_layer,
+ vision_feature_select_strategy=vision_feature_select_strategy,
+ **kwargs,
+ )
+
+ hidden_states = outputs[0]
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(
+ logits=logits, labels=labels, vocab_size=self.config.text_config.vocab_size, **kwargs
+ )
+
+ return FastVlmCausalLMOutputWithPast(
+ loss=loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ image_hidden_states=outputs.image_hidden_states,
+ )
+
+ def prepare_inputs_for_generation(
+ self,
+ input_ids,
+ past_key_values=None,
+ inputs_embeds=None,
+ pixel_values=None,
+ attention_mask=None,
+ logits_to_keep=None,
+ is_first_iteration=False,
+ **kwargs,
+ ):
+ # Overwritten -- in specific circumstances we don't want to forward image inputs to the model
+
+ model_inputs = super().prepare_inputs_for_generation(
+ input_ids,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ logits_to_keep=logits_to_keep,
+ is_first_iteration=is_first_iteration,
+ **kwargs,
+ )
+
+ if is_first_iteration or not kwargs.get("use_cache", True):
+ # Pixel values are used only in the first iteration if available
+ # In subsequent iterations, they are already merged with text and cached
+ # NOTE: first iteration doesn't have to be prefill, it can be the first
+ # iteration with a question and cached system prompt (continue generate from cache)
+ model_inputs["pixel_values"] = pixel_values
+
+ return model_inputs
+
+
+__all__ = ["FastVlmForConditionalGeneration", "FastVlmModel", "FastVlmPreTrainedModel"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/fast_vlm/modular_fast_vlm.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/fast_vlm/modular_fast_vlm.py
new file mode 100644
index 0000000000000000000000000000000000000000..d9db87ab27d4318d9fd6dace7b15ad4cb73ab732
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/fast_vlm/modular_fast_vlm.py
@@ -0,0 +1,337 @@
+# Copyright 2025 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+import torch
+from huggingface_hub.dataclasses import strict
+from torch import nn
+
+from ...activations import ACT2FN
+from ...cache_utils import Cache
+from ...configuration_utils import PreTrainedConfig
+from ...modeling_outputs import BaseModelOutputWithPooling
+from ...processing_utils import Unpack
+from ...utils import TransformersKwargs, auto_docstring
+from ...utils.generic import can_return_tuple, merge_with_config_defaults
+from ..auto import CONFIG_MAPPING
+from ..llava.configuration_llava import LlavaConfig
+from ..llava.modeling_llava import (
+ LlavaCausalLMOutputWithPast,
+ LlavaForConditionalGeneration,
+ LlavaModel,
+ LlavaModelOutputWithPast,
+ LlavaMultiModalProjector,
+ LlavaPreTrainedModel,
+)
+
+
+@auto_docstring(checkpoint="KamilaMila/FastVLM-7B")
+@strict
+class FastVlmConfig(LlavaConfig):
+ r"""
+ Example:
+
+ ```python
+ >>> from transformers import FastVlmForConditionalGeneration, FastVlmConfig
+
+ >>> # Initializing a FastVLM-7B style configuration
+ >>> configuration = FastVlmConfig()
+
+ >>> # Initializing a model from the FastVLM-7B style configuration
+ >>> model = FastVlmForConditionalGeneration(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "fast_vlm"
+
+ vision_config: dict | PreTrainedConfig | None = None
+ text_config: dict | PreTrainedConfig | None = None
+ image_token_index: int = 151646
+ projector_hidden_act: str = "gelu"
+ vision_feature_select_strategy: str = "full"
+ vision_feature_layer: int | list[int] = -1
+ multimodal_projector_bias: bool = True
+ tie_word_embeddings: bool = False
+
+ def __post_init__(self, **kwargs):
+ if isinstance(self.vision_config, dict):
+ self.vision_config["model_type"] = self.vision_config.get("model_type", "timm_wrapper")
+ self.vision_config = CONFIG_MAPPING[self.vision_config["model_type"]](**self.vision_config)
+ elif self.vision_config is None:
+ self.vision_config = CONFIG_MAPPING["timm_wrapper"](
+ architecture="fastvit_mci3",
+ do_pooling=True,
+ global_pool="avg",
+ hidden_size=3072,
+ initializer_range=0.02,
+ model_args={"inference_mode": True},
+ )
+
+ if isinstance(self.text_config, dict):
+ self.text_config["model_type"] = self.text_config.get("model_type", "qwen2")
+ self.text_config = CONFIG_MAPPING[self.text_config["model_type"]](**self.text_config)
+ elif self.text_config is None:
+ self.text_config = CONFIG_MAPPING["qwen2"](
+ hidden_size=3584,
+ vocab_size=152128,
+ intermediate_size=18944,
+ num_attention_heads=28,
+ num_key_value_heads=4,
+ num_hidden_layers=28,
+ )
+ # The default value is `False` but this config is used with many model types
+ # Attr `tie_word_embeddings` was saved in text config for those models, so we
+ # need an ugly workaround and forward-pass the attr from text config
+ if not self.tie_word_embeddings and self.text_config.tie_word_embeddings:
+ self.tie_word_embeddings = self.text_config.tie_word_embeddings
+
+ PreTrainedConfig.__post_init__(**kwargs)
+
+ def validate_architecture(self):
+ """Part of `@strict`-powered validation. Validates the architecture of the config."""
+ if self.vision_feature_select_strategy != "full":
+ raise ValueError(
+ f"Unexpected select feature strategy: {self.vision_feature_select_strategy}. Only 'full' is supported in FastVLM."
+ )
+
+ if self.vision_feature_layer != -1:
+ raise ValueError(
+ f"Unexpected vision feature layer: {self.vision_feature_layer}. Only -1 is supported in FastVLM."
+ )
+
+
+class FastVlmMultiModalProjector(LlavaMultiModalProjector):
+ def __init__(self, config: FastVlmConfig):
+ nn.Module.__init__()
+ self.linear_1 = nn.Linear(
+ config.vision_config.hidden_size,
+ config.text_config.hidden_size,
+ bias=config.multimodal_projector_bias,
+ )
+ self.act = ACT2FN[config.projector_hidden_act]
+ self.linear_2 = nn.Linear(
+ config.text_config.hidden_size, config.text_config.hidden_size, bias=config.multimodal_projector_bias
+ )
+
+
+class FastVlmPreTrainedModel(LlavaPreTrainedModel):
+ pass
+
+
+class FastVlmModelOutputWithPast(LlavaModelOutputWithPast):
+ pass
+
+
+class FastVlmModel(LlavaModel):
+ def __init__(self, config: FastVlmConfig):
+ super().__init__(config)
+
+ @merge_with_config_defaults
+ @can_return_tuple
+ @auto_docstring(
+ custom_intro="Obtains image last hidden states from the vision tower and apply multimodal projection."
+ )
+ def get_image_features(
+ self,
+ pixel_values: torch.FloatTensor,
+ vision_feature_layer: int | list[int] | list[int] | None = None,
+ vision_feature_select_strategy: str | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutputWithPooling:
+ r"""
+ pixel_values (`torch.FloatTensor]` of shape `(batch_size, channels, height, width)`):
+ The tensors corresponding to the input images.
+ vision_feature_layer (`Union[int, list[int]]`, *optional*):
+ The index/indices of the layer to select the vision feature. Only -1 supported.
+ vision_feature_select_strategy (`str`, *optional*):
+ The feature selection strategy used to select the vision feature from the vision backbone.
+ Only "full" supported.
+ """
+ kwargs = {k: v for k, v in kwargs.items() if v is not None}
+ image_outputs = self.vision_tower(pixel_values, return_dict=True, **kwargs)
+
+ # since the vision tower is hybrid in FastVLM, its output needs to be handled differently from Llava
+ selected_image_feature = image_outputs.last_hidden_state
+ selected_image_feature = selected_image_feature.flatten(2).permute(0, 2, 1)
+ image_features = self.multi_modal_projector(selected_image_feature)
+ image_outputs.pooler_output = list(image_features)
+
+ return image_outputs
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ pixel_values: torch.FloatTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ vision_feature_layer: int | list[int] | list[int] | None = None,
+ vision_feature_select_strategy: str | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | FastVlmModelOutputWithPast:
+ r"""
+ vision_feature_layer (`Union[int, list[int], NoneType]`, *optional*):
+ The index of the layer to select the vision feature. If multiple indices are provided, the vision feature of the
+ corresponding indices will be concatenated to form the vision features. Only -1 supported.
+ vision_feature_select_strategy (`str`, *optional*):
+ The feature selection strategy used to select the vision feature from the vision backbone. Only "full" supported.
+ """
+ if (input_ids is None) ^ (inputs_embeds is not None):
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
+
+ if inputs_embeds is None:
+ inputs_embeds = self.get_input_embeddings()(input_ids)
+
+ if pixel_values is not None:
+ image_features = self.get_image_features(
+ pixel_values=pixel_values,
+ vision_feature_layer=vision_feature_layer,
+ vision_feature_select_strategy=vision_feature_select_strategy,
+ return_dict=True,
+ ).pooler_output
+ image_features = torch.cat(image_features, dim=0).to(inputs_embeds.device, inputs_embeds.dtype)
+ special_image_mask = self.get_placeholder_mask(
+ input_ids, inputs_embeds=inputs_embeds, image_features=image_features
+ )
+ inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)
+
+ outputs = self.language_model(
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ **kwargs,
+ )
+
+ return FastVlmModelOutputWithPast(
+ last_hidden_state=outputs.last_hidden_state,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ image_hidden_states=image_features if pixel_values is not None else None,
+ )
+
+
+class FastVlmCausalLMOutputWithPast(LlavaCausalLMOutputWithPast):
+ pass
+
+
+@auto_docstring(
+ custom_intro="""
+ The FastVlm model which consists of a vision backbone and a language model.
+ """
+)
+class FastVlmForConditionalGeneration(LlavaForConditionalGeneration):
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ pixel_values: torch.FloatTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ vision_feature_layer: int | list[int] | list[int] | None = None,
+ vision_feature_select_strategy: str | None = None,
+ labels: torch.LongTensor | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | FastVlmCausalLMOutputWithPast:
+ r"""
+ vision_feature_layer (`Union[int, list[int], NoneType]`, *optional*):
+ The index of the layer to select the vision feature. If multiple indices are provided, the vision feature of the
+ corresponding indices will be concatenated to form the vision features. Only -1 supported.
+ vision_feature_select_strategy (`str`, *optional*):
+ The feature selection strategy used to select the vision feature from the vision backbone. Only "full" supported.
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
+
+ Example:
+
+ ```python
+ >>> from PIL import Image
+ >>> import httpx
+ >>> from io import BytesIO
+ >>> from transformers import AutoProcessor, AutoModelForImageTextToText
+ >>> import torch
+
+ >>> device = "cuda" if torch.cuda.is_available() else "cpu"
+
+ >>> model = AutoModelForImageTextToText.from_pretrained("KamilaMila/FastVLM-0.5B").to(device)
+ >>> processor = AutoProcessor.from_pretrained("KamilaMila/FastVLM-0.5B")
+
+ >>> conversation = [
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "What are these?"},
+ {"type": "image"}
+ ]
+ }
+ ]
+
+ >>> prompt = processor.apply_chat_template(conversation, add_generation_prompt=True)
+ >>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
+ >>> with httpx.stream("GET", url) as response:
+ ... image = Image.open(BytesIO(response.read()))
+
+ >>> inputs = processor(images=image, text=prompt, return_tensors="pt").to(device)
+
+ >>> # Generate
+ >>> generated_ids = model.generate(**inputs, max_new_tokens=15)
+ >>> print(processor.batch_decode(generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0])
+ system\n You are a helpful assistant.\n user\n What are these?\n assistant\n The image depicts a traditional Chinese street...
+ ```"""
+ outputs = self.model(
+ input_ids=input_ids,
+ pixel_values=pixel_values,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ vision_feature_layer=vision_feature_layer,
+ vision_feature_select_strategy=vision_feature_select_strategy,
+ **kwargs,
+ )
+
+ hidden_states = outputs[0]
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(
+ logits=logits, labels=labels, vocab_size=self.config.text_config.vocab_size, **kwargs
+ )
+
+ return FastVlmCausalLMOutputWithPast(
+ loss=loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ image_hidden_states=outputs.image_hidden_states,
+ )
+
+
+__all__ = ["FastVlmForConditionalGeneration", "FastVlmModel", "FastVlmPreTrainedModel", "FastVlmConfig"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/flex_olmo/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/flex_olmo/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..6728345e33f876871625cb5c1ed82444bc5bcb2e
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/flex_olmo/__init__.py
@@ -0,0 +1,28 @@
+# Copyright 2025 the HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_flex_olmo import *
+ from .modeling_flex_olmo import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/flex_olmo/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/flex_olmo/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..eb943288a917eaa6caa2e3fa73f7da4e518e0cf0
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/flex_olmo/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/flex_olmo/__pycache__/configuration_flex_olmo.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/flex_olmo/__pycache__/configuration_flex_olmo.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0de90dcd0bf8de36288f4947a774730d8a749c5a
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/flex_olmo/__pycache__/configuration_flex_olmo.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/flex_olmo/__pycache__/modeling_flex_olmo.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/flex_olmo/__pycache__/modeling_flex_olmo.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..300b2a43858b4adf632d9fed1c125dc1a53044ea
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/flex_olmo/__pycache__/modeling_flex_olmo.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/flex_olmo/__pycache__/modular_flex_olmo.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/flex_olmo/__pycache__/modular_flex_olmo.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8220a8e2499a1482655a73831726c7f9fb30555a
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/flex_olmo/__pycache__/modular_flex_olmo.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/flex_olmo/configuration_flex_olmo.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/flex_olmo/configuration_flex_olmo.py
new file mode 100644
index 0000000000000000000000000000000000000000..7b08a79b801b5f931f07d15a87eb1751ba1b7ee1
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/flex_olmo/configuration_flex_olmo.py
@@ -0,0 +1,97 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/flex_olmo/modular_flex_olmo.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_flex_olmo.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2025 the HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...modeling_rope_utils import RopeParameters
+from ...utils import auto_docstring
+
+
+@auto_docstring(checkpoint="allenai/FlexOlmo-7x7B-1T")
+@strict
+class FlexOlmoConfig(PreTrainedConfig):
+ r"""
+ Example:
+
+ ```python
+ >>> from transformers import FlexOlmoModel, FlexOlmoConfig
+
+ >>> # Initializing a FlexOlmo style configuration
+ >>> configuration = FlexOlmoConfig()
+
+ >>> # Initializing a model from the FlexOlmo style configuration
+ >>> model = FlexOlmoModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "flex_olmo"
+ keys_to_ignore_at_inference = ["past_key_values"]
+ attribute_map = {"num_local_experts": "num_experts"}
+ default_theta = 500000.0
+ base_model_tp_plan = {
+ "layers.*.self_attn.q_proj": "colwise_gather_output", # we need to replicate here due to the added norm on q and k
+ "layers.*.self_attn.k_proj": "colwise_gather_output", # we need to replicate here due to the added norm on q and k
+ "layers.*.self_attn.v_proj": "colwise_gather_output", # we need to replicate here due to the added norm on q and k
+ "layers.*.self_attn.o_proj": "rowwise_split_input", # input is replicated due to the added norm on q and k
+ "layers.*.mlp.experts.gate_up_proj": "packed_colwise",
+ "layers.*.mlp.experts.down_proj": "rowwise",
+ "layers.*.mlp.experts": "moe_tp_experts",
+ }
+ base_model_pp_plan = {
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
+ "norm": (["hidden_states"], ["hidden_states"]),
+ }
+
+ vocab_size: int = 100352
+ hidden_size: int = 4096
+ intermediate_size: int = 11008
+ num_hidden_layers: int = 32
+ num_attention_heads: int = 32
+ num_key_value_heads: int | None = None
+ hidden_act: str = "silu"
+ max_position_embeddings: int = 4096
+ initializer_range: float = 0.02
+ rms_norm_eps: float = 1e-06
+ use_cache: bool = True
+ pad_token_id: int | None = 100277
+ bos_token_id: int | None = None
+ eos_token_id: int | list[int] | None = 100257
+ tie_word_embeddings: bool = False
+ rope_parameters: RopeParameters | dict | None = None
+ attention_bias: bool = False
+ attention_dropout: float | None = 0.0
+ num_experts_per_tok: int = 5
+ num_experts: int = 7
+ output_router_logits: bool = False
+ router_aux_loss_coef: float = 0.01
+ norm_topk_prob: bool = False
+
+ def __post_init__(self, **kwargs):
+ if self.num_key_value_heads is None:
+ self.num_key_value_heads = self.num_attention_heads
+ super().__post_init__(**kwargs)
+
+
+__all__ = ["FlexOlmoConfig"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/flex_olmo/modeling_flex_olmo.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/flex_olmo/modeling_flex_olmo.py
new file mode 100644
index 0000000000000000000000000000000000000000..100e6fa35554e1a274354e332236fedd3f049c5c
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/flex_olmo/modeling_flex_olmo.py
@@ -0,0 +1,701 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/flex_olmo/modular_flex_olmo.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_flex_olmo.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2025 the HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+from collections.abc import Callable
+from typing import Optional
+
+import torch
+import torch.nn.functional as F
+from torch import nn
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...cache_utils import Cache, DynamicCache
+from ...generation import GenerationMixin
+from ...integrations import use_experts_implementation, use_kernel_forward_from_hub, use_kernelized_func
+from ...masking_utils import create_causal_mask
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import MoeCausalLMOutputWithPast, MoeModelOutputWithPast
+from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import TransformersKwargs, auto_docstring, can_return_tuple
+from ...utils.generic import maybe_autocast, merge_with_config_defaults
+from ...utils.output_capturing import OutputRecorder, capture_outputs
+from .configuration_flex_olmo import FlexOlmoConfig
+
+
+@use_kernel_forward_from_hub("RMSNorm")
+class FlexOlmoRMSNorm(nn.Module):
+ def __init__(self, hidden_size, eps: float = 1e-6) -> None:
+ """
+ FlexOlmoRMSNorm is equivalent to T5LayerNorm
+ """
+ super().__init__()
+ self.weight = nn.Parameter(torch.ones(hidden_size))
+ self.variance_epsilon = eps
+
+ def forward(self, hidden_states) -> torch.Tensor:
+ input_dtype = hidden_states.dtype
+ hidden_states = hidden_states.to(torch.float32)
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
+ return (self.weight * hidden_states).to(input_dtype)
+
+ def extra_repr(self):
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
+
+
+class FlexOlmoRotaryEmbedding(nn.Module):
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
+
+ def __init__(self, config: FlexOlmoConfig, device=None):
+ super().__init__()
+ self.max_seq_len_cached = config.max_position_embeddings
+ self.original_max_seq_len = config.max_position_embeddings
+
+ self.config = config
+
+ self.rope_type = self.config.rope_parameters["rope_type"]
+ rope_init_fn: Callable = self.compute_default_rope_parameters
+ if self.rope_type != "default":
+ rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
+ inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
+
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
+ self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
+
+ @staticmethod
+ def compute_default_rope_parameters(
+ config: FlexOlmoConfig | None = None,
+ device: Optional["torch.device"] = None,
+ seq_len: int | None = None,
+ ) -> tuple["torch.Tensor", float]:
+ """
+ Computes the inverse frequencies according to the original RoPE implementation
+ Args:
+ config ([`~transformers.PreTrainedConfig`]):
+ The model configuration.
+ device (`torch.device`):
+ The device to use for initialization of the inverse frequencies.
+ seq_len (`int`, *optional*):
+ The current sequence length. Unused for this type of RoPE.
+ Returns:
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
+ """
+ base = config.rope_parameters["rope_theta"]
+ dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
+
+ attention_factor = 1.0 # Unused in this type of RoPE
+
+ # Compute the inverse frequencies
+ inv_freq = 1.0 / (
+ base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
+ )
+ return inv_freq, attention_factor
+
+ @torch.no_grad()
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
+ def forward(self, x, position_ids):
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
+ position_ids_expanded = position_ids[:, None, :].float()
+
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
+ with maybe_autocast(device_type=device_type, enabled=False): # Force float32
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
+ emb = torch.cat((freqs, freqs), dim=-1)
+ cos = emb.cos() * self.attention_scaling
+ sin = emb.sin() * self.attention_scaling
+ return cos, sin
+
+
+class FlexOlmoMLP(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.hidden_size = config.hidden_size
+ self.intermediate_size = config.intermediate_size
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
+ self.act_fn = ACT2FN[config.hidden_act]
+
+ def forward(self, x):
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
+ return down_proj
+
+
+def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
+ """
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
+ """
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
+ if n_rep == 1:
+ return hidden_states
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
+
+
+def eager_attention_forward(
+ module: nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: torch.Tensor | None,
+ scaling: float,
+ dropout: float = 0.0,
+ **kwargs: Unpack[TransformersKwargs],
+):
+ key_states = repeat_kv(key, module.num_key_value_groups)
+ value_states = repeat_kv(value, module.num_key_value_groups)
+
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
+ if attention_mask is not None:
+ attn_weights = attn_weights + attention_mask
+
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
+ attn_output = torch.matmul(attn_weights, value_states)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+
+ return attn_output, attn_weights
+
+
+def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
+ """Applies Rotary Position Embedding to the query and key tensors.
+
+ Args:
+ q (`torch.Tensor`): The query tensor.
+ k (`torch.Tensor`): The key tensor.
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
+ Returns:
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
+ """
+ q_type, k_type = q.dtype, k.dtype
+ cos = cos.unsqueeze(unsqueeze_dim)
+ sin = sin.unsqueeze(unsqueeze_dim)
+ q_embed = (q * cos) + (rotate_half(q) * sin)
+ k_embed = (k * cos) + (rotate_half(k) * sin)
+ return q_embed.to(q_type), k_embed.to(k_type)
+
+
+def rotate_half(x):
+ """Rotates half the hidden dims of the input."""
+ x1 = x[..., : x.shape[-1] // 2]
+ x2 = x[..., x.shape[-1] // 2 :]
+ return torch.cat((-x2, x1), dim=-1)
+
+
+@use_kernelized_func(apply_rotary_pos_emb)
+class FlexOlmoAttention(nn.Module):
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
+
+ def __init__(self, config: FlexOlmoConfig, layer_idx: int | None = None):
+ super().__init__()
+ self.config = config
+ self.layer_idx = layer_idx
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
+ self.scaling = self.head_dim**-0.5
+ self.attention_dropout = config.attention_dropout
+ self.is_causal = True
+
+ self.q_proj = nn.Linear(
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
+ )
+ self.k_proj = nn.Linear(
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
+ )
+ self.v_proj = nn.Linear(
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
+ )
+ self.o_proj = nn.Linear(
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
+ )
+ self.q_norm = FlexOlmoRMSNorm(config.num_attention_heads * self.head_dim, config.rms_norm_eps)
+ self.k_norm = FlexOlmoRMSNorm(config.num_key_value_heads * self.head_dim, config.rms_norm_eps)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
+ attention_mask: torch.Tensor | None,
+ past_key_values: Cache | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor, torch.Tensor | None]:
+ input_shape = hidden_states.shape[:-1]
+ hidden_shape = (*input_shape, -1, self.head_dim)
+
+ query_states = self.q_norm(self.q_proj(hidden_states))
+ key_states = self.k_norm(self.k_proj(hidden_states))
+ value_states = self.v_proj(hidden_states)
+
+ query_states = query_states.view(hidden_shape).transpose(1, 2)
+ key_states = key_states.view(hidden_shape).transpose(1, 2)
+ value_states = value_states.view(hidden_shape).transpose(1, 2)
+
+ cos, sin = position_embeddings
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
+
+ if past_key_values is not None:
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_states,
+ key_states,
+ value_states,
+ attention_mask,
+ dropout=0.0 if not self.training else self.attention_dropout,
+ scaling=self.scaling,
+ **kwargs,
+ )
+
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ attn_output = self.o_proj(attn_output)
+ return attn_output, attn_weights
+
+
+class FlexOlmoTopKRouter(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.top_k = config.num_experts_per_tok
+ self.num_experts = config.num_experts
+ self.norm_topk_prob = config.norm_topk_prob
+ self.hidden_dim = config.hidden_size
+ self.weight = nn.Parameter(torch.zeros(self.num_experts, self.hidden_dim))
+
+ def forward(self, hidden_states):
+ hidden_states = hidden_states.reshape(-1, self.hidden_dim)
+ router_logits = F.linear(hidden_states, self.weight) # (seq_len, num_experts)
+ router_probs = torch.nn.functional.softmax(router_logits, dtype=torch.float, dim=-1)
+ router_top_value, router_indices = torch.topk(router_probs, self.top_k, dim=-1) # (seq_len, top_k)
+ if self.norm_topk_prob:
+ router_top_value /= router_top_value.sum(dim=-1, keepdim=True)
+ router_top_value = router_top_value.to(router_logits.dtype)
+ router_scores = router_top_value
+ return router_logits, router_scores, router_indices
+
+
+@use_experts_implementation
+class FlexOlmoExperts(nn.Module):
+ """Collection of expert weights stored as 3D tensors."""
+
+ def __init__(self, config: FlexOlmoConfig):
+ super().__init__()
+ self.num_experts = config.num_local_experts
+ self.hidden_dim = config.hidden_size
+ self.intermediate_dim = config.intermediate_size
+ self.gate_up_proj = nn.Parameter(torch.empty(self.num_experts, 2 * self.intermediate_dim, self.hidden_dim))
+ self.down_proj = nn.Parameter(torch.empty(self.num_experts, self.hidden_dim, self.intermediate_dim))
+ self.act_fn = ACT2FN[config.hidden_act]
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ top_k_index: torch.Tensor,
+ top_k_weights: torch.Tensor,
+ ) -> torch.Tensor:
+ final_hidden_states = torch.zeros_like(hidden_states)
+ with torch.no_grad():
+ expert_mask = torch.nn.functional.one_hot(top_k_index, num_classes=self.num_experts)
+ expert_mask = expert_mask.permute(2, 1, 0)
+ expert_hit = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero()
+
+ for expert_idx in expert_hit:
+ expert_idx = expert_idx[0]
+ if expert_idx == self.num_experts:
+ continue
+ top_k_pos, token_idx = torch.where(expert_mask[expert_idx])
+ current_state = hidden_states[token_idx]
+ gate, up = nn.functional.linear(current_state, self.gate_up_proj[expert_idx]).chunk(2, dim=-1)
+ current_hidden_states = self.act_fn(gate) * up
+ current_hidden_states = nn.functional.linear(current_hidden_states, self.down_proj[expert_idx])
+ current_hidden_states = current_hidden_states * top_k_weights[token_idx, top_k_pos, None]
+ final_hidden_states.index_add_(0, token_idx, current_hidden_states.to(final_hidden_states.dtype))
+
+ return final_hidden_states
+
+
+class FlexOlmoSparseMoeBlock(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.gate = FlexOlmoTopKRouter(config)
+ self.experts = FlexOlmoExperts(config)
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ batch_size, sequence_length, hidden_dim = hidden_states.shape
+ hidden_states = hidden_states.view(-1, hidden_dim)
+ _, top_k_weights, top_k_index = self.gate(hidden_states)
+ final_hidden_states = self.experts(hidden_states, top_k_index, top_k_weights).reshape(
+ batch_size, sequence_length, hidden_dim
+ )
+ return final_hidden_states
+
+
+class FlexOlmoDecoderLayer(GradientCheckpointingLayer):
+ def __init__(self, config: FlexOlmoConfig, layer_idx: int):
+ super().__init__()
+ self.hidden_size = config.hidden_size
+ self.self_attn = FlexOlmoAttention(config=config, layer_idx=layer_idx)
+ self.mlp = FlexOlmoSparseMoeBlock(config)
+ self.post_attention_layernorm = FlexOlmoRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.post_feedforward_layernorm = FlexOlmoRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
+ **kwargs,
+ ) -> torch.FloatTensor:
+ residual = hidden_states
+
+ # Self Attention
+ hidden_states, _ = self.self_attn(
+ hidden_states=hidden_states,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ position_embeddings=position_embeddings,
+ **kwargs,
+ )
+ hidden_states = self.post_attention_layernorm(hidden_states)
+ hidden_states = residual + hidden_states
+
+ # Fully Connected
+ residual = hidden_states
+ hidden_states = self.mlp(hidden_states)
+ hidden_states = self.post_feedforward_layernorm(hidden_states)
+ hidden_states = residual + hidden_states
+ return hidden_states
+
+
+@auto_docstring
+class FlexOlmoPreTrainedModel(PreTrainedModel):
+ config: FlexOlmoConfig
+ base_model_prefix = "model"
+ supports_gradient_checkpointing = True
+ _no_split_modules = ["FlexOlmoDecoderLayer"]
+ _skip_keys_device_placement = ["past_key_values"]
+ _supports_flash_attn = True
+ _supports_sdpa = True
+ _supports_flex_attn = True
+
+ _can_compile_fullgraph = True
+ _supports_attention_backend = True
+ _can_record_outputs = {
+ "router_logits": OutputRecorder(FlexOlmoTopKRouter, index=0),
+ "hidden_states": FlexOlmoDecoderLayer,
+ "attentions": FlexOlmoAttention,
+ }
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ super()._init_weights(module)
+ std = self.config.initializer_range
+ if isinstance(module, FlexOlmoExperts):
+ init.normal_(module.gate_up_proj, mean=0.0, std=std)
+ init.normal_(module.down_proj, mean=0.0, std=std)
+ elif isinstance(module, FlexOlmoTopKRouter):
+ init.normal_(module.weight, mean=0.0, std=std)
+
+
+@auto_docstring
+class FlexOlmoModel(FlexOlmoPreTrainedModel):
+ def __init__(self, config: FlexOlmoConfig):
+ super().__init__(config)
+ self.padding_idx = config.pad_token_id
+ self.vocab_size = config.vocab_size
+
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
+ self.layers = nn.ModuleList(
+ [FlexOlmoDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
+ )
+ self.norm = FlexOlmoRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.rotary_emb = FlexOlmoRotaryEmbedding(config=config)
+ self.gradient_checkpointing = False
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @merge_with_config_defaults
+ @capture_outputs
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ use_cache: bool | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> MoeModelOutputWithPast:
+ if (input_ids is None) ^ (inputs_embeds is not None):
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
+
+ if use_cache and past_key_values is None:
+ past_key_values = DynamicCache(config=self.config)
+
+ if inputs_embeds is None:
+ inputs_embeds = self.embed_tokens(input_ids)
+
+ if position_ids is None:
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
+ position_ids = position_ids.unsqueeze(0)
+
+ causal_mask = create_causal_mask(
+ config=self.config,
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ position_ids=position_ids,
+ )
+
+ hidden_states = inputs_embeds
+
+ # create position embeddings to be shared across the decoder layers
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
+
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
+ hidden_states = decoder_layer(
+ hidden_states,
+ position_embeddings=position_embeddings,
+ attention_mask=causal_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ **kwargs,
+ )
+
+ hidden_states = self.norm(hidden_states)
+
+ return MoeModelOutputWithPast( # only diff with Mistral is the output type, we need MoE
+ last_hidden_state=hidden_states,
+ past_key_values=past_key_values,
+ )
+
+
+def load_balancing_loss_func(
+ gate_logits: torch.Tensor | tuple[torch.Tensor] | None,
+ num_experts: int | None = None,
+ top_k=2,
+ attention_mask: torch.Tensor | None = None,
+) -> torch.Tensor | int:
+ r"""
+ Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
+
+ See Switch Transformer (https://huggingface.co/papers/2101.03961) for more details. This function implements the loss
+ function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
+ experts is too unbalanced.
+
+ Args:
+ gate_logits:
+ Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of
+ shape [batch_size X sequence_length, num_experts].
+ num_experts:
+ Number of experts
+ top_k:
+ The number of experts to route per-token, can be also interpreted as the `top-k` routing
+ parameter.
+ attention_mask (`torch.Tensor`, *optional*):
+ The attention_mask used in forward function
+ shape [batch_size X sequence_length] if not None.
+
+ Returns:
+ The auxiliary loss.
+ """
+ if gate_logits is None or not isinstance(gate_logits, tuple):
+ return 0
+
+ if isinstance(gate_logits, tuple):
+ compute_device = gate_logits[0].device
+ concatenated_gate_logits = torch.cat([layer_gate.to(compute_device) for layer_gate in gate_logits], dim=0)
+
+ routing_weights = torch.nn.functional.softmax(concatenated_gate_logits, dim=-1)
+
+ _, selected_experts = torch.topk(routing_weights, top_k, dim=-1)
+
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_experts)
+
+ if attention_mask is None:
+ # Compute the percentage of tokens routed to each experts
+ tokens_per_expert = torch.mean(expert_mask.float(), dim=0)
+
+ # Compute the average probability of routing to these experts
+ router_prob_per_expert = torch.mean(routing_weights, dim=0)
+ else:
+ batch_size, sequence_length = attention_mask.shape
+ num_hidden_layers = concatenated_gate_logits.shape[0] // (batch_size * sequence_length)
+
+ # Compute the mask that masks all padding tokens as 0 with the same shape of expert_mask
+ expert_attention_mask = (
+ attention_mask[None, :, :, None, None]
+ .expand((num_hidden_layers, batch_size, sequence_length, top_k, num_experts))
+ .reshape(-1, top_k, num_experts)
+ .to(compute_device)
+ )
+
+ # Compute the percentage of tokens routed to each experts
+ tokens_per_expert = torch.sum(expert_mask.float() * expert_attention_mask, dim=0) / torch.sum(
+ expert_attention_mask, dim=0
+ )
+
+ # Compute the mask that masks all padding tokens as 0 with the same shape of tokens_per_expert
+ router_per_expert_attention_mask = (
+ attention_mask[None, :, :, None]
+ .expand((num_hidden_layers, batch_size, sequence_length, num_experts))
+ .reshape(-1, num_experts)
+ .to(compute_device)
+ )
+
+ # Compute the average probability of routing to these experts
+ router_prob_per_expert = torch.sum(routing_weights * router_per_expert_attention_mask, dim=0) / torch.sum(
+ router_per_expert_attention_mask, dim=0
+ )
+
+ overall_loss = torch.sum(tokens_per_expert * router_prob_per_expert.unsqueeze(0))
+ return overall_loss * num_experts
+
+
+@auto_docstring
+class FlexOlmoForCausalLM(FlexOlmoPreTrainedModel, GenerationMixin):
+ _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
+ _tp_plan = {"lm_head": "colwise_gather_output"}
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
+
+ def __init__(self, config):
+ super().__init__(config)
+ self.model = FlexOlmoModel(config)
+ self.vocab_size = config.vocab_size
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
+ self.router_aux_loss_coef = config.router_aux_loss_coef
+ self.num_experts = config.num_experts
+ self.num_experts_per_tok = config.num_experts_per_tok
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ use_cache: bool | None = None,
+ output_router_logits: bool | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> MoeCausalLMOutputWithPast:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
+
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, FlexOlmoForCausalLM
+
+ >>> model = FlexOlmoForCausalLM.from_pretrained("allenai/FlexOlmo-1B-7B-0924")
+ >>> tokenizer = AutoTokenizer.from_pretrained("allenai/FlexOlmo-1B-7B-0924")
+
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
+
+ >>> # Generate
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
+ 'Hey, are you conscious? Can you talk to me?\nI’m not sure if you’re conscious of this, but I’m'
+ ```
+ """
+
+ output_router_logits = (
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
+ )
+
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
+ outputs: MoeModelOutputWithPast = self.model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ output_router_logits=output_router_logits,
+ **kwargs,
+ )
+
+ hidden_states = outputs.last_hidden_state
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
+
+ aux_loss = None
+ if output_router_logits:
+ aux_loss = load_balancing_loss_func(
+ outputs.router_logits,
+ self.num_experts,
+ self.num_experts_per_tok,
+ attention_mask,
+ )
+ if labels is not None:
+ loss += self.router_aux_loss_coef * aux_loss.to(loss.device) # make sure to reside in the same device
+
+ return MoeCausalLMOutputWithPast(
+ loss=loss,
+ aux_loss=aux_loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ router_logits=outputs.router_logits,
+ )
+
+
+__all__ = ["FlexOlmoForCausalLM", "FlexOlmoModel", "FlexOlmoPreTrainedModel"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/flex_olmo/modular_flex_olmo.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/flex_olmo/modular_flex_olmo.py
new file mode 100644
index 0000000000000000000000000000000000000000..01f32227f31fa1ab70f3cb95aa4811991b43b280
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/flex_olmo/modular_flex_olmo.py
@@ -0,0 +1,260 @@
+# Copyright 2025 the HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+import torch
+from huggingface_hub.dataclasses import strict
+
+from ...cache_utils import Cache, DynamicCache
+from ...configuration_utils import PreTrainedConfig
+from ...masking_utils import create_causal_mask
+from ...modeling_outputs import MoeModelOutputWithPast
+from ...modeling_rope_utils import RopeParameters
+from ...processing_utils import Unpack
+from ...utils import TransformersKwargs, auto_docstring
+from ...utils.generic import merge_with_config_defaults
+from ...utils.output_capturing import OutputRecorder, capture_outputs
+from ..mixtral.modeling_mixtral import MixtralModel, MixtralPreTrainedModel
+from ..olmo2.modeling_olmo2 import Olmo2Attention, Olmo2RMSNorm, Olmo2RotaryEmbedding
+from ..olmoe.modeling_olmoe import (
+ OlmoeDecoderLayer,
+ OlmoeForCausalLM,
+ OlmoeMLP,
+ OlmoeSparseMoeBlock,
+ OlmoeTopKRouter,
+)
+
+
+@auto_docstring(checkpoint="allenai/FlexOlmo-7x7B-1T")
+@strict
+class FlexOlmoConfig(PreTrainedConfig):
+ r"""
+ Example:
+
+ ```python
+ >>> from transformers import FlexOlmoModel, FlexOlmoConfig
+
+ >>> # Initializing a FlexOlmo style configuration
+ >>> configuration = FlexOlmoConfig()
+
+ >>> # Initializing a model from the FlexOlmo style configuration
+ >>> model = FlexOlmoModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "flex_olmo"
+ keys_to_ignore_at_inference = ["past_key_values"]
+ attribute_map = {"num_local_experts": "num_experts"}
+ default_theta = 500000.0
+ base_model_tp_plan = {
+ "layers.*.self_attn.q_proj": "colwise_gather_output", # we need to replicate here due to the added norm on q and k
+ "layers.*.self_attn.k_proj": "colwise_gather_output", # we need to replicate here due to the added norm on q and k
+ "layers.*.self_attn.v_proj": "colwise_gather_output", # we need to replicate here due to the added norm on q and k
+ "layers.*.self_attn.o_proj": "rowwise_split_input", # input is replicated due to the added norm on q and k
+ "layers.*.mlp.experts.gate_up_proj": "packed_colwise",
+ "layers.*.mlp.experts.down_proj": "rowwise",
+ "layers.*.mlp.experts": "moe_tp_experts",
+ }
+ base_model_pp_plan = {
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
+ "norm": (["hidden_states"], ["hidden_states"]),
+ }
+
+ vocab_size: int = 100352
+ hidden_size: int = 4096
+ intermediate_size: int = 11008
+ num_hidden_layers: int = 32
+ num_attention_heads: int = 32
+ num_key_value_heads: int | None = None
+ hidden_act: str = "silu"
+ max_position_embeddings: int = 4096
+ initializer_range: float = 0.02
+ rms_norm_eps: float = 1e-06
+ use_cache: bool = True
+ pad_token_id: int | None = 100277
+ bos_token_id: int | None = None
+ eos_token_id: int | list[int] | None = 100257
+ tie_word_embeddings: bool = False
+ rope_parameters: RopeParameters | dict | None = None
+ attention_bias: bool = False
+ attention_dropout: float | None = 0.0
+ num_experts_per_tok: int = 5
+ num_experts: int = 7
+ output_router_logits: bool = False
+ router_aux_loss_coef: float = 0.01
+ norm_topk_prob: bool = False
+
+ def __post_init__(self, **kwargs):
+ if self.num_key_value_heads is None:
+ self.num_key_value_heads = self.num_attention_heads
+ super().__post_init__(**kwargs)
+
+
+# FlexOlmo RMS norm reuses Olmo2 RMS norm, which handles low precision slightly differently than the original Olmoe.
+class FlexOlmoRMSNorm(Olmo2RMSNorm):
+ pass
+
+
+# FlexOlmo RMS norm reuses Olmo2 RMS norm, so that the output cos and sin are returned
+# as float32 rather than the input type.
+class FlexOlmoRotaryEmbedding(Olmo2RotaryEmbedding):
+ pass
+
+
+class FlexOlmoMLP(OlmoeMLP):
+ pass
+
+
+# FlexOlmo uses Olmo2 attention instead of OlmoE Attention since its `apply_rotary_pos_emb`
+# implementation handles lower precision more faithfully to the Olmo codebase.
+class FlexOlmoAttention(Olmo2Attention):
+ pass
+
+
+class FlexOlmoTopKRouter(OlmoeTopKRouter):
+ pass
+
+
+class FlexOlmoSparseMoeBlock(OlmoeSparseMoeBlock):
+ pass
+
+
+# FlexOlmo decoder layer is identical to OlmoE decoder layer except:
+# - Norm is applied after attention/feedforward rather than before.
+class FlexOlmoDecoderLayer(OlmoeDecoderLayer):
+ def __init__(self, config: FlexOlmoConfig, layer_idx: int):
+ super().__init__(config, layer_idx=layer_idx)
+ self.post_attention_layernorm = FlexOlmoRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.post_feedforward_layernorm = FlexOlmoRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.self_attn = FlexOlmoAttention(config=config, layer_idx=layer_idx)
+ del self.input_layernorm
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
+ **kwargs,
+ ) -> torch.FloatTensor:
+ residual = hidden_states
+
+ # Self Attention
+ hidden_states, _ = self.self_attn(
+ hidden_states=hidden_states,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ position_embeddings=position_embeddings,
+ **kwargs,
+ )
+ hidden_states = self.post_attention_layernorm(hidden_states)
+ hidden_states = residual + hidden_states
+
+ # Fully Connected
+ residual = hidden_states
+ hidden_states = self.mlp(hidden_states)
+ hidden_states = self.post_feedforward_layernorm(hidden_states)
+ hidden_states = residual + hidden_states
+ return hidden_states
+
+
+# FlexOlmo uses Mixtral model as its base instead of OlmoE model since Mixtral is more up-to-date with the rest
+# of the transformers library. For example, it uses the newer mechanisms of recording submodule outputs.
+class FlexOlmoPreTrainedModel(MixtralPreTrainedModel):
+ _can_record_outputs = {
+ "router_logits": OutputRecorder(FlexOlmoTopKRouter, index=0),
+ "hidden_states": FlexOlmoDecoderLayer,
+ "attentions": FlexOlmoAttention,
+ }
+
+
+# FlexOlmo uses Mixtral model as its base instead of OlmoE model since Mixtral is more up-to-date with the rest
+# of the transformers library. For example, it uses the newer mechanisms of recording submodule outputs.
+# FlexOlmo model is identical to Mixtral model except:
+# - FlexOlmo does not use sliding window attention.
+class FlexOlmoModel(MixtralModel):
+ @merge_with_config_defaults
+ @capture_outputs
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ use_cache: bool | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> MoeModelOutputWithPast:
+ if (input_ids is None) ^ (inputs_embeds is not None):
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
+
+ if use_cache and past_key_values is None:
+ past_key_values = DynamicCache(config=self.config)
+
+ if inputs_embeds is None:
+ inputs_embeds = self.embed_tokens(input_ids)
+
+ if position_ids is None:
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
+ position_ids = position_ids.unsqueeze(0)
+
+ causal_mask = create_causal_mask(
+ config=self.config,
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ position_ids=position_ids,
+ )
+
+ hidden_states = inputs_embeds
+
+ # create position embeddings to be shared across the decoder layers
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
+
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
+ hidden_states = decoder_layer(
+ hidden_states,
+ position_embeddings=position_embeddings,
+ attention_mask=causal_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ **kwargs,
+ )
+
+ hidden_states = self.norm(hidden_states)
+
+ return MoeModelOutputWithPast( # only diff with Mistral is the output type, we need MoE
+ last_hidden_state=hidden_states,
+ past_key_values=past_key_values,
+ )
+
+
+class FlexOlmoForCausalLM(OlmoeForCausalLM):
+ pass
+
+
+__all__ = [
+ "FlexOlmoConfig",
+ "FlexOlmoForCausalLM",
+ "FlexOlmoModel",
+ "FlexOlmoPreTrainedModel",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/florence2/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/florence2/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..010fbeaae3418dd1c2a8aa18fd7162a6bd89911a
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/florence2/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/florence2/__pycache__/configuration_florence2.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/florence2/__pycache__/configuration_florence2.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6a2cf1ee8c419332e4671576dfaa7bad551ee6f4
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/florence2/__pycache__/configuration_florence2.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/florence2/__pycache__/modeling_florence2.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/florence2/__pycache__/modeling_florence2.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1f33b942bf176eafe655a9d772e9f53d50b63cf6
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/florence2/__pycache__/modeling_florence2.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/florence2/__pycache__/modular_florence2.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/florence2/__pycache__/modular_florence2.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4d2cabb802acb91a316a6edb8a5dd0c9970230ee
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/florence2/__pycache__/modular_florence2.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/florence2/__pycache__/processing_florence2.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/florence2/__pycache__/processing_florence2.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..596197cc354db474c6cdcac306de363b275bf575
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/florence2/__pycache__/processing_florence2.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/focalnet/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/focalnet/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..5dec8135f3b3030b20691e761483e5994ba441f0
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/focalnet/__init__.py
@@ -0,0 +1,27 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_focalnet import *
+ from .modeling_focalnet import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/focalnet/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/focalnet/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..47cb743f423daa33b25ba296f5a22b55f53c37cb
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/focalnet/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/focalnet/__pycache__/configuration_focalnet.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/focalnet/__pycache__/configuration_focalnet.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..05ef1e28663b0c2367ceda082396d50f56ea3877
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/focalnet/__pycache__/configuration_focalnet.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/focalnet/__pycache__/modeling_focalnet.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/focalnet/__pycache__/modeling_focalnet.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bb9b01843ad3b2a91aa57d71c55d3972174c098c
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/focalnet/__pycache__/modeling_focalnet.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/focalnet/configuration_focalnet.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/focalnet/configuration_focalnet.py
new file mode 100644
index 0000000000000000000000000000000000000000..c5bf658bbc2c3bbd60ac52508140d80022ea0aaf
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/focalnet/configuration_focalnet.py
@@ -0,0 +1,98 @@
+# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""FocalNet model configuration"""
+
+from huggingface_hub.dataclasses import strict
+
+from ...backbone_utils import BackboneConfigMixin
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring
+
+
+@auto_docstring(checkpoint="microsoft/focalnet-tiny")
+@strict
+class FocalNetConfig(BackboneConfigMixin, PreTrainedConfig):
+ r"""
+ use_conv_embed (`bool`, *optional*, defaults to `False`):
+ Whether to use convolutional embedding. The authors noted that using convolutional embedding usually
+ improve the performance, but it's not used by default.
+ focal_levels (`list(int)`, *optional*, defaults to `[2, 2, 2, 2]`):
+ Number of focal levels in each layer of the respective stages in the encoder.
+ focal_windows (`list(int)`, *optional*, defaults to `[3, 3, 3, 3]`):
+ Focal window size in each layer of the respective stages in the encoder.
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
+ The dropout probability for all fully connected layers in the embeddings and encoder.
+ use_layerscale (`bool`, *optional*, defaults to `False`):
+ Whether to use layer scale in the encoder.
+ layerscale_value (`float`, *optional*, defaults to 0.0001):
+ The initial value of the layer scale.
+ use_post_layernorm (`bool`, *optional*, defaults to `False`):
+ Whether to use post layer normalization in the encoder.
+ use_post_layernorm_in_modulation (`bool`, *optional*, defaults to `False`):
+ Whether to use post layer normalization in the modulation layer.
+ normalize_modulator (`bool`, *optional*, defaults to `False`):
+ Whether to normalize the modulator.
+ encoder_stride (`int`, *optional*, defaults to 32):
+ Factor to increase the spatial resolution by in the decoder head for masked image modeling.
+
+ Example:
+
+ ```python
+ >>> from transformers import FocalNetConfig, FocalNetModel
+
+ >>> # Initializing a FocalNet microsoft/focalnet-tiny style configuration
+ >>> configuration = FocalNetConfig()
+
+ >>> # Initializing a model (with random weights) from the microsoft/focalnet-tiny style configuration
+ >>> model = FocalNetModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "focalnet"
+
+ image_size: int | list[int] | tuple[int, int] = 224
+ patch_size: int | list[int] | tuple[int, int] = 4
+ num_channels: int = 3
+ embed_dim: int = 96
+ use_conv_embed: bool = False
+ hidden_sizes: list[int] | tuple[int, ...] = (192, 384, 768, 768)
+ depths: list[int] | tuple[int, ...] = (2, 2, 6, 2)
+ focal_levels: list[int] | tuple[int, ...] = (2, 2, 2, 2)
+ focal_windows: list[int] | tuple[int, ...] = (3, 3, 3, 3)
+ hidden_act: str = "gelu"
+ mlp_ratio: float = 4.0
+ hidden_dropout_prob: float | int = 0.0
+ drop_path_rate: float | int = 0.1
+ use_layerscale: bool = False
+ layerscale_value: float = 1e-4
+ use_post_layernorm: bool = False
+ use_post_layernorm_in_modulation: bool = False
+ normalize_modulator: bool = False
+ initializer_range: float = 0.02
+ layer_norm_eps: float = 1e-5
+ encoder_stride: int = 32
+ _out_features: list[str] | None = None
+ _out_indices: list[int] | None = None
+
+ def __post_init__(self, **kwargs):
+ self.stage_names = ["stem"] + [f"stage{idx}" for idx in range(1, len(self.depths) + 1)]
+ self.set_output_features_output_indices(
+ out_indices=kwargs.pop("out_indices", None), out_features=kwargs.pop("out_features", None)
+ )
+ super().__post_init__(**kwargs)
+
+
+__all__ = ["FocalNetConfig"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/focalnet/modeling_focalnet.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/focalnet/modeling_focalnet.py
new file mode 100644
index 0000000000000000000000000000000000000000..31e2cea4b90e5d28d64b4cb3f9f10f6720e54c83
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/focalnet/modeling_focalnet.py
@@ -0,0 +1,928 @@
+# Copyright 2023 Microsoft Research and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch FocalNet model."""
+
+import collections.abc
+import math
+from dataclasses import dataclass
+
+import torch
+from torch import nn
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...backbone_utils import BackboneMixin, filter_output_hidden_states
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import BackboneOutput
+from ...modeling_utils import PreTrainedModel
+from ...utils import ModelOutput, auto_docstring, logging
+from ...utils.generic import can_return_tuple
+from .configuration_focalnet import FocalNetConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+@auto_docstring(
+ custom_intro="""
+ FocalNet encoder's outputs, with potential hidden states.
+ """
+)
+@dataclass
+class FocalNetEncoderOutput(ModelOutput):
+ r"""
+ reshaped_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
+ shape `(batch_size, hidden_size, height, width)`.
+
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs reshaped to
+ include the spatial dimensions.
+ """
+
+ last_hidden_state: torch.FloatTensor | None = None
+ hidden_states: tuple[torch.FloatTensor] | None = None
+ reshaped_hidden_states: tuple[torch.FloatTensor] | None = None
+
+
+@auto_docstring(
+ custom_intro="""
+ FocalNet model's outputs that also contains a pooling of the last hidden states.
+ """
+)
+@dataclass
+class FocalNetModelOutput(ModelOutput):
+ r"""
+ pooler_output (`torch.FloatTensor` of shape `(batch_size, hidden_size)`, *optional*, returned when `add_pooling_layer=True` is passed):
+ Average pooling of the last layer hidden-state.
+ reshaped_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
+ shape `(batch_size, hidden_size, height, width)`.
+
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs reshaped to
+ include the spatial dimensions.
+ """
+
+ last_hidden_state: torch.FloatTensor | None = None
+ pooler_output: torch.FloatTensor | None = None
+ hidden_states: tuple[torch.FloatTensor] | None = None
+ reshaped_hidden_states: tuple[torch.FloatTensor] | None = None
+
+
+@auto_docstring(
+ custom_intro="""
+ FocalNet masked image model outputs.
+ """
+)
+@dataclass
+class FocalNetMaskedImageModelingOutput(ModelOutput):
+ r"""
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `bool_masked_pos` is provided):
+ Masked image modeling (MLM) loss.
+ reconstruction (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
+ Reconstructed pixel values.
+ reshaped_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
+ shape `(batch_size, hidden_size, height, width)`.
+
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs reshaped to
+ include the spatial dimensions.
+ """
+
+ loss: torch.FloatTensor | None = None
+ reconstruction: torch.FloatTensor | None = None
+ hidden_states: tuple[torch.FloatTensor] | None = None
+ reshaped_hidden_states: tuple[torch.FloatTensor] | None = None
+
+
+@auto_docstring(
+ custom_intro="""
+ FocalNet outputs for image classification.
+ """
+)
+@dataclass
+class FocalNetImageClassifierOutput(ModelOutput):
+ r"""
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
+ Classification (or regression if config.num_labels==1) loss.
+ logits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`):
+ Classification (or regression if config.num_labels==1) scores (before SoftMax).
+ reshaped_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
+ shape `(batch_size, hidden_size, height, width)`.
+
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs reshaped to
+ include the spatial dimensions.
+ """
+
+ loss: torch.FloatTensor | None = None
+ logits: torch.FloatTensor | None = None
+ hidden_states: tuple[torch.FloatTensor] | None = None
+ reshaped_hidden_states: tuple[torch.FloatTensor] | None = None
+
+
+class FocalNetEmbeddings(nn.Module):
+ """
+ Construct the patch embeddings and layernorm. Optionally, also the mask token.
+ """
+
+ def __init__(self, config, use_mask_token=False):
+ super().__init__()
+
+ self.patch_embeddings = FocalNetPatchEmbeddings(
+ config=config,
+ image_size=config.image_size,
+ patch_size=config.patch_size,
+ num_channels=config.num_channels,
+ embed_dim=config.embed_dim,
+ use_conv_embed=config.use_conv_embed,
+ is_stem=True,
+ )
+ self.patch_grid = self.patch_embeddings.grid_size
+ self.mask_token = nn.Parameter(torch.zeros(1, 1, config.embed_dim)) if use_mask_token else None
+
+ self.norm = nn.LayerNorm(config.embed_dim, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(
+ self, pixel_values: torch.FloatTensor | None, bool_masked_pos: torch.BoolTensor | None = None
+ ) -> tuple[torch.Tensor]:
+ embeddings, output_dimensions = self.patch_embeddings(pixel_values)
+ embeddings = self.norm(embeddings)
+ batch_size, seq_len, _ = embeddings.size()
+
+ if bool_masked_pos is not None:
+ mask_tokens = self.mask_token.expand(batch_size, seq_len, -1)
+ # replace the masked visual tokens by mask_tokens
+ mask = bool_masked_pos.unsqueeze(-1).type_as(mask_tokens)
+ embeddings = embeddings * (1.0 - mask) + mask_tokens * mask
+
+ embeddings = self.dropout(embeddings)
+ return embeddings, output_dimensions
+
+
+class FocalNetPatchEmbeddings(nn.Module):
+ def __init__(
+ self,
+ config,
+ image_size,
+ patch_size,
+ num_channels,
+ embed_dim,
+ add_norm=False,
+ use_conv_embed=False,
+ is_stem=False,
+ ):
+ super().__init__()
+ image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
+ patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
+ num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
+ self.image_size = image_size
+ self.patch_size = patch_size
+ self.num_channels = num_channels
+ self.num_patches = num_patches
+ self.grid_size = (image_size[0] // patch_size[0], image_size[1] // patch_size[1])
+
+ if use_conv_embed:
+ # if we choose to use conv embedding, then we treat the stem and non-stem differently
+ if is_stem:
+ kernel_size = 7
+ padding = 2
+ stride = 4
+ else:
+ kernel_size = 3
+ padding = 1
+ stride = 2
+ self.projection = nn.Conv2d(
+ num_channels, embed_dim, kernel_size=kernel_size, stride=stride, padding=padding
+ )
+ else:
+ self.projection = nn.Conv2d(num_channels, embed_dim, kernel_size=patch_size, stride=patch_size)
+
+ if add_norm:
+ self.norm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
+ else:
+ self.norm = None
+
+ def maybe_pad(self, pixel_values, height, width):
+ if width % self.patch_size[1] != 0:
+ pad_values = (0, self.patch_size[1] - width % self.patch_size[1])
+ pixel_values = nn.functional.pad(pixel_values, pad_values)
+ if height % self.patch_size[0] != 0:
+ pad_values = (0, 0, 0, self.patch_size[0] - height % self.patch_size[0])
+ pixel_values = nn.functional.pad(pixel_values, pad_values)
+ return pixel_values
+
+ def forward(self, pixel_values: torch.FloatTensor | None) -> tuple[torch.Tensor, tuple[int]]:
+ _, num_channels, height, width = pixel_values.shape
+ if num_channels != self.num_channels:
+ raise ValueError(
+ "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
+ )
+ # pad the input to be divisible by self.patch_size, if needed
+ pixel_values = self.maybe_pad(pixel_values, height, width)
+ embeddings = self.projection(pixel_values)
+ _, _, height, width = embeddings.shape
+ output_dimensions = (height, width)
+ embeddings = embeddings.flatten(2).transpose(1, 2)
+
+ if self.norm is not None:
+ embeddings = self.norm(embeddings)
+
+ return embeddings, output_dimensions
+
+
+class FocalNetModulation(nn.Module):
+ def __init__(self, config, index, dim, focal_factor=2, bias=True, projection_dropout=0.0):
+ super().__init__()
+
+ self.dim = dim
+ self.focal_window = config.focal_windows[index]
+ self.focal_level = config.focal_levels[index]
+ self.focal_factor = focal_factor
+ self.use_post_layernorm_in_modulation = config.use_post_layernorm_in_modulation
+ self.normalize_modulator = config.normalize_modulator
+
+ self.projection_in = nn.Linear(dim, 2 * dim + (self.focal_level + 1), bias=bias)
+ self.projection_context = nn.Conv2d(dim, dim, kernel_size=1, stride=1, bias=bias)
+
+ self.activation = nn.GELU()
+ self.projection_out = nn.Linear(dim, dim)
+ self.projection_dropout = nn.Dropout(projection_dropout)
+ self.focal_layers = nn.ModuleList()
+
+ self.kernel_sizes = []
+ for k in range(self.focal_level):
+ kernel_size = self.focal_factor * k + self.focal_window
+ self.focal_layers.append(
+ nn.Sequential(
+ nn.Conv2d(
+ dim, dim, kernel_size=kernel_size, stride=1, groups=dim, padding=kernel_size // 2, bias=False
+ ),
+ nn.GELU(),
+ )
+ )
+ self.kernel_sizes.append(kernel_size)
+ if self.use_post_layernorm_in_modulation:
+ self.layernorm = nn.LayerNorm(dim, eps=config.layer_norm_eps)
+
+ def forward(self, hidden_state):
+ """
+ Args:
+ hidden_state:
+ Input features with shape of (batch_size, height, width, num_channels)
+ """
+ num_channels = hidden_state.shape[-1]
+
+ # pre linear projection
+ x = self.projection_in(hidden_state).permute(0, 3, 1, 2).contiguous()
+ q, ctx, gates = torch.split(x, (num_channels, num_channels, self.focal_level + 1), 1)
+
+ # context aggregation
+ ctx_all = 0
+ for level in range(self.focal_level):
+ ctx = self.focal_layers[level](ctx)
+ ctx_all = ctx_all + ctx * gates[:, level : level + 1]
+ ctx_global = self.activation(ctx.mean(2, keepdim=True).mean(3, keepdim=True))
+ ctx_all = ctx_all + ctx_global * gates[:, self.focal_level :]
+
+ # normalize context
+ if self.normalize_modulator:
+ ctx_all = ctx_all / (self.focal_level + 1)
+
+ # focal modulation
+ modulator = self.projection_context(ctx_all)
+ x_out = q * modulator
+ x_out = x_out.permute(0, 2, 3, 1).contiguous()
+ if self.use_post_layernorm_in_modulation:
+ x_out = self.layernorm(x_out)
+
+ # post linear projection
+ x_out = self.projection_out(x_out)
+ x_out = self.projection_dropout(x_out)
+ return x_out
+
+
+class FocalNetMlp(nn.Module):
+ def __init__(self, config, in_features, hidden_features=None, out_features=None, drop=0.0):
+ super().__init__()
+ out_features = out_features or in_features
+ hidden_features = hidden_features or in_features
+ self.fc1 = nn.Linear(in_features, hidden_features)
+ self.activation = ACT2FN[config.hidden_act]
+ self.fc2 = nn.Linear(hidden_features, out_features)
+ self.drop = nn.Dropout(drop)
+
+ def forward(self, hidden_state):
+ hidden_state = self.fc1(hidden_state)
+ hidden_state = self.activation(hidden_state)
+ hidden_state = self.drop(hidden_state)
+ hidden_state = self.fc2(hidden_state)
+ hidden_state = self.drop(hidden_state)
+ return hidden_state
+
+
+# Copied from transformers.models.swin.modular_swin.SwinDropPath with SwinDropPath->FocalNetDropPath
+class FocalNetDropPath(nn.Module):
+ """Stochastic depth (DropPath) per sample, for residual blocks.
+
+ Identity when ``drop_prob`` is 0 or outside training. See `Deep Networks with Stochastic Depth
+ `_.
+ """
+
+ def __init__(self, drop_prob: float = 0.0) -> None:
+ super().__init__()
+ self.drop_prob = drop_prob
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ if self.drop_prob == 0.0 or not self.training:
+ return hidden_states
+ keep_prob = 1 - self.drop_prob
+ shape = (hidden_states.shape[0],) + (1,) * (hidden_states.ndim - 1)
+ random_tensor = torch.rand(shape, dtype=hidden_states.dtype, device=hidden_states.device)
+ random_tensor = torch.floor(random_tensor + keep_prob)
+ return hidden_states.div(keep_prob) * random_tensor
+
+ def extra_repr(self) -> str:
+ return f"p={self.drop_prob}"
+
+
+class FocalNetLayer(nn.Module):
+ r"""Focal Modulation Network layer (block).
+
+ Args:
+ config (`FocalNetConfig`):
+ Model config.
+ index (`int`):
+ Layer index.
+ dim (`int`):
+ Number of input channels.
+ input_resolution (`tuple[int]`):
+ Input resolution.
+ drop_path (`float`, *optional*, defaults to 0.0):
+ Stochastic depth rate.
+ """
+
+ def __init__(self, config, index, dim, input_resolution, drop_path=0.0):
+ super().__init__()
+
+ self.config = config
+
+ # layer-specific attributes
+ self.dim = dim
+ self.input_resolution = input_resolution
+
+ # general attributes
+ self.drop = config.hidden_dropout_prob
+ self.use_post_layernorm = config.use_post_layernorm
+
+ self.norm1 = nn.LayerNorm(dim, eps=config.layer_norm_eps)
+ self.modulation = FocalNetModulation(
+ config=config,
+ index=index,
+ dim=dim,
+ projection_dropout=self.drop,
+ )
+
+ self.drop_path = FocalNetDropPath(drop_path) if drop_path > 0.0 else nn.Identity()
+ self.norm2 = nn.LayerNorm(dim, eps=config.layer_norm_eps)
+ mlp_hidden_dim = int(dim * config.mlp_ratio)
+ self.mlp = FocalNetMlp(config=config, in_features=dim, hidden_features=mlp_hidden_dim, drop=self.drop)
+
+ self.gamma_1 = 1.0
+ self.gamma_2 = 1.0
+ if config.use_layerscale:
+ self.gamma_1 = nn.Parameter(config.layerscale_value * torch.ones(dim), requires_grad=True)
+ self.gamma_2 = nn.Parameter(config.layerscale_value * torch.ones(dim), requires_grad=True)
+
+ def forward(self, hidden_state, input_dimensions):
+ height, width = input_dimensions
+ batch_size, _, num_channels = hidden_state.shape
+ shortcut = hidden_state
+
+ # Focal Modulation
+ hidden_state = hidden_state if self.use_post_layernorm else self.norm1(hidden_state)
+ hidden_state = hidden_state.view(batch_size, height, width, num_channels)
+ hidden_state = self.modulation(hidden_state).view(batch_size, height * width, num_channels)
+ hidden_state = hidden_state if not self.use_post_layernorm else self.norm1(hidden_state)
+
+ # FFN
+ hidden_state = shortcut + self.drop_path(self.gamma_1 * hidden_state)
+ hidden_state = hidden_state + self.drop_path(
+ self.gamma_2
+ * (self.norm2(self.mlp(hidden_state)) if self.use_post_layernorm else self.mlp(self.norm2(hidden_state)))
+ )
+
+ return hidden_state
+
+
+class FocalNetStage(GradientCheckpointingLayer):
+ def __init__(self, config, index, input_resolution):
+ super().__init__()
+
+ self.config = config
+ self.num_stages = len(config.depths)
+
+ embed_dim = [config.embed_dim * (2**i) for i in range(self.num_stages)]
+ dim = embed_dim[index]
+ out_dim = embed_dim[index + 1] if (index < self.num_stages - 1) else None
+ downsample = FocalNetPatchEmbeddings if (index < self.num_stages - 1) else None
+
+ # stochastic depth decay rule
+ dpr = [x.item() for x in torch.linspace(0, config.drop_path_rate, sum(config.depths), device="cpu")]
+ drop_path = dpr[sum(config.depths[:index]) : sum(config.depths[: index + 1])]
+
+ self.layers = nn.ModuleList(
+ [
+ FocalNetLayer(
+ config=config,
+ index=index,
+ dim=dim,
+ input_resolution=input_resolution,
+ drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path,
+ )
+ for i in range(config.depths[index])
+ ]
+ )
+
+ if downsample is not None:
+ self.downsample = downsample(
+ config=config,
+ image_size=input_resolution,
+ patch_size=2,
+ num_channels=dim,
+ embed_dim=out_dim,
+ add_norm=True,
+ use_conv_embed=config.use_conv_embed,
+ is_stem=False,
+ )
+ else:
+ self.downsample = None
+
+ self.pointing = False
+
+ def forward(self, hidden_states: torch.Tensor, input_dimensions: tuple[int, int]) -> tuple[torch.Tensor]:
+ height, width = input_dimensions
+ for layer_module in self.layers:
+ hidden_states = layer_module(hidden_states, input_dimensions)
+
+ hidden_states_before_downsampling = hidden_states
+ if self.downsample is not None:
+ height, width = input_dimensions
+ hidden_states = hidden_states.transpose(1, 2).reshape(
+ hidden_states_before_downsampling.shape[0], -1, height, width
+ )
+ hidden_states, output_dimensions = self.downsample(hidden_states)
+
+ else:
+ output_dimensions = (height, width, height, width)
+
+ stage_outputs = (hidden_states, hidden_states_before_downsampling, output_dimensions)
+
+ return stage_outputs
+
+
+class FocalNetEncoder(nn.Module):
+ def __init__(self, config, grid_size):
+ super().__init__()
+ self.num_stages = len(config.depths)
+ self.config = config
+
+ self.stages = nn.ModuleList(
+ [
+ FocalNetStage(
+ config=config,
+ index=i_layer,
+ input_resolution=(grid_size[0] // (2**i_layer), grid_size[1] // (2**i_layer)),
+ )
+ for i_layer in range(self.num_stages)
+ ]
+ )
+
+ self.gradient_checkpointing = False
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ input_dimensions: tuple[int, int],
+ output_hidden_states: bool | None = False,
+ output_hidden_states_before_downsampling: bool | None = False,
+ return_dict: bool | None = True,
+ ) -> tuple | FocalNetEncoderOutput:
+ all_hidden_states = () if output_hidden_states else None
+ all_reshaped_hidden_states = () if output_hidden_states else None
+
+ if output_hidden_states:
+ batch_size, _, hidden_size = hidden_states.shape
+ # rearrange b (h w) c -> b c h w
+ reshaped_hidden_state = hidden_states.view(batch_size, *input_dimensions, hidden_size)
+ reshaped_hidden_state = reshaped_hidden_state.permute(0, 3, 1, 2)
+ all_hidden_states += (hidden_states,)
+ all_reshaped_hidden_states += (reshaped_hidden_state,)
+
+ for i, stage_module in enumerate(self.stages):
+ stage_outputs = stage_module(hidden_states, input_dimensions)
+
+ hidden_states = stage_outputs[0]
+ hidden_states_before_downsampling = stage_outputs[1]
+ output_dimensions = stage_outputs[2]
+
+ input_dimensions = (output_dimensions[-2], output_dimensions[-1])
+
+ if output_hidden_states and output_hidden_states_before_downsampling:
+ batch_size, _, hidden_size = hidden_states_before_downsampling.shape
+ # rearrange b (h w) c -> b c h w
+ # here we use the original (not downsampled) height and width
+ reshaped_hidden_state = hidden_states_before_downsampling.view(
+ batch_size, *(output_dimensions[0], output_dimensions[1]), hidden_size
+ )
+ reshaped_hidden_state = reshaped_hidden_state.permute(0, 3, 1, 2)
+ all_hidden_states += (hidden_states_before_downsampling,)
+ all_reshaped_hidden_states += (reshaped_hidden_state,)
+ elif output_hidden_states and not output_hidden_states_before_downsampling:
+ batch_size, _, hidden_size = hidden_states.shape
+ # rearrange b (h w) c -> b c h w
+ reshaped_hidden_state = hidden_states.view(batch_size, *input_dimensions, hidden_size)
+ reshaped_hidden_state = reshaped_hidden_state.permute(0, 3, 1, 2)
+ all_hidden_states += (hidden_states,)
+ all_reshaped_hidden_states += (reshaped_hidden_state,)
+
+ if not return_dict:
+ return tuple(v for v in [hidden_states, all_hidden_states] if v is not None)
+
+ return FocalNetEncoderOutput(
+ last_hidden_state=hidden_states,
+ hidden_states=all_hidden_states,
+ reshaped_hidden_states=all_reshaped_hidden_states,
+ )
+
+
+@auto_docstring
+class FocalNetPreTrainedModel(PreTrainedModel):
+ config: FocalNetConfig
+ base_model_prefix = "focalnet"
+ main_input_name = "pixel_values"
+ supports_gradient_checkpointing = True
+ _no_split_modules = ["FocalNetStage"]
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ """Initialize the weights"""
+ super()._init_weights(module)
+ if isinstance(module, FocalNetEmbeddings):
+ if module.mask_token is not None:
+ init.zeros_(module.mask_token)
+ elif isinstance(module, FocalNetLayer):
+ if self.config.use_layerscale:
+ init.constant_(module.gamma_1, self.config.layerscale_value)
+ init.constant_(module.gamma_2, self.config.layerscale_value)
+
+
+@auto_docstring
+class FocalNetModel(FocalNetPreTrainedModel):
+ def __init__(self, config, add_pooling_layer=True, use_mask_token=False):
+ r"""
+ add_pooling_layer (bool, *optional*, defaults to `True`):
+ Whether to add a pooling layer
+ use_mask_token (`bool`, *optional*, defaults to `False`):
+ Whether to use a mask token for masked image modeling.
+ """
+ super().__init__(config)
+ self.config = config
+ self.num_stages = len(config.depths)
+ self.num_features = int(config.embed_dim * 2 ** (self.num_stages - 1))
+
+ self.embeddings = FocalNetEmbeddings(config, use_mask_token=use_mask_token)
+ self.encoder = FocalNetEncoder(config, self.embeddings.patch_grid)
+
+ self.layernorm = nn.LayerNorm(self.num_features, eps=config.layer_norm_eps)
+ self.pooler = nn.AdaptiveAvgPool1d(1) if add_pooling_layer else None
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.embeddings.patch_embeddings
+
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: torch.FloatTensor | None = None,
+ bool_masked_pos: torch.BoolTensor | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple | FocalNetModelOutput:
+ r"""
+ bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, num_patches)`):
+ Boolean masked positions. Indicates which patches are masked (1) and which aren't (0).
+ """
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ if pixel_values is None:
+ raise ValueError("You have to specify pixel_values")
+
+ embedding_output, input_dimensions = self.embeddings(pixel_values, bool_masked_pos=bool_masked_pos)
+
+ encoder_outputs = self.encoder(
+ embedding_output,
+ input_dimensions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ sequence_output = encoder_outputs[0]
+ sequence_output = self.layernorm(sequence_output)
+
+ pooled_output = None
+ if self.pooler is not None:
+ pooled_output = self.pooler(sequence_output.transpose(1, 2))
+ pooled_output = torch.flatten(pooled_output, 1)
+
+ if not return_dict:
+ output = (sequence_output, pooled_output) + encoder_outputs[1:]
+
+ return output
+
+ return FocalNetModelOutput(
+ last_hidden_state=sequence_output,
+ pooler_output=pooled_output,
+ hidden_states=encoder_outputs.hidden_states,
+ reshaped_hidden_states=encoder_outputs.reshaped_hidden_states,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ FocalNet Model with a decoder on top for masked image modeling.
+
+ This follows the same implementation as in [SimMIM](https://huggingface.co/papers/2111.09886).
+
+
+
+ Note that we provide a script to pre-train this model on custom data in our [examples
+ directory](https://github.com/huggingface/transformers/tree/main/examples/pytorch/image-pretraining).
+
+
+ """
+)
+class FocalNetForMaskedImageModeling(FocalNetPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.focalnet = FocalNetModel(config, add_pooling_layer=False, use_mask_token=True)
+
+ self.num_stages = len(config.depths)
+ num_features = int(config.embed_dim * 2 ** (self.num_stages - 1))
+ self.decoder = nn.Sequential(
+ nn.Conv2d(
+ in_channels=num_features, out_channels=config.encoder_stride**2 * config.num_channels, kernel_size=1
+ ),
+ nn.PixelShuffle(config.encoder_stride),
+ )
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: torch.FloatTensor | None = None,
+ bool_masked_pos: torch.BoolTensor | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple | FocalNetMaskedImageModelingOutput:
+ r"""
+ bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, num_patches)`):
+ Boolean masked positions. Indicates which patches are masked (1) and which aren't (0).
+
+ Examples:
+ ```python
+ >>> from transformers import AutoImageProcessor, FocalNetConfig, FocalNetForMaskedImageModeling
+ >>> import torch
+ >>> from PIL import Image
+ >>> import httpx
+ >>> from io import BytesIO
+
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
+ >>> with httpx.stream("GET", url) as response:
+ ... image = Image.open(BytesIO(response.read()))
+
+ >>> image_processor = AutoImageProcessor.from_pretrained("microsoft/focalnet-base-simmim-window6-192")
+ >>> config = FocalNetConfig()
+ >>> model = FocalNetForMaskedImageModeling(config)
+
+ >>> num_patches = (model.config.image_size // model.config.patch_size) ** 2
+ >>> pixel_values = image_processor(images=image, return_tensors="pt").pixel_values
+ >>> # create random boolean mask of shape (batch_size, num_patches)
+ >>> bool_masked_pos = torch.randint(low=0, high=2, size=(1, num_patches)).bool()
+
+ >>> outputs = model(pixel_values, bool_masked_pos=bool_masked_pos)
+ >>> loss, reconstructed_pixel_values = outputs.loss, outputs.logits
+ >>> list(reconstructed_pixel_values.shape)
+ [1, 3, 192, 192]
+ ```"""
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ outputs = self.focalnet(
+ pixel_values,
+ bool_masked_pos=bool_masked_pos,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ sequence_output = outputs[0]
+ # Reshape to (batch_size, num_channels, height, width)
+ sequence_output = sequence_output.transpose(1, 2)
+ batch_size, num_channels, sequence_length = sequence_output.shape
+ height = width = math.floor(sequence_length**0.5)
+ sequence_output = sequence_output.reshape(batch_size, num_channels, height, width)
+
+ # Reconstruct pixel values
+ reconstructed_pixel_values = self.decoder(sequence_output)
+
+ masked_im_loss = None
+ if bool_masked_pos is not None:
+ size = self.config.image_size // self.config.patch_size
+ bool_masked_pos = bool_masked_pos.reshape(-1, size, size)
+ mask = (
+ bool_masked_pos.repeat_interleave(self.config.patch_size, 1)
+ .repeat_interleave(self.config.patch_size, 2)
+ .unsqueeze(1)
+ .contiguous()
+ )
+ reconstruction_loss = nn.functional.l1_loss(pixel_values, reconstructed_pixel_values, reduction="none")
+ masked_im_loss = (reconstruction_loss * mask).sum() / (mask.sum() + 1e-5) / self.config.num_channels
+
+ if not return_dict:
+ output = (reconstructed_pixel_values,) + outputs[2:]
+ return ((masked_im_loss,) + output) if masked_im_loss is not None else output
+
+ return FocalNetMaskedImageModelingOutput(
+ loss=masked_im_loss,
+ reconstruction=reconstructed_pixel_values,
+ hidden_states=outputs.hidden_states,
+ reshaped_hidden_states=outputs.reshaped_hidden_states,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ FocalNet Model with an image classification head on top (a linear layer on top of the pooled output) e.g. for
+ ImageNet.
+ """
+)
+class FocalNetForImageClassification(FocalNetPreTrainedModel):
+ # Copied from transformers.models.swin.modeling_swin.SwinForImageClassification.__init__ with Swin->FocalNet, swin->focalnet
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.num_labels = config.num_labels
+ self.focalnet = FocalNetModel(config)
+
+ # Classifier head
+ self.classifier = (
+ nn.Linear(self.focalnet.num_features, config.num_labels) if config.num_labels > 0 else nn.Identity()
+ )
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple | FocalNetImageClassifierOutput:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ outputs = self.focalnet(
+ pixel_values,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ pooled_output = outputs[1]
+
+ logits = self.classifier(pooled_output)
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(labels, logits, self.config)
+
+ if not return_dict:
+ output = (logits,) + outputs[2:]
+ return ((loss,) + output) if loss is not None else output
+
+ return FocalNetImageClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ reshaped_hidden_states=outputs.reshaped_hidden_states,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ FocalNet backbone, to be used with frameworks like X-Decoder.
+ """
+)
+class FocalNetBackbone(BackboneMixin, FocalNetPreTrainedModel):
+ has_attentions = False
+
+ def __init__(self, config: FocalNetConfig):
+ super().__init__(config)
+
+ self.num_features = [config.embed_dim] + config.hidden_sizes
+ self.focalnet = FocalNetModel(config)
+
+ # initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @filter_output_hidden_states
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: torch.Tensor,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> BackboneOutput:
+ r"""
+ Examples:
+
+ ```python
+ >>> from transformers import AutoImageProcessor, AutoBackbone
+ >>> import torch
+ >>> from PIL import Image
+ >>> import httpx
+ >>> from io import BytesIO
+
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
+ >>> with httpx.stream("GET", url) as response:
+ ... image = Image.open(BytesIO(response.read()))
+
+ >>> processor = AutoImageProcessor.from_pretrained("microsoft/focalnet-tiny-lrf")
+ >>> model = AutoBackbone.from_pretrained("microsoft/focalnet-tiny-lrf")
+
+ >>> inputs = processor(image, return_tensors="pt")
+ >>> outputs = model(**inputs)
+ ```"""
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+
+ outputs = self.focalnet(pixel_values, output_hidden_states=True, return_dict=True)
+
+ hidden_states = outputs.reshaped_hidden_states
+
+ feature_maps = ()
+ for idx, stage in enumerate(self.stage_names):
+ if stage in self.out_features:
+ feature_maps += (hidden_states[idx],)
+
+ if not return_dict:
+ output = (feature_maps,)
+ if output_hidden_states:
+ output += (outputs.hidden_states,)
+ return output
+
+ return BackboneOutput(
+ feature_maps=feature_maps,
+ hidden_states=outputs.hidden_states if output_hidden_states else None,
+ attentions=None,
+ )
+
+
+__all__ = [
+ "FocalNetForImageClassification",
+ "FocalNetForMaskedImageModeling",
+ "FocalNetBackbone",
+ "FocalNetModel",
+ "FocalNetPreTrainedModel",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/fsmt/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/fsmt/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..f8f31762d681dbf3541d38c39fafdf5fa6b864d1
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/fsmt/__init__.py
@@ -0,0 +1,28 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_fsmt import *
+ from .modeling_fsmt import *
+ from .tokenization_fsmt import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/fsmt/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/fsmt/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..93ac3ba0f4b216d5e023013931ea759101b310be
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/fsmt/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/fsmt/__pycache__/configuration_fsmt.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/fsmt/__pycache__/configuration_fsmt.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4ade23bf51fbd9be108aa51e9a61cd4a22b9dfa8
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/fsmt/__pycache__/configuration_fsmt.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/fsmt/__pycache__/modeling_fsmt.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/fsmt/__pycache__/modeling_fsmt.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dbbe01d258d133c84aa975b6d8dd6f72604258a7
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/fsmt/__pycache__/modeling_fsmt.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/fsmt/__pycache__/tokenization_fsmt.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/fsmt/__pycache__/tokenization_fsmt.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fa5607e83f85e35b35cc023914c61bb12ca06c07
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/fsmt/__pycache__/tokenization_fsmt.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/fsmt/configuration_fsmt.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/fsmt/configuration_fsmt.py
new file mode 100644
index 0000000000000000000000000000000000000000..bbc1fe601b8e522ee0ff737e68ab8850a9edd235
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/fsmt/configuration_fsmt.py
@@ -0,0 +1,108 @@
+# Copyright 2019-present, Facebook, Inc and the HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""FSMT configuration"""
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring
+
+
+@auto_docstring(checkpoint="facebook/wmt19-en-ru")
+@strict
+class FSMTConfig(PreTrainedConfig):
+ r"""
+ langs (`list[str]`):
+ A list with source language and target_language (e.g., ['en', 'ru']).
+ src_vocab_size (`int`):
+ Vocabulary size of the encoder. Defines the number of different tokens that can be represented by the
+ `inputs_ids` passed to the forward method in the encoder.
+ tgt_vocab_size (`int`):
+ Vocabulary size of the decoder. Defines the number of different tokens that can be represented by the
+ `inputs_ids` passed to the forward method in the decoder.
+ max_length (`int`, *optional*, defaults to 200):
+ Maximum length to generate.
+ num_beams (`int`, *optional*, defaults to 5):
+ Number of beams for beam search that will be used by default in the `generate` method of the model. 1 means
+ no beam search.
+ length_penalty (`float`, *optional*, defaults to 1):
+ Exponential penalty to the length that is used with beam-based generation. It is applied as an exponent to
+ the sequence length, which in turn is used to divide the score of the sequence. Since the score is the log
+ likelihood of the sequence (i.e. negative), `length_penalty` > 0.0 promotes longer sequences, while
+ `length_penalty` < 0.0 encourages shorter sequences.
+ early_stopping (`bool`, *optional*, defaults to `False`):
+ Flag that will be used by default in the `generate` method of the model. Whether to stop the beam search
+ when at least `num_beams` sentences are finished per batch or not.
+
+ Examples:
+
+ ```python
+ >>> from transformers import FSMTConfig, FSMTModel
+
+ >>> # Initializing a FSMT facebook/wmt19-en-ru style configuration
+ >>> config = FSMTConfig()
+
+ >>> # Initializing a model (with random weights) from the configuration
+ >>> model = FSMTModel(config)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "fsmt"
+ attribute_map = {
+ "num_attention_heads": "encoder_attention_heads",
+ "hidden_size": "d_model",
+ "vocab_size": "tgt_vocab_size",
+ "num_hidden_layers": "encoder_layers",
+ }
+
+ langs: list[str] | tuple[str, ...] = ("en", "de")
+ src_vocab_size: int = 42024
+ tgt_vocab_size: int = 42024
+ activation_function: str = "relu"
+ d_model: int = 1024
+ max_length: int = 200
+ max_position_embeddings: int = 1024
+ encoder_ffn_dim: int = 4096
+ encoder_layers: int = 12
+ encoder_attention_heads: int = 16
+ encoder_layerdrop: float | int = 0.0
+ decoder_ffn_dim: int = 4096
+ decoder_layers: int = 12
+ decoder_attention_heads: int = 16
+ decoder_layerdrop: float | int = 0.0
+ attention_dropout: float | int = 0.0
+ dropout: float | int = 0.1
+ activation_dropout: float | int = 0.0
+ init_std: float = 0.02
+ decoder_start_token_id: int | None = 2
+ is_encoder_decoder: bool = True
+ scale_embedding: bool = True
+ tie_word_embeddings: bool = False
+ num_beams: int = 5
+ length_penalty: float = 1.0
+ early_stopping: bool = False
+ use_cache: bool = True
+ pad_token_id: int | None = 1
+ bos_token_id: int | None = 0
+ eos_token_id: int | list[int] | None = 2
+ forced_eos_token_id: int | list[int] | None = 2
+
+ def __post_init__(self, **kwargs):
+ kwargs.pop("decoder", None) # delete unused kwargs
+ super().__post_init__(**kwargs)
+
+
+__all__ = ["FSMTConfig"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/fsmt/modeling_fsmt.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/fsmt/modeling_fsmt.py
new file mode 100644
index 0000000000000000000000000000000000000000..2d364266778d84de7c20b4e68a1fc52482bce0f3
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/fsmt/modeling_fsmt.py
@@ -0,0 +1,1136 @@
+# Copyright 2020 The Facebook AI Research Team Authors and The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# Original implementation: https://github.com/pytorch/fairseq/tree/master/examples/wmt19
+# Authors:
+# - @alexeib Alexei Baevski
+# - @edunov Sergey Edunov
+# - @michaelauli Michael Auli
+# - @myleott Myle Ott
+# - @nng555 Nathan Ng
+# - David Grangier
+# - Kyra Yee
+#
+# Paper: Facebook FAIR's WMT19 News Translation Task Submission https://huggingface.co/papers/1907.06616
+#
+"""PyTorch Fairseq model, ported from https://github.com/pytorch/fairseq/tree/master/examples/wmt19"""
+
+import math
+from typing import Any
+
+import torch
+from torch import Tensor, nn
+from torch.nn import CrossEntropyLoss, LayerNorm
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...cache_utils import Cache, DynamicCache, EncoderDecoderCache
+from ...generation import GenerationMixin
+from ...modeling_outputs import (
+ BaseModelOutput,
+ BaseModelOutputWithPastAndCrossAttentions,
+ Seq2SeqLMOutput,
+ Seq2SeqModelOutput,
+)
+from ...modeling_utils import PreTrainedModel
+from ...utils import auto_docstring, logging
+from .configuration_fsmt import FSMTConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+# See all FSMT models at https://huggingface.co/models?filter=fsmt
+
+# Porting notes:
+# this one is modeled after BartModel*
+#
+# Currently only translation (fairseq also has weights for LM)
+#
+# fairseq provides weights for ru-en, en-ru and de-en, en-de pairs. All have been ported.
+# - ru-en, en-ru use asymmetric vocab
+# - de-en, en-de use a merged single vocab (but the code works as if they are separate)
+#
+# Differences with Bart:
+# - not using bos token
+# - 2 separate vocabs (src and target)
+# - embed weights aren't tied
+# - uses a model Ensemble (but that part isn't ported/implemented yet) - so we
+# aren't getting as good of a BLEU score
+# - uses a projection layer at the end of the decoder
+# - doesn't use final_logits_bias
+# - beam search: stops as soon as num_beams == len(hypos) (whereas transformers
+# is not satisfied there and will continue searching until the next cycles
+# aren't promising something better), comparing BLEU scores - the transformers
+# algorithm is slightly superior, therefore using the latter. But if you want
+# to match fairseq outputs, you need to pass ``early_stopping=True`` to ``generate()``.
+#
+# SinusoidalPositionalEmbedding is slightly different from Bart's - generates
+# different embeddings. This implementation is copied verbatim from fairseq with
+# some small changes to make it work here.
+#
+# Other changes:
+# - doesn't support use_cache as Bart's version does
+#
+#
+# FSMTConfig changes with BartConfig
+#
+# Differences with BART:
+# - src/tgt vocabs aren't shared
+# - token embeddings aren't shared
+# - needs a language pair
+# - scale_embedding are True
+#
+# some unused args were removed too
+#
+#
+# TODO:
+# - port model ensemble (fs uses 4 model checkpoints)
+# - solve beam search discrepancies
+# docstyle-ignore
+
+"""
+
+Here is how to compare BLEU scores against fairseq implementation:
+(don't forget to install sacrebleu: `pip install sacrebleu`)
+
+# en-ru
+
+export PAIR=en-ru
+export DATA_DIR=data/$PAIR
+export SAVE_DIR=data/$PAIR
+export BS=8
+export NUM_BEAMS=50
+mkdir -p $DATA_DIR
+sacrebleu -t wmt19 -l $PAIR --echo src > $DATA_DIR/val.source
+sacrebleu -t wmt19 -l $PAIR --echo ref > $DATA_DIR/val.target
+echo $PAIR
+PYTHONPATH="src:examples/seq2seq" python examples/seq2seq/run_eval.py facebook/wmt19-$PAIR $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS
+
+# (fairseq BLEU: 36.4 http://matrix.statmt.org/matrix/output/1914?score_id=37605)
+
+
+# ru-en
+
+export PAIR=ru-en
+export DATA_DIR=data/$PAIR
+export SAVE_DIR=data/$PAIR
+export BS=8
+export NUM_BEAMS=50
+mkdir -p $DATA_DIR
+sacrebleu -t wmt19 -l $PAIR --echo src > $DATA_DIR/val.source
+sacrebleu -t wmt19 -l $PAIR --echo ref > $DATA_DIR/val.target
+PYTHONPATH="src:examples/seq2seq" python examples/seq2seq/run_eval.py facebook/wmt19-$PAIR $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS
+
+
+# (fairseq BLEU: 41.3 http://matrix.statmt.org/matrix/output/1907?run_id=6937)
+
+
+# de-en
+
+export PAIR=de-en
+export DATA_DIR=data/$PAIR
+export SAVE_DIR=data/$PAIR
+export BS=8
+export NUM_BEAMS=50
+mkdir -p $DATA_DIR
+sacrebleu -t wmt19 -l $PAIR --echo src > $DATA_DIR/val.source
+sacrebleu -t wmt19 -l $PAIR --echo ref > $DATA_DIR/val.target
+echo $PAIR
+PYTHONPATH="src:examples/seq2seq" python examples/seq2seq/run_eval.py facebook/wmt19-$PAIR $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS
+
+# (fairseq BLEU: 42.3 http://matrix.statmt.org/matrix/output/1902?run_id=6750)
+
+
+
+# en-de
+
+export PAIR=en-de
+export DATA_DIR=data/$PAIR
+export SAVE_DIR=data/$PAIR
+export BS=8
+mkdir -p $DATA_DIR
+sacrebleu -t wmt19 -l $PAIR --echo src > $DATA_DIR/val.source
+sacrebleu -t wmt19 -l $PAIR --echo ref > $DATA_DIR/val.target
+echo $PAIR
+PYTHONPATH="src:examples/seq2seq" python examples/seq2seq/run_eval.py facebook/wmt19-$PAIR $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS
+
+# (fairseq BLEU: 43.1 http://matrix.statmt.org/matrix/output/1909?run_id=6862)
+
+"""
+
+
+def invert_mask(attention_mask):
+ """Turns 1->0, 0->1, False->True, True-> False"""
+ assert attention_mask.dim() == 2
+ return attention_mask.eq(0)
+
+
+def triu_onnx(x, diagonal=0):
+ l = x.shape[0]
+ arange = torch.arange(l, device=x.device)
+ mask = arange.expand(l, l)
+ arange = arange.unsqueeze(-1)
+ if diagonal:
+ arange = arange + diagonal
+ mask = mask >= arange
+ return x.masked_fill(mask == 0, 0)
+
+
+def _prepare_fsmt_decoder_inputs(
+ config,
+ input_ids,
+ decoder_input_ids=None,
+ decoder_padding_mask=None,
+ causal_mask_dtype=torch.float32,
+):
+ """
+ Prepare masks that ignore padding tokens in the decoder and a causal mask for the decoder if none are provided.
+ This mimics the default behavior in fairseq. To override it pass in masks. Note: this is not called during
+ generation
+ """
+ pad_token_id = config.pad_token_id
+ if decoder_input_ids is None:
+ decoder_input_ids = shift_tokens_right(input_ids, pad_token_id)
+ bsz, tgt_len = decoder_input_ids.size()
+ if decoder_padding_mask is None:
+ decoder_padding_mask = make_padding_mask(decoder_input_ids, pad_token_id)
+ else:
+ decoder_padding_mask = invert_mask(decoder_padding_mask)
+ causal_mask = triu_onnx(fill_with_neg_inf(torch.zeros(tgt_len, tgt_len, dtype=causal_mask_dtype)), 1).to(
+ device=decoder_input_ids.device
+ )
+ return decoder_input_ids, decoder_padding_mask, causal_mask
+
+
+@auto_docstring
+class PretrainedFSMTModel(PreTrainedModel):
+ config: FSMTConfig
+ base_model_prefix = "model"
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ std = self.config.init_std
+ if isinstance(module, nn.Linear):
+ init.normal_(module.weight, mean=0.0, std=std)
+ if module.bias is not None:
+ init.zeros_(module.bias)
+ elif isinstance(module, SinusoidalPositionalEmbedding):
+ weight = module.get_embedding(*module.weight.shape, module.padding_idx)
+ init.copy_(module.weight, weight)
+ elif isinstance(module, nn.Embedding):
+ init.normal_(module.weight, mean=0.0, std=std)
+ # Here we need the check explicitly, as we slice the weight in the `zeros_` call, so it looses the flag
+ if module.padding_idx is not None and not getattr(module.weight, "_is_hf_initialized", False):
+ init.zeros_(module.weight[module.padding_idx])
+
+ @property
+ def dummy_inputs(self):
+ pad_token = self.config.pad_token_id
+ input_ids = torch.tensor([[0, 6, 10, 4, 2], [0, 8, 12, 2, pad_token]], device=self.device)
+ dummy_inputs = {
+ "attention_mask": input_ids.ne(pad_token),
+ "input_ids": input_ids,
+ }
+ return dummy_inputs
+
+
+def _make_linear_from_emb(emb):
+ vocab_size, emb_size = emb.weight.shape
+ lin_layer = nn.Linear(vocab_size, emb_size, bias=False)
+ lin_layer.weight.data = emb.weight.data
+ return lin_layer
+
+
+# Helper Functions, mostly for making masks
+def _check_shapes(shape_1, shape2):
+ if shape_1 != shape2:
+ raise AssertionError(f"shape mismatch: {shape_1} != {shape2}")
+
+
+def shift_tokens_right(input_ids, pad_token_id):
+ """Shift input ids one token to the right, and wrap the last non pad token (usually )."""
+
+ # replace possible -100 values in labels by `pad_token_id`
+ input_ids.masked_fill_(input_ids == -100, pad_token_id)
+
+ prev_output_tokens = input_ids.clone()
+ index_of_eos = (input_ids.ne(pad_token_id).sum(dim=1) - 1).unsqueeze(-1)
+ prev_output_tokens[:, 0] = input_ids.gather(1, index_of_eos).squeeze()
+ prev_output_tokens[:, 1:] = input_ids[:, :-1]
+ return prev_output_tokens
+
+
+def make_padding_mask(input_ids, padding_idx=1):
+ """True for pad tokens"""
+ padding_mask = input_ids.eq(padding_idx)
+ if not padding_mask.any():
+ padding_mask = None
+ return padding_mask
+
+
+# Helper Modules
+
+
+class EncoderLayer(nn.Module):
+ def __init__(self, config: FSMTConfig):
+ super().__init__()
+ self.embed_dim = config.d_model
+ self.self_attn = Attention(self.embed_dim, config.encoder_attention_heads, dropout=config.attention_dropout)
+ self.self_attn_layer_norm = LayerNorm(self.embed_dim)
+ self.dropout = config.dropout
+ self.activation_fn = ACT2FN[config.activation_function]
+ self.activation_dropout = config.activation_dropout
+ self.fc1 = nn.Linear(self.embed_dim, config.encoder_ffn_dim)
+ self.fc2 = nn.Linear(config.encoder_ffn_dim, self.embed_dim)
+ self.final_layer_norm = LayerNorm(self.embed_dim)
+
+ def forward(self, x, encoder_padding_mask, output_attentions=False):
+ """
+ Args:
+ x (`torch.Tensor`): input to the layer of shape *(seq_len, batch, embed_dim)*
+ encoder_padding_mask (`torch.ByteTensor`): binary ByteTensor of shape
+ *(batch, src_len)* where padding elements are indicated by `1`.
+ for t_tgt, t_src is excluded (or masked out), =0 means it is
+ included in attention
+
+ Returns:
+ encoded output of shape *(seq_len, batch, embed_dim)*
+ """
+ residual = x
+ x, attn_weights = self.self_attn(
+ query=x,
+ key=x,
+ key_padding_mask=encoder_padding_mask,
+ output_attentions=output_attentions,
+ )
+ x = nn.functional.dropout(x, p=self.dropout, training=self.training)
+ x = residual + x
+ x = self.self_attn_layer_norm(x)
+
+ residual = x
+ x = self.activation_fn(self.fc1(x))
+ x = nn.functional.dropout(x, p=self.activation_dropout, training=self.training)
+ x = self.fc2(x)
+ x = nn.functional.dropout(x, p=self.dropout, training=self.training)
+ x = residual + x
+ x = self.final_layer_norm(x)
+ return x, attn_weights
+
+
+class FSMTEncoder(nn.Module):
+ """
+ Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a [`EncoderLayer`].
+
+ Args:
+ config: FSMTConfig
+ """
+
+ def __init__(self, config: FSMTConfig):
+ super().__init__()
+ self.dropout = config.dropout
+ self.layerdrop = config.encoder_layerdrop
+ self.padding_idx = config.pad_token_id
+ self.embed_tokens = nn.Embedding(config.src_vocab_size, config.d_model, config.pad_token_id)
+ embed_dim = self.embed_tokens.embedding_dim
+ self.embed_scale = math.sqrt(embed_dim) if config.scale_embedding else 1.0
+ self.embed_positions = SinusoidalPositionalEmbedding(
+ config.max_position_embeddings + self.padding_idx + 1, embed_dim, self.padding_idx
+ )
+ self.layers = nn.ModuleList([EncoderLayer(config) for _ in range(config.encoder_layers)]) # type: list[EncoderLayer]
+
+ def forward(
+ self,
+ input_ids: torch.Tensor,
+ attention_mask: torch.Tensor | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ output_attentions: bool = False,
+ output_hidden_states: bool = False,
+ return_dict: bool = True,
+ ):
+ """
+ Args:
+ input_ids (`torch.LongTensor`): tokens in the source language of shape
+ *(batch, src_len)*
+ attention_mask (`torch.LongTensor`): indicating which indices are padding tokens
+ inputs_embeds (`torch.FloatTensor`):
+ embedding vectors of shape *(batch, src_len, embed_dim)*
+
+ Returns:
+ BaseModelOutput or Tuple comprised of:
+
+ - **x** (`torch.Tensor`): the last encoder layer's output of shape *(src_len, batch, embed_dim)*
+ - **encoder_states** (`Tuple(torch.FloatTensor)`): all intermediate hidden states of shape *(src_len,
+ batch, embed_dim)*. Only populated if *output_hidden_states:* is True.
+ - **all_attentions** (`Tuple(torch.FloatTensor)`): Attention weights for each layer.
+ During training might not be of length n_layers because of layer dropout.
+ """
+ # check attention mask and invert
+ if attention_mask is not None:
+ attention_mask = invert_mask(attention_mask)
+
+ if input_ids is not None and inputs_embeds is not None:
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
+ elif input_ids is not None:
+ inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
+ embed_pos = self.embed_positions(input_ids)
+ elif inputs_embeds is not None:
+ inputs_embeds = inputs_embeds * self.embed_scale
+
+ # We assume zeros hidden states correspond to padding tokens
+ # and create `position_ids` where inputs_embeds[:, :, 0] == 0
+ position_ids = inputs_embeds[:, :, 0].masked_fill(
+ inputs_embeds[:, :, 0].eq(0), self.embed_positions.padding_idx
+ )
+
+ embed_pos = self.embed_positions(position_ids)
+ else:
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
+
+ x = inputs_embeds + embed_pos
+ x = nn.functional.dropout(x, p=self.dropout, training=self.training)
+
+ # B x T x C -> T x B x C
+ x = x.transpose(0, 1)
+
+ encoder_states = () if output_hidden_states else None
+ all_attentions = () if output_attentions else None
+ for idx, encoder_layer in enumerate(self.layers):
+ if output_hidden_states:
+ x = x.transpose(0, 1) # T x B x C -> B x T x C
+ encoder_states += (x,)
+ x = x.transpose(0, 1) # B x T x C -> T x B x C
+ # add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
+ dropout_probability = torch.rand([])
+ if self.training and (dropout_probability < self.layerdrop): # skip the layer
+ attn = None
+ else:
+ x, attn = encoder_layer(
+ x,
+ attention_mask,
+ output_attentions=output_attentions,
+ )
+
+ if output_attentions:
+ all_attentions = all_attentions + (attn,)
+
+ # T x B x C -> B x T x C
+ x = x.transpose(0, 1)
+
+ if output_hidden_states:
+ encoder_states += (x,)
+
+ if not return_dict:
+ return tuple(v for v in [x, encoder_states, all_attentions] if v is not None)
+ return BaseModelOutput(last_hidden_state=x, hidden_states=encoder_states, attentions=all_attentions)
+
+
+class DecoderLayer(nn.Module):
+ def __init__(self, config: FSMTConfig, layer_idx=None):
+ super().__init__()
+ self.embed_dim = config.d_model
+
+ self.self_attn = Attention(
+ embed_dim=self.embed_dim,
+ num_heads=config.decoder_attention_heads,
+ dropout=config.attention_dropout,
+ layer_idx=layer_idx,
+ )
+ self.dropout = config.dropout
+ self.activation_fn = ACT2FN[config.activation_function]
+ self.activation_dropout = config.activation_dropout
+
+ self.self_attn_layer_norm = LayerNorm(self.embed_dim)
+ self.encoder_attn = Attention(
+ self.embed_dim,
+ config.decoder_attention_heads,
+ dropout=config.attention_dropout,
+ encoder_decoder_attention=True,
+ layer_idx=layer_idx,
+ )
+ self.encoder_attn_layer_norm = LayerNorm(self.embed_dim)
+ self.fc1 = nn.Linear(self.embed_dim, config.decoder_ffn_dim)
+ self.fc2 = nn.Linear(config.decoder_ffn_dim, self.embed_dim)
+ self.final_layer_norm = LayerNorm(self.embed_dim)
+
+ def forward(
+ self,
+ x,
+ encoder_hidden_states,
+ encoder_attn_mask=None,
+ layer_state=None,
+ causal_mask=None,
+ decoder_padding_mask=None,
+ output_attentions=False,
+ **kwargs,
+ ):
+ residual = x
+
+ # Self Attention
+ x, self_attn_weights = self.self_attn(
+ query=x,
+ key=x,
+ layer_state=layer_state, # adds keys to layer state
+ key_padding_mask=decoder_padding_mask,
+ attn_mask=causal_mask,
+ output_attentions=output_attentions,
+ )
+ x = nn.functional.dropout(x, p=self.dropout, training=self.training)
+ x = residual + x
+ x = self.self_attn_layer_norm(x)
+
+ # Cross attention
+ residual = x
+ assert self.encoder_attn.cache_key != self.self_attn.cache_key
+ x, cross_attn_weights = self.encoder_attn(
+ query=x,
+ key=encoder_hidden_states,
+ key_padding_mask=encoder_attn_mask,
+ layer_state=layer_state, # mutates layer state
+ output_attentions=output_attentions,
+ )
+ x = nn.functional.dropout(x, p=self.dropout, training=self.training)
+ x = residual + x
+ x = self.encoder_attn_layer_norm(x)
+
+ # Fully Connected
+ residual = x
+ x = self.activation_fn(self.fc1(x))
+ x = nn.functional.dropout(x, p=self.activation_dropout, training=self.training)
+ x = self.fc2(x)
+ x = nn.functional.dropout(x, p=self.dropout, training=self.training)
+ x = residual + x
+ x = self.final_layer_norm(x)
+ return (
+ x,
+ self_attn_weights,
+ cross_attn_weights,
+ )
+
+
+class FSMTDecoder(nn.Module):
+ """
+ Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`DecoderLayer`]
+
+ Args:
+ config: FSMTConfig
+ embed_tokens (nn.Embedding): output embedding
+ """
+
+ def __init__(self, config: FSMTConfig):
+ super().__init__()
+ self.dropout = config.dropout
+ self.layerdrop = config.decoder_layerdrop
+ self.padding_idx = config.pad_token_id
+ self.embed_scale = math.sqrt(config.d_model) if config.scale_embedding else 1.0
+ self.embed_tokens = nn.Embedding(config.tgt_vocab_size, config.d_model, self.padding_idx)
+ embed_dim = self.embed_tokens.embedding_dim
+ self.embed_positions = SinusoidalPositionalEmbedding(
+ config.max_position_embeddings + self.padding_idx + 1, embed_dim, self.padding_idx
+ )
+ self.layers = nn.ModuleList([DecoderLayer(config, layer_idx=i) for i in range(config.decoder_layers)]) # type: list[DecoderLayer]
+ self.output_projection = nn.Linear(config.d_model, config.tgt_vocab_size, bias=False)
+
+ def forward(
+ self,
+ input_ids: torch.Tensor,
+ encoder_hidden_states: torch.Tensor,
+ encoder_padding_mask: torch.Tensor,
+ decoder_padding_mask: torch.Tensor,
+ decoder_causal_mask: torch.Tensor,
+ inputs_embeds: torch.Tensor | None = None,
+ past_key_values: Cache | None = None,
+ use_cache: bool | None = False,
+ output_attentions: bool | None = False,
+ output_hidden_states: bool | None = False,
+ return_dict: bool | None = True,
+ **kwargs,
+ ):
+ """
+ Includes several features from "Jointly Learning to Align and Translate with Transformer Models" (Garg et al.,
+ EMNLP 2019).
+
+ Args:
+ input_ids (`torch.LongTensor` of shape `(batch, tgt_len)`):
+ previous decoder outputs for teacher forcing
+ encoder_hidden_states: output from the encoder, used for
+ encoder-side attention
+ encoder_padding_mask: for ignoring pad tokens
+ past_key_values (dict or None): dictionary used for storing state during generation
+
+ Returns:
+ BaseModelOutputWithPast or tuple:
+
+ - the decoder's features of shape *(batch, tgt_len, embed_dim)*
+ - the cache
+ - hidden states
+ - attentions
+ """
+ # check attention mask and invert
+ if encoder_padding_mask is not None:
+ encoder_padding_mask = invert_mask(encoder_padding_mask)
+
+ if input_ids is not None and inputs_embeds is not None:
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
+ elif input_ids is not None:
+ # embed positions
+ positions = self.embed_positions(input_ids)
+ if use_cache:
+ input_ids = input_ids[:, -1:]
+ positions = positions[:, -1:] # happens after we embed them
+ x = self.embed_tokens(input_ids) * self.embed_scale
+ elif inputs_embeds is not None:
+ # We assume zeros hidden states correspond to padding tokens
+ # and create `position_ids` where inputs_embeds[:, :, 0] == 0
+ position_ids = inputs_embeds[:, :, 0].masked_fill(
+ inputs_embeds[:, :, 0].eq(0), self.embed_positions.padding_idx
+ )
+ positions = self.embed_positions(position_ids)
+ x = inputs_embeds * self.embed_scale
+ else:
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
+
+ x += positions
+ x = nn.functional.dropout(x, p=self.dropout, training=self.training)
+
+ # Convert to FSMT output format: (BS, seq_len, model_dim) -> (seq_len, BS, model_dim)
+ x = x.transpose(0, 1)
+ encoder_hidden_states = encoder_hidden_states.transpose(0, 1)
+
+ # decoder layers
+ all_hidden_states = () if output_hidden_states else None
+ all_self_attns = () if output_attentions else None
+ all_cross_attns = () if output_attentions else None
+
+ for idx, decoder_layer in enumerate(self.layers):
+ # add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
+ if output_hidden_states:
+ x = x.transpose(0, 1)
+ all_hidden_states += (x,)
+ x = x.transpose(0, 1)
+ if self.training:
+ dropout_probability = torch.rand([])
+ if dropout_probability < self.layerdrop:
+ continue
+
+ x, layer_self_attn, layer_cross_attn = decoder_layer(
+ x,
+ encoder_hidden_states,
+ encoder_attn_mask=encoder_padding_mask,
+ decoder_padding_mask=decoder_padding_mask,
+ layer_state=past_key_values,
+ causal_mask=decoder_causal_mask,
+ output_attentions=output_attentions,
+ )
+
+ if output_attentions:
+ all_self_attns += (layer_self_attn,)
+ all_cross_attns += (layer_cross_attn,)
+
+ # add hidden states from the last decoder layer
+ if output_hidden_states:
+ x = x.transpose(0, 1)
+ all_hidden_states += (x,)
+ x = x.transpose(0, 1)
+
+ # Convert to standard output format: (seq_len, BS, model_dim) -> (BS, seq_len, model_dim)
+ x = x.transpose(0, 1)
+ encoder_hidden_states = encoder_hidden_states.transpose(0, 1)
+
+ x = self.output_projection(x)
+
+ if not return_dict:
+ return tuple(
+ v for v in [x, past_key_values, all_hidden_states, all_self_attns, all_cross_attns] if v is not None
+ )
+ return BaseModelOutputWithPastAndCrossAttentions(
+ last_hidden_state=x,
+ past_key_values=past_key_values,
+ hidden_states=all_hidden_states,
+ attentions=all_self_attns,
+ cross_attentions=all_cross_attns,
+ )
+
+
+def _reorder_buffer(attn_cache, new_order):
+ for k, input_buffer_k in attn_cache.items():
+ if input_buffer_k is not None:
+ attn_cache[k] = input_buffer_k.index_select(0, new_order)
+ return attn_cache
+
+
+class Attention(nn.Module):
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
+
+ def __init__(
+ self,
+ embed_dim,
+ num_heads,
+ dropout=0.0,
+ bias=True,
+ encoder_decoder_attention=False, # otherwise self_attention
+ layer_idx=None,
+ ):
+ super().__init__()
+ self.embed_dim = embed_dim
+ self.num_heads = num_heads
+ self.dropout = dropout
+ self.head_dim = embed_dim // num_heads
+ assert self.head_dim * num_heads == self.embed_dim, "embed_dim must be divisible by num_heads"
+ self.scaling = self.head_dim**-0.5
+ self.layer_idx = layer_idx
+
+ self.encoder_decoder_attention = encoder_decoder_attention
+ self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
+ self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
+ self.cache_key = "encoder_decoder" if self.encoder_decoder_attention else "self"
+
+ def forward(
+ self,
+ query,
+ key: Tensor | None,
+ key_padding_mask: Tensor | None = None,
+ layer_state: Cache | None = None,
+ attn_mask: Tensor | None = None,
+ output_attentions: bool | None = False,
+ **kwargs,
+ ) -> tuple[Tensor, Tensor | None]:
+ """Input shape: Time(SeqLen) x Batch x Channel"""
+ tgt_len, bsz, embed_dim = query.size()
+ assert embed_dim == self.embed_dim
+ assert list(query.size()) == [tgt_len, bsz, embed_dim]
+
+ if layer_state is not None:
+ if isinstance(layer_state, EncoderDecoderCache):
+ is_updated = layer_state.is_updated.get(self.layer_idx)
+ if self.encoder_decoder_attention:
+ # after the first generated id, we can subsequently re-use all key/value_states from cache
+ curr_past_key_values = layer_state.cross_attention_cache
+ else:
+ curr_past_key_values = layer_state.self_attention_cache
+ else:
+ curr_past_key_values = layer_state
+
+ # NOTE: FSMT has format (seq_len, BS, model_dim) for inputs
+ current_states = key if self.encoder_decoder_attention else query
+ if self.encoder_decoder_attention and layer_state is not None and is_updated:
+ # reuse k,v, cross_attentions
+ key_states = curr_past_key_values.layers[self.layer_idx].keys
+ value_states = curr_past_key_values.layers[self.layer_idx].values
+ else:
+ key_states = self.k_proj(current_states)
+ value_states = self.v_proj(current_states)
+ key_states = key_states.view(-1, bsz, self.num_heads, self.head_dim).permute(1, 2, 0, 3)
+ value_states = value_states.view(-1, bsz, self.num_heads, self.head_dim).permute(1, 2, 0, 3)
+
+ if layer_state is not None:
+ # save all key/value_states to cache to be re-used for fast auto-regressive generation
+ key_states, value_states = curr_past_key_values.update(key_states, value_states, self.layer_idx)
+ # set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls
+ if self.encoder_decoder_attention:
+ layer_state.is_updated[self.layer_idx] = True
+
+ query_states = self.q_proj(query) * self.scaling
+
+ # Reshape back to 3D tensors for `bmm`
+ query_states = query_states.view(-1, bsz * self.num_heads, self.head_dim).transpose(0, 1)
+ key_states = key_states.reshape(bsz * self.num_heads, -1, self.head_dim)
+ value_states = value_states.reshape(bsz * self.num_heads, -1, self.head_dim)
+
+ assert key_states is not None
+ src_len = key_states.size(1)
+ attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
+ assert attn_weights.size() == (bsz * self.num_heads, tgt_len, src_len)
+
+ if attn_mask is not None:
+ attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attn_mask
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
+
+ # This is part of a workaround to get around fork/join parallelism not supporting Optional types.
+ if key_padding_mask is not None and key_padding_mask.dim() == 0:
+ key_padding_mask = None
+ assert key_padding_mask is None or key_padding_mask.size()[:2] == (
+ bsz,
+ src_len,
+ )
+
+ if key_padding_mask is not None: # don't attend to padding symbols
+ attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
+ reshaped = key_padding_mask.unsqueeze(1).unsqueeze(2)
+ attn_weights = attn_weights.masked_fill(reshaped, torch.finfo(attn_weights.dtype).min)
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
+
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
+
+ if output_attentions:
+ # make sure that attn_weights are included in graph
+ attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
+ attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
+ else:
+ attn_weights_reshaped = None
+
+ attn_probs = nn.functional.dropout(
+ attn_weights,
+ p=self.dropout,
+ training=self.training,
+ )
+
+ assert value_states is not None
+ attn_output = torch.bmm(attn_probs, value_states)
+ assert attn_output.size() == (bsz * self.num_heads, tgt_len, self.head_dim)
+ attn_output = attn_output.transpose(0, 1).contiguous().view(tgt_len, bsz, embed_dim)
+ attn_output = self.out_proj(attn_output)
+
+ return attn_output, attn_weights_reshaped
+
+
+def fill_with_neg_inf(t):
+ """FP16-compatible function that fills a input_ids with -inf."""
+ return t.float().fill_(torch.finfo(t.dtype).min).type_as(t)
+
+
+# Public API
+def _get_shape(t):
+ return getattr(t, "shape", None)
+
+
+@auto_docstring
+class FSMTModel(PretrainedFSMTModel):
+ _tied_weights_keys = {
+ "encoder.embed_tokens.weight": "decoder.embed_tokens.weight",
+ "decoder.output_projection.weight": "decoder.embed_tokens.weight",
+ }
+
+ def __init__(self, config: FSMTConfig):
+ super().__init__(config)
+ self.encoder = FSMTEncoder(config)
+ self.decoder = FSMTDecoder(config)
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor,
+ attention_mask: torch.Tensor | None = None,
+ decoder_input_ids: torch.LongTensor | None = None,
+ decoder_attention_mask: torch.BoolTensor | None = None,
+ encoder_outputs: tuple[torch.FloatTensor] | None = None,
+ past_key_values: Cache | None = None,
+ use_cache: bool | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ decoder_inputs_embeds: torch.FloatTensor | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple[torch.Tensor] | Seq2SeqModelOutput:
+ r"""
+ decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
+ Indices of decoder input sequence tokens in the vocabulary.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are decoder input IDs?](../glossary#decoder-input-ids)
+
+ FSMT uses the `eos_token_id` as the starting token for `decoder_input_ids` generation. If `past_key_values`
+ is used, optionally only the last `decoder_input_ids` have to be input (see `past_key_values`).
+ decoder_attention_mask (`torch.BoolTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
+ Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
+ be used by default.
+ """
+ if decoder_input_ids is None:
+ use_cache = False
+
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ # make masks if user doesn't supply
+ if not use_cache and input_ids is not None:
+ decoder_input_ids, decoder_padding_mask, causal_mask = _prepare_fsmt_decoder_inputs(
+ self.config,
+ input_ids,
+ decoder_input_ids=decoder_input_ids,
+ decoder_padding_mask=decoder_attention_mask,
+ causal_mask_dtype=self.decoder.embed_tokens.weight.dtype,
+ )
+ else:
+ decoder_padding_mask, causal_mask = None, None
+
+ if decoder_input_ids is None and decoder_inputs_embeds is None:
+ raise ValueError("Make sure that `decoder_input_ids` or `decoder_inputs_embeds` are passed.")
+
+ if use_cache and past_key_values is None:
+ past_key_values = EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache(config=self.config))
+
+ if encoder_outputs is None:
+ encoder_outputs = self.encoder(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+ # If the user passed a tuple for encoder_outputs, we wrap it in a BaseModelOutput when return_dict=False
+ elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):
+ encoder_outputs = BaseModelOutput(
+ last_hidden_state=encoder_outputs[0],
+ hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
+ attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
+ )
+
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
+ decoder_outputs = self.decoder(
+ decoder_input_ids,
+ encoder_outputs[0],
+ attention_mask,
+ decoder_padding_mask,
+ decoder_causal_mask=causal_mask,
+ inputs_embeds=decoder_inputs_embeds,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ if not return_dict:
+ return decoder_outputs + encoder_outputs
+
+ return Seq2SeqModelOutput(
+ last_hidden_state=decoder_outputs.last_hidden_state,
+ past_key_values=decoder_outputs.past_key_values,
+ decoder_hidden_states=decoder_outputs.hidden_states,
+ decoder_attentions=decoder_outputs.attentions,
+ cross_attentions=decoder_outputs.cross_attentions,
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
+ encoder_hidden_states=encoder_outputs.hidden_states,
+ encoder_attentions=encoder_outputs.attentions,
+ )
+
+ def get_input_embeddings(self):
+ return self.encoder.embed_tokens
+
+ def set_input_embeddings(self, value):
+ self.encoder.embed_tokens = value
+
+ def get_output_embeddings(self):
+ return self.decoder.embed_tokens
+
+ def set_output_embeddings(self, value):
+ self.decoder.embed_tokens = value
+
+
+@auto_docstring(
+ custom_intro="""
+ The FSMT Model with a language modeling head. Can be used for summarization.
+ """
+)
+class FSMTForConditionalGeneration(PretrainedFSMTModel, GenerationMixin):
+ base_model_prefix = "model"
+
+ def __init__(self, config: FSMTConfig):
+ super().__init__(config)
+ base_model = FSMTModel(config)
+ self.model = base_model
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ decoder_input_ids: torch.LongTensor | None = None,
+ decoder_attention_mask: torch.BoolTensor | None = None,
+ encoder_outputs: tuple[torch.FloatTensor] | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ decoder_inputs_embeds: torch.Tensor | None = None,
+ labels: torch.LongTensor | None = None,
+ use_cache: bool | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple[torch.Tensor] | Seq2SeqLMOutput:
+ r"""
+ decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
+ Indices of decoder input sequence tokens in the vocabulary.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are decoder input IDs?](../glossary#decoder-input-ids)
+
+ FSMT uses the `eos_token_id` as the starting token for `decoder_input_ids` generation. If `past_key_values`
+ is used, optionally only the last `decoder_input_ids` have to be input (see `past_key_values`).
+ decoder_attention_mask (`torch.BoolTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
+ Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
+ be used by default.
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
+
+ Example Translation:
+
+ ```python
+ >>> from transformers import AutoTokenizer, FSMTForConditionalGeneration
+
+ >>> mname = "facebook/wmt19-ru-en"
+ >>> model = FSMTForConditionalGeneration.from_pretrained(mname)
+ >>> tokenizer = AutoTokenizer.from_pretrained(mname)
+
+ >>> src_text = "Машинное обучение - это здорово, не так ли?"
+ >>> input_ids = tokenizer(src_text, return_tensors="pt").input_ids
+ >>> outputs = model.generate(input_ids, num_beams=5, num_return_sequences=3)
+ >>> tokenizer.decode(outputs[0], skip_special_tokens=True)
+ "Machine learning is great, isn't it?"
+ ```
+ """
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ if labels is not None:
+ use_cache = False
+
+ outputs = self.model(
+ input_ids,
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ decoder_input_ids=decoder_input_ids,
+ decoder_inputs_embeds=decoder_inputs_embeds,
+ encoder_outputs=encoder_outputs,
+ decoder_attention_mask=decoder_attention_mask,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+ lm_logits = outputs[0]
+
+ masked_lm_loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ # TODO(SS): do we need to ignore pad tokens in labels?
+ masked_lm_loss = loss_fct(lm_logits.view(-1, self.config.tgt_vocab_size), labels.view(-1))
+
+ if not return_dict:
+ output = (lm_logits,) + outputs[1:]
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
+
+ return Seq2SeqLMOutput(
+ loss=masked_lm_loss,
+ logits=lm_logits,
+ past_key_values=outputs.past_key_values,
+ decoder_hidden_states=outputs.decoder_hidden_states,
+ decoder_attentions=outputs.decoder_attentions,
+ cross_attentions=outputs.cross_attentions,
+ encoder_last_hidden_state=outputs.encoder_last_hidden_state,
+ encoder_hidden_states=outputs.encoder_hidden_states,
+ encoder_attentions=outputs.encoder_attentions,
+ )
+
+ def prepare_decoder_input_ids_from_labels(self, labels: torch.Tensor):
+ return shift_tokens_right(labels, self.config.pad_token_id)
+
+ def get_output_embeddings(self):
+ return self.model.decoder.embed_tokens
+
+ def set_output_embeddings(self, value):
+ self.model.decoder.embed_tokens = value
+
+
+class SinusoidalPositionalEmbedding(nn.Embedding):
+ """
+ This module produces sinusoidal positional embeddings of any length.
+
+ We don't want to save the weight of this embedding since it's not trained (deterministic) and it can be huge.
+
+ Padding symbols are ignored.
+
+ These embeddings get automatically extended in forward if more positions is needed.
+ """
+
+ def __init__(self, num_positions, embedding_dim, padding_idx):
+ super().__init__(num_positions, embedding_dim, padding_idx)
+
+ def make_weight(self, num_positions, embedding_dim, padding_idx):
+ weight = self.get_embedding(num_positions, embedding_dim, padding_idx)
+ # in forward put the weights on the correct dtype and device of the param
+ weight = weight.to(dtype=self.weight.dtype, device=self.weight.device)
+ self.weight = nn.Parameter(weight)
+ self.weight.detach_()
+ self.weight.requires_grad = False
+
+ @staticmethod
+ def get_embedding(num_embeddings, embedding_dim, padding_idx):
+ """
+ Build sinusoidal embeddings.
+
+ This matches the implementation in tensor2tensor, but differs slightly from the description in Section 3.5 of
+ "Attention Is All You Need".
+ """
+ half_dim = embedding_dim // 2
+ emb = math.log(10000) / (half_dim - 1)
+ emb = torch.exp(torch.arange(half_dim, dtype=torch.int64).float() * -emb)
+ emb = torch.arange(num_embeddings, dtype=torch.int64).float().unsqueeze(1) * emb.unsqueeze(0)
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1).view(num_embeddings, -1)
+ if embedding_dim % 2 == 1:
+ # zero pad
+ emb = torch.cat([emb, torch.zeros(num_embeddings, 1)], dim=1)
+ if padding_idx is not None:
+ emb[padding_idx, :] = 0
+ return emb
+
+ @staticmethod
+ def make_positions(tensor, padding_idx: int):
+ """
+ Replace non-padding symbols with their position numbers.
+
+ Position numbers begin at padding_idx+1. Padding symbols are ignored.
+ """
+ # The series of casts and type-conversions here are carefully
+ # balanced to both work with ONNX export and XLA. In particular XLA
+ # prefers ints, cumsum defaults to output longs, and ONNX doesn't know
+ # how to handle the dtype kwarg in cumsum.
+ mask = tensor.ne(padding_idx).int()
+ return (torch.cumsum(mask, dim=1).type_as(mask) * mask).long() + padding_idx
+
+ def forward(
+ self,
+ input,
+ incremental_state: Any | None = None,
+ timestep: Tensor | None = None,
+ ):
+ """Input is expected to be of size [bsz x seqlen]."""
+ bsz, seq_len = input.shape[:2]
+ max_pos = self.padding_idx + 1 + seq_len
+ if max_pos > self.weight.size(0):
+ # expand embeddings if needed
+ self.make_weight(max_pos, self.embedding_dim, self.padding_idx)
+ positions = self.make_positions(input, self.padding_idx)
+ return super().forward(positions)
+
+
+__all__ = ["FSMTForConditionalGeneration", "FSMTModel", "PretrainedFSMTModel"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/fsmt/tokenization_fsmt.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/fsmt/tokenization_fsmt.py
new file mode 100644
index 0000000000000000000000000000000000000000..40eeb1fb855b7352c7ad7f2bed4ea626f14aa8b8
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/fsmt/tokenization_fsmt.py
@@ -0,0 +1,486 @@
+# Copyright 2019 The Open AI Team Authors and The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Tokenization classes for FSMT."""
+
+import json
+import os
+import re
+import unicodedata
+
+from ...tokenization_python import PreTrainedTokenizer
+from ...utils import logging
+
+
+logger = logging.get_logger(__name__)
+
+VOCAB_FILES_NAMES = {
+ "src_vocab_file": "vocab-src.json",
+ "tgt_vocab_file": "vocab-tgt.json",
+ "merges_file": "merges.txt",
+}
+
+
+def get_pairs(word):
+ """
+ Return set of symbol pairs in a word. word is represented as tuple of symbols (symbols being variable-length
+ strings)
+ """
+ pairs = set()
+ prev_char = word[0]
+ for char in word[1:]:
+ pairs.add((prev_char, char))
+ prev_char = char
+ return pairs
+
+
+def replace_unicode_punct(text):
+ """
+ Port of https://github.com/moses-smt/mosesdecoder/blob/master/scripts/tokenizer/replace-unicode-punctuation.perl
+ """
+ text = text.replace(",", ",")
+ text = re.sub(r"。\s*", ". ", text)
+ text = text.replace("、", ",")
+ text = text.replace("”", '"')
+ text = text.replace("“", '"')
+ text = text.replace("∶", ":")
+ text = text.replace(":", ":")
+ text = text.replace("?", "?")
+ text = text.replace("《", '"')
+ text = text.replace("》", '"')
+ text = text.replace(")", ")")
+ text = text.replace("!", "!")
+ text = text.replace("(", "(")
+ text = text.replace(";", ";")
+ text = text.replace("1", "1")
+ text = text.replace("」", '"')
+ text = text.replace("「", '"')
+ text = text.replace("0", "0")
+ text = text.replace("3", "3")
+ text = text.replace("2", "2")
+ text = text.replace("5", "5")
+ text = text.replace("6", "6")
+ text = text.replace("9", "9")
+ text = text.replace("7", "7")
+ text = text.replace("8", "8")
+ text = text.replace("4", "4")
+ text = re.sub(r".\s*", ". ", text)
+ text = text.replace("~", "~")
+ text = text.replace("’", "'")
+ text = text.replace("…", "...")
+ text = text.replace("━", "-")
+ text = text.replace("〈", "<")
+ text = text.replace("〉", ">")
+ text = text.replace("【", "[")
+ text = text.replace("】", "]")
+ text = text.replace("%", "%")
+ return text
+
+
+def remove_non_printing_char(text):
+ """
+ Port of https://github.com/moses-smt/mosesdecoder/blob/master/scripts/tokenizer/remove-non-printing-char.perl
+ """
+ output = []
+ for char in text:
+ cat = unicodedata.category(char)
+ if cat.startswith("C"):
+ continue
+ output.append(char)
+ return "".join(output)
+
+
+# Porting notes:
+# this one is modeled after XLMTokenizer
+#
+# added:
+# - src_vocab_file,
+# - tgt_vocab_file,
+# - langs,
+
+
+class FSMTTokenizer(PreTrainedTokenizer):
+ """
+ Construct an FAIRSEQ Transformer tokenizer. Based on Byte-Pair Encoding. The tokenization process is the following:
+
+ - Moses preprocessing and tokenization.
+ - Normalizing all inputs text.
+ - The arguments `special_tokens` and the function `set_special_tokens`, can be used to add additional symbols (like
+ "__classify__") to a vocabulary.
+ - The argument `langs` defines a pair of languages.
+
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
+ this superclass for more information regarding those methods.
+
+ Args:
+ langs (`List[str]`, *optional*):
+ A list of two languages to translate from and to, for instance `["en", "ru"]`.
+ src_vocab_file (`str`, *optional*):
+ File containing the vocabulary for the source language.
+ tgt_vocab_file (`st`, *optional*):
+ File containing the vocabulary for the target language.
+ merges_file (`str`, *optional*):
+ File containing the merges.
+ do_lower_case (`bool`, *optional*, defaults to `False`):
+ Whether or not to lowercase the input when tokenizing.
+ unk_token (`str`, *optional*, defaults to `""`):
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
+ token instead.
+ bos_token (`str`, *optional*, defaults to `""`):
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
+
+
+
+ When building a sequence using special tokens, this is not the token that is used for the beginning of
+ sequence. The token used is the `cls_token`.
+
+
+
+ sep_token (`str`, *optional*, defaults to `""`):
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
+ sequence classification or for a text and a question for question answering. It is also used as the last
+ token of a sequence built with special tokens.
+ pad_token (`str`, *optional*, defaults to `""`):
+ The token used for padding, for example when batching sequences of different lengths.
+
+ """
+
+ vocab_files_names = VOCAB_FILES_NAMES
+ model_input_names = ["input_ids", "attention_mask"]
+
+ def __init__(
+ self,
+ langs=None,
+ src_vocab_file=None,
+ tgt_vocab_file=None,
+ merges_file=None,
+ do_lower_case=False,
+ unk_token="",
+ bos_token="",
+ sep_token="",
+ pad_token="",
+ **kwargs,
+ ):
+ try:
+ import sacremoses
+ except ImportError:
+ raise ImportError(
+ "You need to install sacremoses to use XLMTokenizer. "
+ "See https://pypi.org/project/sacremoses/ for installation."
+ )
+
+ self.sm = sacremoses
+
+ self.src_vocab_file = src_vocab_file
+ self.tgt_vocab_file = tgt_vocab_file
+ self.merges_file = merges_file
+ self.do_lower_case = do_lower_case
+
+ # cache of sm.MosesPunctNormalizer instance
+ self.cache_moses_punct_normalizer = {}
+ # cache of sm.MosesTokenizer instance
+ self.cache_moses_tokenizer = {}
+ self.cache_moses_detokenizer = {}
+
+ if langs and len(langs) == 2:
+ self.src_lang, self.tgt_lang = langs
+ else:
+ raise ValueError(
+ f"arg `langs` needs to be a list of 2 langs, e.g. ['en', 'ru'], but got {langs}. "
+ "Usually that means that tokenizer can't find a mapping for the given model path "
+ "in and other maps of this tokenizer."
+ )
+
+ with open(src_vocab_file, encoding="utf-8") as src_vocab_handle:
+ self.encoder = json.load(src_vocab_handle)
+ with open(tgt_vocab_file, encoding="utf-8") as tgt_vocab_handle:
+ tgt_vocab = json.load(tgt_vocab_handle)
+ self.decoder = {v: k for k, v in tgt_vocab.items()}
+ with open(merges_file, encoding="utf-8") as merges_handle:
+ merges = merges_handle.read().split("\n")[:-1]
+ merges = [tuple(merge.split()[:2]) for merge in merges]
+ self.bpe_ranks = dict(zip(merges, range(len(merges))))
+ self.cache = {}
+ super().__init__(
+ langs=langs,
+ src_vocab_file=src_vocab_file,
+ tgt_vocab_file=tgt_vocab_file,
+ merges_file=merges_file,
+ do_lower_case=do_lower_case,
+ unk_token=unk_token,
+ bos_token=bos_token,
+ sep_token=sep_token,
+ pad_token=pad_token,
+ **kwargs,
+ )
+
+ # hack override
+ def get_vocab(self) -> dict[str, int]:
+ return self.get_src_vocab()
+
+ # hack override
+ @property
+ def vocab_size(self) -> int:
+ return self.src_vocab_size
+
+ def moses_punct_norm(self, text, lang):
+ if lang not in self.cache_moses_punct_normalizer:
+ punct_normalizer = self.sm.MosesPunctNormalizer(lang=lang)
+ self.cache_moses_punct_normalizer[lang] = punct_normalizer
+ return self.cache_moses_punct_normalizer[lang].normalize(text)
+
+ def moses_tokenize(self, text, lang):
+ if lang not in self.cache_moses_tokenizer:
+ moses_tokenizer = self.sm.MosesTokenizer(lang=lang)
+ self.cache_moses_tokenizer[lang] = moses_tokenizer
+ return self.cache_moses_tokenizer[lang].tokenize(
+ text, aggressive_dash_splits=True, return_str=False, escape=True
+ )
+
+ def moses_detokenize(self, tokens, lang):
+ if lang not in self.cache_moses_detokenizer:
+ moses_detokenizer = self.sm.MosesDetokenizer(lang=lang)
+ self.cache_moses_detokenizer[lang] = moses_detokenizer
+ return self.cache_moses_detokenizer[lang].detokenize(tokens)
+
+ def moses_pipeline(self, text, lang):
+ text = replace_unicode_punct(text)
+ text = self.moses_punct_norm(text, lang)
+ text = remove_non_printing_char(text)
+ return text
+
+ @property
+ def src_vocab_size(self):
+ return len(self.encoder)
+
+ @property
+ def tgt_vocab_size(self):
+ return len(self.decoder)
+
+ def get_src_vocab(self):
+ return dict(self.encoder, **self.added_tokens_encoder)
+
+ def get_tgt_vocab(self):
+ return dict(self.decoder, **self.added_tokens_decoder)
+
+ def bpe(self, token):
+ word = tuple(token[:-1]) + (token[-1] + "",)
+ if token in self.cache:
+ return self.cache[token]
+ pairs = get_pairs(word)
+
+ if not pairs:
+ return token + ""
+
+ while True:
+ bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
+ if bigram not in self.bpe_ranks:
+ break
+ first, second = bigram
+ new_word = []
+ i = 0
+ while i < len(word):
+ try:
+ j = word.index(first, i)
+ except ValueError:
+ new_word.extend(word[i:])
+ break
+ else:
+ new_word.extend(word[i:j])
+ i = j
+
+ if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
+ new_word.append(first + second)
+ i += 2
+ else:
+ new_word.append(word[i])
+ i += 1
+ new_word = tuple(new_word)
+ word = new_word
+ if len(word) == 1:
+ break
+ else:
+ pairs = get_pairs(word)
+ word = " ".join(word)
+ if word == "\n ":
+ word = "\n"
+ self.cache[token] = word
+ return word
+
+ def _tokenize(self, text, lang="en", bypass_tokenizer=False):
+ """
+ Tokenize a string given language code using Moses.
+
+ Details of tokenization:
+
+ - [sacremoses](https://github.com/alvations/sacremoses): port of Moses
+ - Install with `pip install sacremoses`
+
+ Args:
+ - lang: ISO language code (default = 'en') (string). Languages should belong of the model supported
+ languages. However, we don't enforce it.
+ - bypass_tokenizer: Allow users to preprocess and tokenize the sentences externally (default = False)
+ (bool). If True, we only apply BPE.
+
+ Returns:
+ List of tokens.
+ """
+ # ignore `lang` which is currently isn't explicitly passed in tokenization_utils.py and always results in lang=en
+ # if lang != self.src_lang:
+ # raise ValueError(f"Expected lang={self.src_lang}, but got {lang}")
+ lang = self.src_lang
+
+ if self.do_lower_case:
+ text = text.lower()
+
+ if bypass_tokenizer:
+ text = text.split()
+ else:
+ text = self.moses_pipeline(text, lang=lang)
+ text = self.moses_tokenize(text, lang=lang)
+
+ split_tokens = []
+ for token in text:
+ if token:
+ split_tokens.extend(list(self.bpe(token).split(" ")))
+
+ return split_tokens
+
+ def _convert_token_to_id(self, token):
+ """Converts a token (str) in an id using the vocab."""
+ return self.encoder.get(token, self.encoder.get(self.unk_token))
+
+ def _convert_id_to_token(self, index):
+ """Converts an index (integer) in a token (str) using the vocab."""
+ return self.decoder.get(index, self.unk_token)
+
+ def convert_tokens_to_string(self, tokens):
+ """Converts a sequence of tokens (string) in a single string."""
+
+ # remove BPE
+ tokens = [t.replace(" ", "").replace("", " ") for t in tokens]
+ tokens = "".join(tokens).split()
+ # detokenize
+ text = self.moses_detokenize(tokens, self.tgt_lang)
+ return text
+
+ def build_inputs_with_special_tokens(
+ self, token_ids_0: list[int], token_ids_1: list[int] | None = None
+ ) -> list[int]:
+ """
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
+ adding special tokens. A FAIRSEQ Transformer sequence has the following format:
+
+ - single sequence: ` X `
+ - pair of sequences: ` A B `
+
+ Args:
+ token_ids_0 (`List[int]`):
+ List of IDs to which the special tokens will be added.
+ token_ids_1 (`List[int]`, *optional*):
+ Optional second list of IDs for sequence pairs.
+
+ Returns:
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
+ """
+ sep = [self.sep_token_id]
+
+ # no bos used in fairseq
+ if token_ids_1 is None:
+ return token_ids_0 + sep
+ return token_ids_0 + sep + token_ids_1 + sep
+
+ def get_special_tokens_mask(
+ self, token_ids_0: list[int], token_ids_1: list[int] | None = None, already_has_special_tokens: bool = False
+ ) -> list[int]:
+ """
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
+ special tokens using the tokenizer `prepare_for_model` method.
+
+ Args:
+ token_ids_0 (`List[int]`):
+ List of IDs.
+ token_ids_1 (`List[int]`, *optional*):
+ Optional second list of IDs for sequence pairs.
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
+ Whether or not the token list is already formatted with special tokens for the model.
+
+ Returns:
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
+ """
+
+ if already_has_special_tokens:
+ return super().get_special_tokens_mask(
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
+ )
+ # no bos used in fairseq
+ if token_ids_1 is not None:
+ return ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
+ return ([0] * len(token_ids_0)) + [1]
+
+ def save_vocabulary(self, save_directory: str, filename_prefix: str | None = None) -> tuple[str]:
+ if not os.path.isdir(save_directory):
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
+ return
+
+ src_vocab_file = os.path.join(
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["src_vocab_file"]
+ )
+ tgt_vocab_file = os.path.join(
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["tgt_vocab_file"]
+ )
+ merges_file = os.path.join(
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
+ )
+
+ with open(src_vocab_file, "w", encoding="utf-8") as f:
+ f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
+
+ with open(tgt_vocab_file, "w", encoding="utf-8") as f:
+ tgt_vocab = {v: k for k, v in self.decoder.items()}
+ f.write(json.dumps(tgt_vocab, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
+
+ index = 0
+ with open(merges_file, "w", encoding="utf-8") as writer:
+ for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
+ if index != token_index:
+ logger.warning(
+ f"Saving vocabulary to {merges_file}: BPE merge indices are not consecutive."
+ " Please check that the tokenizer is not corrupted!"
+ )
+ index = token_index
+ writer.write(" ".join(bpe_tokens) + "\n")
+ index += 1
+
+ return src_vocab_file, tgt_vocab_file, merges_file
+
+ def __getstate__(self):
+ state = self.__dict__.copy()
+ state["sm"] = None
+ return state
+
+ def __setstate__(self, d):
+ self.__dict__ = d
+
+ try:
+ import sacremoses
+ except ImportError:
+ raise ImportError(
+ "You need to install sacremoses to use XLMTokenizer. "
+ "See https://pypi.org/project/sacremoses/ for installation."
+ )
+
+ self.sm = sacremoses
+
+
+__all__ = ["FSMTTokenizer"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gemma/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gemma/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..80c8d30760c45526b97bfffd557a6d39b8e3e826
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gemma/__init__.py
@@ -0,0 +1,29 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_gemma import *
+ from .modeling_gemma import *
+ from .tokenization_gemma import *
+ from .tokenization_gemma_fast import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gemma/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gemma/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..347a5b898c2d19405d0af328e16ef4034296eaf9
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gemma/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gemma/__pycache__/configuration_gemma.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gemma/__pycache__/configuration_gemma.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8182b22264c81dc9b36091f09aed2623d939d693
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gemma/__pycache__/configuration_gemma.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gemma/__pycache__/modeling_gemma.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gemma/__pycache__/modeling_gemma.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5dc37b1043c7de18846d5f6272da14179d3feb7b
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gemma/__pycache__/modeling_gemma.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gemma/__pycache__/modular_gemma.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gemma/__pycache__/modular_gemma.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6e1b5a6f7fcaf33f9694addd8fb875f2485c7ae4
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gemma/__pycache__/modular_gemma.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gemma/__pycache__/tokenization_gemma.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gemma/__pycache__/tokenization_gemma.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7149cadd9f2cdecec846bf57f54451dc4c89d1e9
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gemma/__pycache__/tokenization_gemma.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gemma/configuration_gemma.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gemma/configuration_gemma.py
new file mode 100644
index 0000000000000000000000000000000000000000..0ef2e8b31b8d2d73783c7cc22fe9761f18eef36d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gemma/configuration_gemma.py
@@ -0,0 +1,86 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/gemma/modular_gemma.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_gemma.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2024 Google Inc. HuggingFace Inc. team. All rights reserved.
+#
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...modeling_rope_utils import RopeParameters
+from ...utils import auto_docstring
+
+
+@auto_docstring(checkpoint="google/gemma-7b")
+@strict
+class GemmaConfig(PreTrainedConfig):
+ r"""
+ use_bidirectional_attention (`bool`, *optional*):
+ If True, the model will attend to all text tokens instead of using a causal mask.
+
+ ```python
+ >>> from transformers import GemmaModel, GemmaConfig
+ >>> # Initializing a Gemma gemma-7b style configuration
+ >>> configuration = GemmaConfig()
+ >>> # Initializing a model from the gemma-7b style configuration
+ >>> model = GemmaModel(configuration)
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "gemma"
+ keys_to_ignore_at_inference = ["past_key_values"]
+ base_model_tp_plan = {
+ "layers.*.self_attn.q_proj": "colwise",
+ "layers.*.self_attn.k_proj": "colwise",
+ "layers.*.self_attn.v_proj": "colwise",
+ "layers.*.self_attn.o_proj": "rowwise",
+ "layers.*.mlp.gate_proj": "colwise",
+ "layers.*.mlp.up_proj": "colwise",
+ "layers.*.mlp.down_proj": "rowwise",
+ }
+ base_model_pp_plan = {
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
+ "norm": (["hidden_states"], ["hidden_states"]),
+ }
+
+ vocab_size: int = 256000
+ hidden_size: int = 3072
+ intermediate_size: int = 24576
+ num_hidden_layers: int = 28
+ num_attention_heads: int = 16
+ num_key_value_heads: int = 16
+ head_dim: int = 256
+ hidden_act: str = "gelu_pytorch_tanh"
+ max_position_embeddings: int = 8192
+ initializer_range: float = 0.02
+ rms_norm_eps: float = 1e-6
+ use_cache: bool = True
+ pad_token_id: int | None = 0
+ eos_token_id: int | list[int] | None = 1
+ bos_token_id: int | None = 2
+ tie_word_embeddings: bool = True
+ rope_parameters: RopeParameters | dict | None = None
+ attention_bias: bool = False
+ attention_dropout: float | int = 0.0
+ use_bidirectional_attention: bool | None = None
+
+
+__all__ = ["GemmaConfig"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gemma/modeling_gemma.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gemma/modeling_gemma.py
new file mode 100644
index 0000000000000000000000000000000000000000..c6c5a55b87900447b98456c3b17cb51cbc1620b7
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gemma/modeling_gemma.py
@@ -0,0 +1,538 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/gemma/modular_gemma.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_gemma.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2024 Google Inc. HuggingFace Inc. team. All rights reserved.
+#
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+from collections.abc import Callable
+from typing import Optional
+
+import torch
+from torch import nn
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...cache_utils import Cache, DynamicCache
+from ...generation import GenerationMixin
+from ...integrations import use_kernel_func_from_hub, use_kernelized_func
+from ...masking_utils import create_causal_mask
+from ...modeling_layers import (
+ GenericForSequenceClassification,
+ GenericForTokenClassification,
+ GradientCheckpointingLayer,
+)
+from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
+from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import TransformersKwargs, auto_docstring, can_return_tuple
+from ...utils.generic import maybe_autocast, merge_with_config_defaults
+from ...utils.output_capturing import capture_outputs
+from .configuration_gemma import GemmaConfig
+
+
+class GemmaTextScaledWordEmbedding(nn.Embedding):
+ """
+ This module overrides nn.Embeddings' forward by multiplying with embeddings scale.
+ """
+
+ def __init__(self, num_embeddings: int, embedding_dim: int, padding_idx: int, embed_scale: float = 1.0):
+ super().__init__(num_embeddings, embedding_dim, padding_idx)
+ self.scalar_embed_scale = embed_scale
+ self.register_buffer("embed_scale", torch.tensor(embed_scale), persistent=False)
+
+ def forward(self, input_ids: torch.Tensor):
+ return super().forward(input_ids) * self.embed_scale.to(self.weight.dtype)
+
+
+class GemmaRMSNorm(nn.Module):
+ def __init__(self, dim: int, eps: float = 1e-6):
+ super().__init__()
+ self.eps = eps
+ self.weight = nn.Parameter(torch.zeros(dim))
+
+ def _norm(self, x):
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
+
+ def forward(self, x):
+ output = self._norm(x.float())
+ # Llama does x.to(float16) * w whilst Gemma is (x * w).to(float16)
+ # See https://github.com/huggingface/transformers/pull/29402
+ output = output * (1.0 + self.weight.float())
+ return output.type_as(x)
+
+ def extra_repr(self):
+ return f"{tuple(self.weight.shape)}, eps={self.eps}"
+
+
+class GemmaMLP(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.hidden_size = config.hidden_size
+ self.intermediate_size = config.intermediate_size
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
+ self.act_fn = ACT2FN[config.hidden_act]
+
+ def forward(self, x):
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
+ return down_proj
+
+
+class GemmaRotaryEmbedding(nn.Module):
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
+
+ def __init__(self, config: GemmaConfig, device=None):
+ super().__init__()
+ self.max_seq_len_cached = config.max_position_embeddings
+ self.original_max_seq_len = config.max_position_embeddings
+
+ self.config = config
+
+ self.rope_type = self.config.rope_parameters["rope_type"]
+ rope_init_fn: Callable = self.compute_default_rope_parameters
+ if self.rope_type != "default":
+ rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
+ inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
+
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
+ self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
+
+ @staticmethod
+ def compute_default_rope_parameters(
+ config: GemmaConfig | None = None,
+ device: Optional["torch.device"] = None,
+ seq_len: int | None = None,
+ ) -> tuple["torch.Tensor", float]:
+ """
+ Computes the inverse frequencies according to the original RoPE implementation
+ Args:
+ config ([`~transformers.PreTrainedConfig`]):
+ The model configuration.
+ device (`torch.device`):
+ The device to use for initialization of the inverse frequencies.
+ seq_len (`int`, *optional*):
+ The current sequence length. Unused for this type of RoPE.
+ Returns:
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
+ """
+ base = config.rope_parameters["rope_theta"]
+ dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
+
+ attention_factor = 1.0 # Unused in this type of RoPE
+
+ # Compute the inverse frequencies
+ inv_freq = 1.0 / (
+ base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
+ )
+ return inv_freq, attention_factor
+
+ @torch.no_grad()
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
+ def forward(self, x, position_ids):
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
+ position_ids_expanded = position_ids[:, None, :].float()
+
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
+ with maybe_autocast(device_type=device_type, enabled=False): # Force float32
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
+ emb = torch.cat((freqs, freqs), dim=-1)
+ cos = emb.cos() * self.attention_scaling
+ sin = emb.sin() * self.attention_scaling
+
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
+
+
+def rotate_half(x):
+ """Rotates half the hidden dims of the input."""
+ x1 = x[..., : x.shape[-1] // 2]
+ x2 = x[..., x.shape[-1] // 2 :]
+ return torch.cat((-x2, x1), dim=-1)
+
+
+@use_kernel_func_from_hub("rotary_pos_emb")
+def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
+ """Applies Rotary Position Embedding to the query and key tensors.
+
+ Args:
+ q (`torch.Tensor`): The query tensor.
+ k (`torch.Tensor`): The key tensor.
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
+ Returns:
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
+ """
+ cos = cos.unsqueeze(unsqueeze_dim)
+ sin = sin.unsqueeze(unsqueeze_dim)
+ q_embed = (q * cos) + (rotate_half(q) * sin)
+ k_embed = (k * cos) + (rotate_half(k) * sin)
+ return q_embed, k_embed
+
+
+def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
+ """
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
+ """
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
+ if n_rep == 1:
+ return hidden_states
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
+
+
+def eager_attention_forward(
+ module: nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: torch.Tensor | None,
+ scaling: float,
+ dropout: float = 0.0,
+ **kwargs: Unpack[TransformersKwargs],
+):
+ key_states = repeat_kv(key, module.num_key_value_groups)
+ value_states = repeat_kv(value, module.num_key_value_groups)
+
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
+ if attention_mask is not None:
+ attn_weights = attn_weights + attention_mask
+
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
+ attn_output = torch.matmul(attn_weights, value_states)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+
+ return attn_output, attn_weights
+
+
+@use_kernelized_func(apply_rotary_pos_emb)
+class GemmaAttention(nn.Module):
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
+
+ def __init__(self, config: GemmaConfig, layer_idx: int):
+ super().__init__()
+ self.config = config
+ self.layer_idx = layer_idx
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
+ self.scaling = self.head_dim**-0.5
+ self.attention_dropout = config.attention_dropout
+ self.is_causal = not getattr(config, "use_bidirectional_attention", False)
+
+ self.q_proj = nn.Linear(
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
+ )
+ self.k_proj = nn.Linear(
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
+ )
+ self.v_proj = nn.Linear(
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
+ )
+ self.o_proj = nn.Linear(
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
+ )
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
+ attention_mask: torch.Tensor | None = None,
+ past_key_values: Cache | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor, torch.Tensor]:
+ input_shape = hidden_states.shape[:-1]
+ hidden_shape = (*input_shape, -1, self.head_dim)
+
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+
+ cos, sin = position_embeddings
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
+
+ if past_key_values is not None:
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_states,
+ key_states,
+ value_states,
+ attention_mask,
+ dropout=0.0 if not self.training else self.attention_dropout,
+ scaling=self.scaling,
+ **kwargs,
+ )
+
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ attn_output = self.o_proj(attn_output)
+ return attn_output, attn_weights
+
+
+class GemmaDecoderLayer(GradientCheckpointingLayer):
+ def __init__(self, config: GemmaConfig, layer_idx: int):
+ super().__init__()
+ self.hidden_size = config.hidden_size
+
+ self.self_attn = GemmaAttention(config=config, layer_idx=layer_idx)
+
+ self.mlp = GemmaMLP(config)
+ self.input_layernorm = GemmaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.post_attention_layernorm = GemmaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ use_cache: bool | None = False,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.Tensor:
+ residual = hidden_states
+ hidden_states = self.input_layernorm(hidden_states)
+ # Self Attention
+ hidden_states, _ = self.self_attn(
+ hidden_states=hidden_states,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ position_embeddings=position_embeddings,
+ **kwargs,
+ )
+ hidden_states = residual + hidden_states
+
+ # Fully Connected
+ residual = hidden_states
+ hidden_states = self.post_attention_layernorm(hidden_states)
+ hidden_states = self.mlp(hidden_states)
+ hidden_states = residual + hidden_states
+ return hidden_states
+
+
+@auto_docstring
+class GemmaPreTrainedModel(PreTrainedModel):
+ config: GemmaConfig
+ base_model_prefix = "model"
+ supports_gradient_checkpointing = True
+ _no_split_modules = ["GemmaDecoderLayer"]
+ _skip_keys_device_placement = ["past_key_values"]
+ _supports_flash_attn = True
+ _supports_sdpa = True
+ _supports_flex_attn = True
+
+ _can_compile_fullgraph = True
+ _supports_attention_backend = True
+ _can_record_outputs = {
+ "hidden_states": GemmaDecoderLayer,
+ "attentions": GemmaAttention,
+ }
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ super()._init_weights(module)
+ # We initialize with 0s to be 1 centered as the RMSNorm here does (1 + weight)
+ if "RMSNorm" in module.__class__.__name__:
+ init.zeros_(module.weight)
+ elif isinstance(module, GemmaTextScaledWordEmbedding):
+ init.constant_(module.embed_scale, module.scalar_embed_scale)
+
+
+@auto_docstring
+class GemmaModel(GemmaPreTrainedModel):
+ def __init__(self, config: GemmaConfig):
+ super().__init__(config)
+ self.padding_idx = config.pad_token_id
+ self.vocab_size = config.vocab_size
+ # Gemma3 downcasts the below to bfloat16, causing sqrt(3072)=55.4256 to become 55.5. See https://github.com/huggingface/transformers/pull/29402
+ self.embed_tokens = GemmaTextScaledWordEmbedding(
+ config.vocab_size, config.hidden_size, self.padding_idx, embed_scale=self.config.hidden_size**0.5
+ )
+ self.layers = nn.ModuleList(
+ [GemmaDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
+ )
+ self.norm = GemmaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.rotary_emb = GemmaRotaryEmbedding(config=config)
+ self.gradient_checkpointing = False
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @merge_with_config_defaults
+ @capture_outputs
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ use_cache: bool | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> BaseModelOutputWithPast:
+ if (input_ids is None) ^ (inputs_embeds is not None):
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
+
+ if inputs_embeds is None:
+ inputs_embeds = self.embed_tokens(input_ids)
+
+ if use_cache and past_key_values is None:
+ past_key_values = DynamicCache(config=self.config)
+
+ if position_ids is None:
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
+ position_ids = position_ids.unsqueeze(0)
+
+ causal_mask = create_causal_mask(
+ config=self.config,
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ position_ids=position_ids,
+ )
+
+ # embed positions
+ hidden_states = inputs_embeds
+ position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
+
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
+ hidden_states = decoder_layer(
+ hidden_states,
+ attention_mask=causal_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ position_embeddings=position_embeddings,
+ **kwargs,
+ )
+ hidden_states = self.norm(hidden_states)
+ return BaseModelOutputWithPast(
+ last_hidden_state=hidden_states,
+ past_key_values=past_key_values if use_cache else None,
+ )
+
+
+@auto_docstring
+class GemmaForCausalLM(GemmaPreTrainedModel, GenerationMixin):
+ _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
+ _tp_plan = {"lm_head": "colwise_gather_output"}
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
+
+ def __init__(self, config):
+ super().__init__(config)
+ self.model = GemmaModel(config)
+ self.vocab_size = config.vocab_size
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ use_cache: bool | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> CausalLMOutputWithPast:
+ r"""
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, GemmaForCausalLM
+
+ >>> model = GemmaForCausalLM.from_pretrained("google/gemma-7b")
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/gemma-7b")
+
+ >>> prompt = "What is your favorite condiment?"
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
+
+ >>> # Generate
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
+ "What is your favorite condiment?"
+ ```"""
+ outputs: BaseModelOutputWithPast = self.model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ **kwargs,
+ )
+
+ hidden_states = outputs.last_hidden_state
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
+
+ return CausalLMOutputWithPast(
+ loss=loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+class GemmaForSequenceClassification(GenericForSequenceClassification, GemmaPreTrainedModel):
+ pass
+
+
+class GemmaForTokenClassification(GenericForTokenClassification, GemmaPreTrainedModel):
+ pass
+
+
+__all__ = [
+ "GemmaModel",
+ "GemmaForCausalLM",
+ "GemmaForSequenceClassification",
+ "GemmaForTokenClassification",
+ "GemmaPreTrainedModel",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gemma/modular_gemma.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gemma/modular_gemma.py
new file mode 100644
index 0000000000000000000000000000000000000000..25f436473fbef06a4015ac29a0f0d7e95b59669d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gemma/modular_gemma.py
@@ -0,0 +1,268 @@
+# Copyright 2024 Google Inc. HuggingFace Inc. team. All rights reserved.
+#
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+import torch
+from huggingface_hub.dataclasses import strict
+from torch import nn
+
+from ... import initialization as init
+from ...cache_utils import Cache, DynamicCache
+from ...configuration_utils import PreTrainedConfig
+from ...masking_utils import create_causal_mask
+from ...modeling_outputs import BaseModelOutputWithPast
+from ...modeling_rope_utils import RopeParameters
+from ...modeling_utils import PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import TransformersKwargs, auto_docstring, logging
+from ..llama.modeling_llama import (
+ LlamaAttention,
+ LlamaForCausalLM,
+ LlamaForSequenceClassification,
+ LlamaForTokenClassification,
+ LlamaMLP,
+ LlamaModel,
+ LlamaPreTrainedModel,
+ LlamaRotaryEmbedding,
+)
+
+
+VOCAB_FILES_NAMES = {"vocab_file": "tokenizer.model"}
+
+SPIECE_UNDERLINE = "▁"
+
+logger = logging.get_logger(__name__)
+
+
+@auto_docstring(checkpoint="google/gemma-7b")
+@strict
+class GemmaConfig(PreTrainedConfig):
+ r"""
+ use_bidirectional_attention (`bool`, *optional*):
+ If True, the model will attend to all text tokens instead of using a causal mask.
+
+ ```python
+ >>> from transformers import GemmaModel, GemmaConfig
+ >>> # Initializing a Gemma gemma-7b style configuration
+ >>> configuration = GemmaConfig()
+ >>> # Initializing a model from the gemma-7b style configuration
+ >>> model = GemmaModel(configuration)
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "gemma"
+ keys_to_ignore_at_inference = ["past_key_values"]
+ base_model_tp_plan = {
+ "layers.*.self_attn.q_proj": "colwise",
+ "layers.*.self_attn.k_proj": "colwise",
+ "layers.*.self_attn.v_proj": "colwise",
+ "layers.*.self_attn.o_proj": "rowwise",
+ "layers.*.mlp.gate_proj": "colwise",
+ "layers.*.mlp.up_proj": "colwise",
+ "layers.*.mlp.down_proj": "rowwise",
+ }
+ base_model_pp_plan = {
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
+ "norm": (["hidden_states"], ["hidden_states"]),
+ }
+
+ vocab_size: int = 256000
+ hidden_size: int = 3072
+ intermediate_size: int = 24576
+ num_hidden_layers: int = 28
+ num_attention_heads: int = 16
+ num_key_value_heads: int = 16
+ head_dim: int = 256
+ hidden_act: str = "gelu_pytorch_tanh"
+ max_position_embeddings: int = 8192
+ initializer_range: float = 0.02
+ rms_norm_eps: float = 1e-6
+ use_cache: bool = True
+ pad_token_id: int | None = 0
+ eos_token_id: int | list[int] | None = 1
+ bos_token_id: int | None = 2
+ tie_word_embeddings: bool = True
+ rope_parameters: RopeParameters | dict | None = None
+ attention_bias: bool = False
+ attention_dropout: float | int = 0.0
+ use_bidirectional_attention: bool | None = None
+
+
+class GemmaTextScaledWordEmbedding(nn.Embedding):
+ """
+ This module overrides nn.Embeddings' forward by multiplying with embeddings scale.
+ """
+
+ def __init__(self, num_embeddings: int, embedding_dim: int, padding_idx: int, embed_scale: float = 1.0):
+ super().__init__(num_embeddings, embedding_dim, padding_idx)
+ self.scalar_embed_scale = embed_scale
+ self.register_buffer("embed_scale", torch.tensor(embed_scale), persistent=False)
+
+ def forward(self, input_ids: torch.Tensor):
+ return super().forward(input_ids) * self.embed_scale.to(self.weight.dtype)
+
+
+class GemmaRMSNorm(nn.Module):
+ def __init__(self, dim: int, eps: float = 1e-6):
+ super().__init__()
+ self.eps = eps
+ self.weight = nn.Parameter(torch.zeros(dim))
+
+ def _norm(self, x):
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
+
+ def forward(self, x):
+ output = self._norm(x.float())
+ # Llama does x.to(float16) * w whilst Gemma is (x * w).to(float16)
+ # See https://github.com/huggingface/transformers/pull/29402
+ output = output * (1.0 + self.weight.float())
+ return output.type_as(x)
+
+ def extra_repr(self):
+ return f"{tuple(self.weight.shape)}, eps={self.eps}"
+
+
+class GemmaMLP(LlamaMLP):
+ def __init__(self, config):
+ super().__init__(config)
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
+
+
+class GemmaRotaryEmbedding(LlamaRotaryEmbedding):
+ pass
+
+
+class GemmaAttention(LlamaAttention):
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
+
+ def __init__(self, config: GemmaConfig, layer_idx: int):
+ super().__init__()
+ self.is_causal = not getattr(config, "use_bidirectional_attention", False)
+
+
+class GemmaPreTrainedModel(LlamaPreTrainedModel):
+ @torch.no_grad()
+ def _init_weights(self, module):
+ PreTrainedModel._init_weights(self, module)
+ # We initialize with 0s to be 1 centered as the RMSNorm here does (1 + weight)
+ if "RMSNorm" in module.__class__.__name__:
+ init.zeros_(module.weight)
+ elif isinstance(module, GemmaTextScaledWordEmbedding):
+ init.constant_(module.embed_scale, module.scalar_embed_scale)
+
+
+class GemmaModel(LlamaModel):
+ def __init__(self, config: GemmaConfig):
+ super().__init__(config)
+ # Gemma3 downcasts the below to bfloat16, causing sqrt(3072)=55.4256 to become 55.5. See https://github.com/huggingface/transformers/pull/29402
+ self.embed_tokens = GemmaTextScaledWordEmbedding(
+ config.vocab_size, config.hidden_size, self.padding_idx, embed_scale=self.config.hidden_size**0.5
+ )
+
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ use_cache: bool | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> BaseModelOutputWithPast:
+ if (input_ids is None) ^ (inputs_embeds is not None):
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
+
+ if inputs_embeds is None:
+ inputs_embeds = self.embed_tokens(input_ids)
+
+ if use_cache and past_key_values is None:
+ past_key_values = DynamicCache(config=self.config)
+
+ if position_ids is None:
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
+ position_ids = position_ids.unsqueeze(0)
+
+ causal_mask = create_causal_mask(
+ config=self.config,
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ position_ids=position_ids,
+ )
+
+ # embed positions
+ hidden_states = inputs_embeds
+ position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
+
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
+ hidden_states = decoder_layer(
+ hidden_states,
+ attention_mask=causal_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ position_embeddings=position_embeddings,
+ **kwargs,
+ )
+ hidden_states = self.norm(hidden_states)
+ return BaseModelOutputWithPast(
+ last_hidden_state=hidden_states,
+ past_key_values=past_key_values if use_cache else None,
+ )
+
+
+class GemmaForCausalLM(LlamaForCausalLM):
+ def forward(**super_kwargs):
+ r"""
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, GemmaForCausalLM
+
+ >>> model = GemmaForCausalLM.from_pretrained("google/gemma-7b")
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/gemma-7b")
+
+ >>> prompt = "What is your favorite condiment?"
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
+
+ >>> # Generate
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
+ "What is your favorite condiment?"
+ ```"""
+ return super().forward(**super_kwargs)
+
+
+class GemmaForSequenceClassification(LlamaForSequenceClassification):
+ pass
+
+
+class GemmaForTokenClassification(LlamaForTokenClassification):
+ pass
+
+
+__all__ = [
+ "GemmaConfig",
+ "GemmaModel",
+ "GemmaForCausalLM",
+ "GemmaForSequenceClassification",
+ "GemmaForTokenClassification",
+ "GemmaPreTrainedModel",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gemma/tokenization_gemma.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gemma/tokenization_gemma.py
new file mode 100644
index 0000000000000000000000000000000000000000..85f0a74bb4c8db81defb4af2f53dc826773ff531
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gemma/tokenization_gemma.py
@@ -0,0 +1,109 @@
+# Copyright 2024 The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from tokenizers import Tokenizer, decoders, normalizers, pre_tokenizers
+from tokenizers.models import BPE
+
+from ...tokenization_utils_tokenizers import TokenizersBackend
+from ...utils import logging
+
+
+logger = logging.get_logger(__name__)
+VOCAB_FILES_NAMES = {"tokenizer_file": "tokenizer.json"}
+
+
+class GemmaTokenizer(TokenizersBackend):
+ """
+ Construct a fast Gemma tokenizer (backed by HuggingFace's tokenizers library).
+
+ This tokenizer uses a BPE model with byte fallback, no prefix space, and a normalizer that replaces
+ spaces with "▁".
+
+ Args:
+ tokenizer_file (`str`, optional):
+ A tokenizers JSON file containing the serialization of a tokenizer.
+ unk_token (`str`, optional, defaults to ""):
+ The unknown token.
+ bos_token (`str`, optional, defaults to ""):
+ The beginning of sequence token.
+ eos_token (`str`, optional, defaults to ""):
+ The end of sequence token.
+ pad_token (`str`, optional, defaults to ""):
+ The padding token.
+ mask_token (`str`, optional, defaults to ""):
+ The mask token.
+ add_bos_token (`bool`, optional, defaults to True):
+ Whether or not to add a `bos_token` at the start of sequences.
+ add_eos_token (`bool`, optional, defaults to False):
+ Whether or not to add an `eos_token` at the end of sequences.
+ vocab (`str` or `dict[str, int]`, optional):
+ Custom vocabulary dict. If not provided, a minimal vocabulary is created using the special tokens.
+ """
+
+ vocab_files_names = VOCAB_FILES_NAMES
+ padding_side = "left"
+ model_input_names = ["input_ids", "attention_mask"]
+ model = BPE
+
+ def __init__(
+ self,
+ vocab: str | dict[str, int] | None = None,
+ merges: str | list[str] | None = None,
+ unk_token: str = "",
+ bos_token: str = "",
+ eos_token: str = "",
+ pad_token: str = "",
+ mask_token: str = "",
+ **kwargs,
+ ):
+ if vocab is None:
+ vocab = {
+ str(pad_token): 0,
+ str(eos_token): 1,
+ str(bos_token): 2,
+ str(unk_token): 3,
+ str(mask_token): 4,
+ }
+ self._vocab = vocab
+ self._merges = merges or []
+
+ self._tokenizer = Tokenizer(
+ BPE(
+ vocab=self._vocab,
+ merges=self._merges,
+ fuse_unk=True,
+ unk_token=str(unk_token),
+ dropout=None,
+ byte_fallback=True,
+ )
+ )
+ self._tokenizer.pre_tokenizer = pre_tokenizers.Split(
+ pattern=" ", behavior="merged_with_previous", invert=False
+ )
+
+ self._tokenizer.decoder = decoders.Sequence(
+ [decoders.Replace("▁", " "), decoders.ByteFallback(), decoders.Fuse()]
+ )
+ self._tokenizer.normalizer = normalizers.Replace(" ", "▁")
+ super().__init__(
+ unk_token=unk_token,
+ bos_token=bos_token,
+ eos_token=eos_token,
+ pad_token=pad_token,
+ mask_token=mask_token,
+ **kwargs,
+ )
+
+
+__all__ = ["GemmaTokenizer"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gemma4_assistant/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gemma4_assistant/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..4fc85ae660aeab2f3f1f4b368986af657a298fe7
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gemma4_assistant/__init__.py
@@ -0,0 +1,28 @@
+# Copyright 2026 the HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_gemma4_assistant import *
+ from .modeling_gemma4_assistant import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gemma4_assistant/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gemma4_assistant/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6f121aa56b966aa9e6da3e45a4b4e59074d63a69
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gemma4_assistant/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gemma4_assistant/__pycache__/configuration_gemma4_assistant.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gemma4_assistant/__pycache__/configuration_gemma4_assistant.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ae8083ae5ebb1c987f83974650b12a6124c7c7d1
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gemma4_assistant/__pycache__/configuration_gemma4_assistant.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gemma4_assistant/__pycache__/modeling_gemma4_assistant.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gemma4_assistant/__pycache__/modeling_gemma4_assistant.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2d83317d3a3636e890d4852bc813f22873a19192
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gemma4_assistant/__pycache__/modeling_gemma4_assistant.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gemma4_assistant/configuration_gemma4_assistant.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gemma4_assistant/configuration_gemma4_assistant.py
new file mode 100644
index 0000000000000000000000000000000000000000..6b15ac963610866d106da3657af107a70ca57692
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gemma4_assistant/configuration_gemma4_assistant.py
@@ -0,0 +1,109 @@
+# Copyright 2026 the HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from typing import Any
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring, logging
+from ..gemma4.configuration_gemma4 import Gemma4TextConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+@auto_docstring(checkpoint="google/gemma-4-e2b-it")
+@strict
+class Gemma4AssistantConfig(PreTrainedConfig):
+ r"""
+ backbone_hidden_size (`int`, defaults to 1536):
+ Hidden size of the target model this assistant was trained with.
+ use_ordered_embeddings (`bool`, defaults to False):
+ If True, uses an embedding table ordered for optimal assistant model performance that needs to be re-ordered to
+ align with the main model.
+ num_centroids (`int`, defaults to 2048):
+ The total numer of centroids.
+ centroid_intermediate_top_k (`int`, defaults to 32):
+ The number of active centroids.
+
+ Example:
+
+ ```python
+ >>> from transformers import (
+ >>> Gemma4AssistantConfig,
+ >>> Gemma4AssistantForCausalLM,
+ >>> Gemma4TextConfig,
+ >>> )
+
+ >>> # Initializing a Gemma 4 Text config similar to google/gemma-4-e2b-it-assistant.
+ >>> text_config = Gemma4TextConfig(...)
+
+ >>> # Initializing a Gemma 4 Assistant config similar to google/gemma-4-e2b-it-assistant.
+ >>> configuration = Gemma4AssistantConfig(text_config)
+
+ >>> # Initializing a model from the google/gemma-4-e2b-it-assistant configuration.
+ >>> model = Gemma4AssistantForCausalLM(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "gemma4_assistant"
+ sub_configs = {
+ "text_config": Gemma4TextConfig,
+ }
+
+ text_config: Gemma4TextConfig | dict[str, Any] | None = None
+
+ backbone_hidden_size: int = 1536
+ use_ordered_embeddings: bool = False
+ num_centroids: int = 2048
+ centroid_intermediate_top_k: int = 32
+ tie_word_embeddings: bool = True
+
+ def __post_init__(self, **kwargs):
+ if isinstance(self.text_config, dict):
+ self.text_config = Gemma4TextConfig(**self.text_config)
+
+ # Assistant reuses the shared kvs across all layers to skip their calculation
+ # I.e. it acts as cache shared across the layers
+ if self.text_config is not None and not self.text_config.num_kv_shared_layers:
+ self.text_config.num_kv_shared_layers = self.text_config.num_hidden_layers
+
+ super().__post_init__(**kwargs)
+
+ def validate_architecture(self):
+ text_config: Gemma4TextConfig | None = self.text_config
+
+ if text_config is not None:
+ if text_config.hidden_size_per_layer_input != 0:
+ raise ValueError(
+ f"hidden_size_per_layer_input must be 0, got {text_config.hidden_size_per_layer_input}"
+ )
+ if text_config.enable_moe_block is not False:
+ raise ValueError(f"enable_moe_block must be False, got {text_config.enable_moe_block}")
+ if text_config.use_double_wide_mlp is not False:
+ raise ValueError(f"use_double_wide_mlp must be False, got {text_config.use_double_wide_mlp}")
+ if text_config.vocab_size_per_layer_input != 0:
+ raise ValueError(f"vocab_size_per_layer_input must be 0, got {text_config.vocab_size_per_layer_input}")
+ if text_config.num_kv_shared_layers != text_config.num_hidden_layers:
+ raise ValueError(
+ "All layers in a Gemma 4 Assistant models must be shared."
+ f" Expected {text_config.num_hidden_layers}. Got {text_config.num_kv_shared_layers}"
+ )
+ return super().validate_architecture()
+
+
+__all__ = ["Gemma4AssistantConfig"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gemma4_assistant/modeling_gemma4_assistant.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gemma4_assistant/modeling_gemma4_assistant.py
new file mode 100644
index 0000000000000000000000000000000000000000..8b7b6b1a8b67d6fbf900446396109f6a7db1d980
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gemma4_assistant/modeling_gemma4_assistant.py
@@ -0,0 +1,241 @@
+# Copyright 2026 the HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from dataclasses import dataclass
+
+import torch
+import torch.nn as nn
+
+from ... import initialization as init
+from ...generation import GenerationMixin
+from ...masking_utils import create_bidirectional_mask, create_bidirectional_sliding_window_mask
+from ...modeling_outputs import BaseModelOutput, BaseModelOutputWithPast
+from ...modeling_utils import PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import TransformersKwargs, auto_docstring, can_return_tuple
+from ..auto.modeling_auto import AutoModel
+from .configuration_gemma4_assistant import Gemma4AssistantConfig
+
+
+@auto_docstring
+@dataclass
+class Gemma4AssistantOutput(BaseModelOutput):
+ r"""
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
+ """
+
+ logits: torch.FloatTensor | None = None
+
+
+class Gemma4AssistantMaskedEmbedder(nn.Module):
+ token_ordering: torch.Tensor
+
+ def __init__(self, config: Gemma4AssistantConfig):
+ super().__init__()
+ text_config = config.get_text_config()
+ self.config = config
+ self.centroid_intermediate_top_k = self.config.centroid_intermediate_top_k
+ self.hidden_size = text_config.hidden_size
+ self.num_centroids = self.config.num_centroids
+ self.vocab_size = text_config.vocab_size
+ self.vocab_size_per_centroid = self.vocab_size // self.num_centroids
+
+ self.centroids = nn.Linear(self.hidden_size, self.num_centroids, bias=False)
+ self.register_buffer("token_ordering", torch.empty(self.vocab_size, dtype=torch.long))
+
+ def forward(self, hidden_states: torch.Tensor, lm_head_weight: torch.Tensor) -> torch.Tensor:
+ batch, seq_len = hidden_states.shape[:2]
+ centroid_logits = self.centroids(hidden_states)
+
+ _, top_k_indices = torch.topk(centroid_logits, k=self.centroid_intermediate_top_k, dim=-1)
+ token_ordering = self.token_ordering.long()
+ canonical_positions_per_cluster = token_ordering.view(self.num_centroids, self.vocab_size_per_centroid)
+
+ # For selected top-K clusters, get canonical positions
+ selected_canonical = canonical_positions_per_cluster[top_k_indices] # [B, L, top_k, K]
+
+ # Gather embeddings from lm_head at these canonical positions
+ selected_flat = selected_canonical.reshape(-1) # [B*L*top_k*K]
+ selected_embeddings = lm_head_weight[selected_flat].view(
+ batch, seq_len, self.centroid_intermediate_top_k * self.vocab_size_per_centroid, self.hidden_size
+ )
+
+ # Compute dot products: [B, L, 1, D] @ [B, L, D, top_k*K] -> [B, L, top_k*K]
+ selected_logits = (hidden_states.unsqueeze(-2) @ selected_embeddings.transpose(-1, -2)).squeeze(-2)
+ mask_value = selected_logits.min().item() - 1.0
+
+ # Scatter logits directly to canonical positions in the output
+ output = torch.full(
+ (batch, seq_len, self.vocab_size),
+ fill_value=mask_value,
+ dtype=hidden_states.dtype,
+ device=hidden_states.device,
+ )
+ scatter_idx = selected_canonical.view(batch, seq_len, -1) # [B, L, top_k*K]
+ return output.scatter_(dim=-1, index=scatter_idx, src=selected_logits)
+
+
+class Gemma4AssistantPreTrainedModel(PreTrainedModel):
+ config: Gemma4AssistantConfig
+ base_model_prefix = "model"
+ supports_gradient_checkpointing = True
+ _skip_keys_device_placement = ["shared_kv_states"]
+ _supports_flash_attn = True
+ _supports_sdpa = True
+
+ _can_compile_fullgraph = True
+ _supports_attention_backend = True
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ super()._init_weights(module)
+
+ if isinstance(module, Gemma4AssistantMaskedEmbedder):
+ init.zeros_(module.token_ordering)
+
+
+@auto_docstring(custom_intro="A model for mutli-token prediction-based assisted decoding with Gemma 4.")
+class Gemma4AssistantForCausalLM(Gemma4AssistantPreTrainedModel, GenerationMixin):
+ _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
+ _tp_plan = {"lm_head": "colwise_gather_output"}
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
+
+ def __init__(self, config: Gemma4AssistantConfig):
+ super().__init__(config)
+ text_config = config.get_text_config()
+
+ self.vocab_size = text_config.vocab_size
+ self.hidden_size = text_config.hidden_size
+ self.backbone_hidden_size = config.backbone_hidden_size
+
+ self.model = AutoModel.from_config(text_config)
+ self.lm_head = nn.Linear(self.hidden_size, self.vocab_size, bias=False)
+ self.pre_projection = nn.Linear(2 * self.backbone_hidden_size, self.hidden_size, bias=False)
+ self.post_projection = nn.Linear(self.hidden_size, self.backbone_hidden_size, bias=False)
+
+ self.masked_embedding = Gemma4AssistantMaskedEmbedder(config) if self.config.use_ordered_embeddings else None
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None, # Not actually used, only kept in signature to be ignored
+ inputs_embeds: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ attention_mask: dict[str, torch.Tensor] | None = None,
+ shared_kv_states: dict[str, tuple[torch.Tensor, torch.Tensor]] | None = None,
+ use_cache: bool | None = None, # Not actually used, only kept in signature to be ignored
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor, torch.Tensor]:
+ r"""
+ shared_kv_states (`dict[str, torch.Tensor` of shape `(batch_size, 1, q_len, kv_len)`, *optional*):
+ A dictionary containing the computed KV values for the last layer of each `layer_type` in this model.
+
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, Gemma4AssistantForCausalLM, Gemma4ForCausalLM
+
+ >>> model = Gemma4ForCausalLM.from_pretrained("google/gemma-4-e2b-it")
+ >>> assistant_model = Gemma4AssistantForCausalLM.from_pretrained("google/gemma-4-e2b-it-assistant")
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/gemma-4-e2b-it")
+
+ >>> prompt = "What is your favorite condiment?"
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
+
+ >>> # Generate
+ >>> generate_ids = model.generate(inputs.input_ids, assistant_model=assistant_model, max_length=30)
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True)[0]
+ "What is your favorite condiment?"
+ ```"""
+ if inputs_embeds is None or shared_kv_states is None:
+ raise ValueError("inputs_embeds and shared_kv_states cannot be None.")
+
+ inputs_embeds = self.pre_projection(inputs_embeds)
+ bidirectional_masks = self.create_attention_masks(inputs_embeds, attention_mask, shared_kv_states)
+
+ outputs: BaseModelOutputWithPast = self.model(
+ input_ids=None,
+ inputs_embeds=inputs_embeds,
+ attention_mask=bidirectional_masks,
+ position_ids=position_ids,
+ shared_kv_states=shared_kv_states,
+ use_cache=False,
+ **kwargs,
+ )
+
+ last_hidden_state = outputs.last_hidden_state
+ projected_state = self.post_projection(last_hidden_state)
+
+ if self.config.use_ordered_embeddings:
+ logits = self.masked_embedding(last_hidden_state, self.lm_head.weight)
+ else:
+ logits = self.lm_head(last_hidden_state)
+
+ return Gemma4AssistantOutput(
+ last_hidden_state=projected_state,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+ def create_attention_masks(self, inputs_embeds, attention_mask, shared_kv_states):
+ """
+ Prepare the attention masks for the assisted model; the `shared_kv_states` acts as past cache in this instance.
+
+ We use bidirectional masks to account for causality
+ - There is no difference for the edge case of `q_len == 1` as it acts as full attention no matter what
+ - SWA interprets the window as forward-looking (future) when `q_idx=1` and `kv>=1`
+ - We switch from a future to a past perspective by flipping on the kv axis
+ - To account for position invariant padding, we also flip the base attention mask before initial creation
+ """
+ config = self.config.get_text_config()
+ # (bsz, num_heads, seq_len, head_dim) -> (bsz, seq_len, head_dim)
+ encoder_states_full_attn = shared_kv_states["full_attention"][0][:, 0]
+ encoder_states_swa_attn = shared_kv_states["sliding_attention"][0][:, 0]
+
+ sliding_attention_mask = attention_mask
+ if attention_mask is not None:
+ # Adjust for full mask --> cut mask only for valid kv states
+ attention_mask = attention_mask[:, : encoder_states_full_attn.shape[1]]
+
+ # 1. Take the last x entries to account for any potential SWA cutoff (from the main model)
+ # 2. Flip the mask here to stay position invariant (along the original kv); see the flip at the end
+ sliding_attention_mask = attention_mask[:, -encoder_states_swa_attn.shape[1] :].flip(dims=(1,))
+
+ full_attention_mask = create_bidirectional_mask(
+ config=config,
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ encoder_hidden_states=encoder_states_full_attn,
+ )
+ swa_mask = create_bidirectional_sliding_window_mask(
+ config=config,
+ inputs_embeds=inputs_embeds,
+ attention_mask=sliding_attention_mask,
+ encoder_hidden_states=encoder_states_swa_attn,
+ )
+
+ if swa_mask is not None:
+ # Reverse the future token perspective to a past tokens perspective by flipping the construct (kv == -1)
+ swa_mask = swa_mask.flip(dims=(-1,))
+
+ return {"full_attention": full_attention_mask, "sliding_attention": swa_mask}
+
+
+__all__ = ["Gemma4AssistantPreTrainedModel", "Gemma4AssistantForCausalLM"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..0636c800beea6b02d16d13098bd7b13f11baf468
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm/__init__.py
@@ -0,0 +1,27 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_glm import *
+ from .modeling_glm import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..59ea83bfe7524f909924c13773271b6db8abdec3
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm/__pycache__/configuration_glm.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm/__pycache__/configuration_glm.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b1b1a406b58e693d0972bef203a4c49471040afe
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm/__pycache__/configuration_glm.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm/__pycache__/modeling_glm.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm/__pycache__/modeling_glm.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d78860f7117658f2d61829469ac2b3313b197599
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm/__pycache__/modeling_glm.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm/__pycache__/modular_glm.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm/__pycache__/modular_glm.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a6f74e9a747eca93e03bd294ba5b167e4ace0584
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm/__pycache__/modular_glm.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm/configuration_glm.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm/configuration_glm.py
new file mode 100644
index 0000000000000000000000000000000000000000..98525012a23beed36b02561d97fed8ccc3600563
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm/configuration_glm.py
@@ -0,0 +1,83 @@
+# Copyright 2024 The GLM & ZhipuAI team and HuggingFace Inc. team. All rights reserved.
+#
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...modeling_rope_utils import RopeParameters
+from ...utils import auto_docstring
+
+
+@auto_docstring(checkpoint="THUDM/glm-4-9b-chat")
+@strict
+class GlmConfig(PreTrainedConfig):
+ r"""
+ Example:
+
+ ```python
+ >>> from transformers import GlmModel, GlmConfig
+ >>> # Initializing a Glm glm-4-9b-chat style configuration
+ >>> configuration = GlmConfig()
+ >>> # Initializing a model from the glm-4-9b-chat style configuration
+ >>> model = GlmModel(configuration)
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "glm"
+ keys_to_ignore_at_inference = ["past_key_values"]
+ base_model_tp_plan = {
+ "layers.*.self_attn.q_proj": "colwise",
+ "layers.*.self_attn.k_proj": "colwise",
+ "layers.*.self_attn.v_proj": "colwise",
+ "layers.*.self_attn.o_proj": "rowwise",
+ "layers.*.mlp.gate_up_proj": "colwise_gather_output", # we need to replicate here due to the `chunk` operation
+ "layers.*.mlp.down_proj": "rowwise_split_input", # input is replicated due to the `chunk` operation
+ }
+ base_model_pp_plan = {
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
+ "norm": (["hidden_states"], ["hidden_states"]),
+ }
+
+ vocab_size: int = 151552
+ hidden_size: int = 4096
+ intermediate_size: int = 13696
+ num_hidden_layers: int = 40
+ num_attention_heads: int = 32
+ num_key_value_heads: int | None = 2
+ head_dim: int | None = 128
+ hidden_act: str = "silu"
+ attention_dropout: float | int | None = 0.0
+ max_position_embeddings: int = 131072
+ initializer_range: float = 0.02
+ rms_norm_eps: float = 0.00000015625
+ use_cache: bool = True
+ tie_word_embeddings: bool = False
+ rope_parameters: RopeParameters | dict | None = None
+ pad_token_id: int | None = 151329
+ eos_token_id: int | list[int] | None = None
+ bos_token_id: int | None = None
+ attention_bias: bool = True
+
+ def __post_init__(self, **kwargs):
+ kwargs.setdefault("partial_rotary_factor", 0.5) # assign default for BC
+ if self.eos_token_id is None:
+ self.eos_token_id = [151329, 151336, 151338]
+ super().__post_init__(**kwargs)
+
+
+__all__ = ["GlmConfig"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm/modeling_glm.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm/modeling_glm.py
new file mode 100644
index 0000000000000000000000000000000000000000..712202580943634dc1250e15db321681aaffff35
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm/modeling_glm.py
@@ -0,0 +1,527 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/glm/modular_glm.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_glm.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2024 The GLM & ZhipuAI team and HuggingFace Inc. team. All rights reserved.
+#
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from collections.abc import Callable
+from typing import Optional
+
+import torch
+import torch.nn as nn
+
+from ...activations import ACT2FN
+from ...cache_utils import Cache, DynamicCache
+from ...generation import GenerationMixin
+from ...integrations import use_kernel_forward_from_hub, use_kernelized_func
+from ...masking_utils import create_causal_mask
+from ...modeling_layers import (
+ GenericForSequenceClassification,
+ GenericForTokenClassification,
+ GradientCheckpointingLayer,
+)
+from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
+from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import TransformersKwargs, auto_docstring, can_return_tuple
+from ...utils.generic import maybe_autocast, merge_with_config_defaults
+from ...utils.output_capturing import capture_outputs
+from .configuration_glm import GlmConfig
+
+
+class GlmMLP(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+
+ self.config = config
+ self.gate_up_proj = nn.Linear(config.hidden_size, 2 * config.intermediate_size, bias=False)
+ self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
+ self.activation_fn = ACT2FN[config.hidden_act]
+
+ def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
+ up_states = self.gate_up_proj(hidden_states)
+
+ gate, up_states = up_states.chunk(2, dim=-1)
+ up_states = up_states * self.activation_fn(gate)
+
+ return self.down_proj(up_states)
+
+
+class GlmRotaryEmbedding(nn.Module):
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
+
+ def __init__(self, config: GlmConfig, device=None):
+ super().__init__()
+ self.max_seq_len_cached = config.max_position_embeddings
+ self.original_max_seq_len = config.max_position_embeddings
+
+ self.config = config
+
+ self.rope_type = self.config.rope_parameters["rope_type"]
+ rope_init_fn: Callable = self.compute_default_rope_parameters
+ if self.rope_type != "default":
+ rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
+ inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
+
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
+ self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
+
+ @staticmethod
+ def compute_default_rope_parameters(
+ config: GlmConfig | None = None,
+ device: Optional["torch.device"] = None,
+ seq_len: int | None = None,
+ ) -> tuple["torch.Tensor", float]:
+ """
+ Computes the inverse frequencies according to the original RoPE implementation
+ Args:
+ config ([`~transformers.PreTrainedConfig`]):
+ The model configuration.
+ device (`torch.device`):
+ The device to use for initialization of the inverse frequencies.
+ seq_len (`int`, *optional*):
+ The current sequence length. Unused for this type of RoPE.
+ Returns:
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
+ """
+ base = config.rope_parameters["rope_theta"]
+ partial_rotary_factor = config.rope_parameters.get("partial_rotary_factor", 1.0)
+ head_dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
+ dim = int(head_dim * partial_rotary_factor)
+
+ attention_factor = 1.0 # Unused in this type of RoPE
+
+ # Compute the inverse frequencies
+ inv_freq = 1.0 / (
+ base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
+ )
+ return inv_freq, attention_factor
+
+ @torch.no_grad()
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
+ def forward(self, x, position_ids):
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
+ position_ids_expanded = position_ids[:, None, :].float()
+
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
+ with maybe_autocast(device_type=device_type, enabled=False): # Force float32
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
+ emb = torch.cat((freqs, freqs), dim=-1)
+ cos = emb.cos() * self.attention_scaling
+ sin = emb.sin() * self.attention_scaling
+
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
+
+
+def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
+ """
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
+ """
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
+ if n_rep == 1:
+ return hidden_states
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
+
+
+def eager_attention_forward(
+ module: nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: torch.Tensor | None,
+ scaling: float,
+ dropout: float = 0.0,
+ **kwargs: Unpack[TransformersKwargs],
+):
+ key_states = repeat_kv(key, module.num_key_value_groups)
+ value_states = repeat_kv(value, module.num_key_value_groups)
+
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
+ if attention_mask is not None:
+ attn_weights = attn_weights + attention_mask
+
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
+ attn_output = torch.matmul(attn_weights, value_states)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+
+ return attn_output, attn_weights
+
+
+def rotate_half(x):
+ """Rotates half the hidden dims of the input."""
+ x1 = x[..., 0::2]
+ x2 = x[..., 1::2]
+ return torch.stack((-x2, x1), dim=-1).flatten(-2)
+
+
+def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
+ """Applies Rotary Position Embedding to the query and key tensors.
+
+ Args:
+ q (`torch.Tensor`): The query tensor.
+ k (`torch.Tensor`): The key tensor.
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
+ Returns:
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
+ """
+ cos = cos.unsqueeze(unsqueeze_dim)
+ sin = sin.unsqueeze(unsqueeze_dim)
+
+ # Interleave them instead of usual shape
+ cos = cos[..., : cos.shape[-1] // 2].repeat_interleave(2, dim=-1)
+ sin = sin[..., : sin.shape[-1] // 2].repeat_interleave(2, dim=-1)
+
+ # Keep half or full tensor for later concatenation
+ rotary_dim = cos.shape[-1]
+ q_rot, q_pass = q[..., :rotary_dim], q[..., rotary_dim:]
+ k_rot, k_pass = k[..., :rotary_dim], k[..., rotary_dim:]
+
+ # Apply rotary embeddings on the first half or full tensor
+ q_embed = (q_rot * cos) + (rotate_half(q_rot) * sin)
+ k_embed = (k_rot * cos) + (rotate_half(k_rot) * sin)
+
+ # Concatenate back to full shape
+ q_embed = torch.cat([q_embed, q_pass], dim=-1)
+ k_embed = torch.cat([k_embed, k_pass], dim=-1)
+ return q_embed, k_embed
+
+
+@use_kernelized_func(apply_rotary_pos_emb)
+class GlmAttention(nn.Module):
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
+
+ def __init__(self, config: GlmConfig, layer_idx: int | None = None):
+ super().__init__()
+ self.config = config
+ self.layer_idx = layer_idx
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
+ self.scaling = self.head_dim**-0.5
+ self.attention_dropout = config.attention_dropout
+ self.is_causal = True
+
+ self.q_proj = nn.Linear(
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
+ )
+ self.k_proj = nn.Linear(
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
+ )
+ self.v_proj = nn.Linear(
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
+ )
+ self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
+ attention_mask: torch.Tensor | None = None,
+ past_key_values: Cache | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor, torch.Tensor]:
+ input_shape = hidden_states.shape[:-1]
+ hidden_shape = (*input_shape, -1, self.head_dim)
+
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+
+ cos, sin = position_embeddings
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
+
+ if past_key_values is not None:
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_states,
+ key_states,
+ value_states,
+ attention_mask,
+ dropout=0.0 if not self.training else self.attention_dropout,
+ scaling=self.scaling,
+ **kwargs,
+ )
+
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ attn_output = self.o_proj(attn_output)
+ return attn_output, attn_weights
+
+
+@use_kernel_forward_from_hub("RMSNorm")
+class GlmRMSNorm(nn.Module):
+ def __init__(self, hidden_size, eps: float = 1e-6) -> None:
+ """
+ GlmRMSNorm is equivalent to T5LayerNorm
+ """
+ super().__init__()
+ self.weight = nn.Parameter(torch.ones(hidden_size))
+ self.variance_epsilon = eps
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ input_dtype = hidden_states.dtype
+ hidden_states = hidden_states.to(torch.float32)
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
+ return self.weight * hidden_states.to(input_dtype)
+
+ def extra_repr(self):
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
+
+
+class GlmDecoderLayer(GradientCheckpointingLayer):
+ def __init__(self, config: GlmConfig, layer_idx: int):
+ super().__init__()
+ self.hidden_size = config.hidden_size
+
+ self.self_attn = GlmAttention(config=config, layer_idx=layer_idx)
+
+ self.mlp = GlmMLP(config)
+ self.input_layernorm = GlmRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.post_attention_layernorm = GlmRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ use_cache: bool | None = False,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.Tensor:
+ residual = hidden_states
+ hidden_states = self.input_layernorm(hidden_states)
+ # Self Attention
+ hidden_states, _ = self.self_attn(
+ hidden_states=hidden_states,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ position_embeddings=position_embeddings,
+ **kwargs,
+ )
+ hidden_states = residual + hidden_states
+
+ # Fully Connected
+ residual = hidden_states
+ hidden_states = self.post_attention_layernorm(hidden_states)
+ hidden_states = self.mlp(hidden_states)
+ hidden_states = residual + hidden_states
+ return hidden_states
+
+
+@auto_docstring
+class GlmPreTrainedModel(PreTrainedModel):
+ config: GlmConfig
+ base_model_prefix = "model"
+ supports_gradient_checkpointing = True
+ _no_split_modules = ["GlmDecoderLayer"]
+ _skip_keys_device_placement = ["past_key_values"]
+ _supports_flash_attn = True
+ _supports_sdpa = True
+ _supports_flex_attn = True
+
+ _can_compile_fullgraph = True
+ _supports_attention_backend = True
+ _can_record_outputs = {
+ "hidden_states": GlmDecoderLayer,
+ "attentions": GlmAttention,
+ }
+
+
+@auto_docstring
+class GlmModel(GlmPreTrainedModel):
+ def __init__(self, config: GlmConfig):
+ super().__init__(config)
+ self.padding_idx = config.pad_token_id
+ self.vocab_size = config.vocab_size
+
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
+ self.layers = nn.ModuleList(
+ [GlmDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
+ )
+ self.norm = GlmRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.rotary_emb = GlmRotaryEmbedding(config=config)
+ self.gradient_checkpointing = False
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @merge_with_config_defaults
+ @capture_outputs
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ use_cache: bool | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> BaseModelOutputWithPast:
+ if (input_ids is None) ^ (inputs_embeds is not None):
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
+
+ if inputs_embeds is None:
+ inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)
+
+ if use_cache and past_key_values is None:
+ past_key_values = DynamicCache(config=self.config)
+
+ if position_ids is None:
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
+ position_ids = position_ids.unsqueeze(0)
+
+ causal_mask = create_causal_mask(
+ config=self.config,
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ position_ids=position_ids,
+ )
+
+ hidden_states = inputs_embeds
+ position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
+
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
+ hidden_states = decoder_layer(
+ hidden_states,
+ attention_mask=causal_mask,
+ position_embeddings=position_embeddings,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ **kwargs,
+ )
+
+ hidden_states = self.norm(hidden_states)
+ return BaseModelOutputWithPast(
+ last_hidden_state=hidden_states,
+ past_key_values=past_key_values,
+ )
+
+
+@auto_docstring
+class GlmForCausalLM(GlmPreTrainedModel, GenerationMixin):
+ _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
+ _tp_plan = {"lm_head": "colwise_gather_output"}
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
+
+ def __init__(self, config):
+ super().__init__(config)
+ self.model = GlmModel(config)
+ self.vocab_size = config.vocab_size
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ use_cache: bool | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> CausalLMOutputWithPast:
+ r"""
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, GlmForCausalLM
+
+ >>> model = GlmForCausalLM.from_pretrained("meta-glm/Glm-2-7b-hf")
+ >>> tokenizer = AutoTokenizer.from_pretrained("meta-glm/Glm-2-7b-hf")
+
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
+
+ >>> # Generate
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
+ ```"""
+ outputs: BaseModelOutputWithPast = self.model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ **kwargs,
+ )
+
+ hidden_states = outputs.last_hidden_state
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
+
+ return CausalLMOutputWithPast(
+ loss=loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+class GlmForSequenceClassification(GenericForSequenceClassification, GlmPreTrainedModel):
+ pass
+
+
+class GlmForTokenClassification(GenericForTokenClassification, GlmPreTrainedModel):
+ pass
+
+
+__all__ = [
+ "GlmPreTrainedModel",
+ "GlmModel",
+ "GlmForCausalLM",
+ "GlmForSequenceClassification",
+ "GlmForTokenClassification",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm/modular_glm.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm/modular_glm.py
new file mode 100644
index 0000000000000000000000000000000000000000..8cc9627bfa9e270c5d1f0b39d2e73e7fa40d2fe9
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm/modular_glm.py
@@ -0,0 +1,146 @@
+# Copyright 2024 The GLM & ZhipuAI team and HuggingFace Inc. team. All rights reserved.
+#
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import Optional
+
+import torch
+import torch.nn as nn
+
+from ...utils import logging
+from ..llama.modeling_llama import (
+ LlamaAttention,
+ LlamaForCausalLM,
+ LlamaForSequenceClassification,
+ LlamaForTokenClassification,
+ LlamaRotaryEmbedding,
+)
+from ..phi3.modeling_phi3 import Phi3MLP
+from .configuration_glm import GlmConfig
+
+
+logger = logging.get_logger(__name__)
+
+_CHECKPOINT_FOR_DOC = "THUDM/glm-4-9b"
+
+
+class GlmMLP(Phi3MLP):
+ pass
+
+
+class GlmRotaryEmbedding(LlamaRotaryEmbedding):
+ @staticmethod
+ def compute_default_rope_parameters(
+ config: GlmConfig | None = None,
+ device: Optional["torch.device"] = None,
+ seq_len: int | None = None,
+ ) -> tuple["torch.Tensor", float]:
+ """
+ Computes the inverse frequencies according to the original RoPE implementation
+ Args:
+ config ([`~transformers.PreTrainedConfig`]):
+ The model configuration.
+ device (`torch.device`):
+ The device to use for initialization of the inverse frequencies.
+ seq_len (`int`, *optional*):
+ The current sequence length. Unused for this type of RoPE.
+ Returns:
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
+ """
+ base = config.rope_parameters["rope_theta"]
+ partial_rotary_factor = config.rope_parameters.get("partial_rotary_factor", 1.0)
+ head_dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
+ dim = int(head_dim * partial_rotary_factor)
+
+ attention_factor = 1.0 # Unused in this type of RoPE
+
+ # Compute the inverse frequencies
+ inv_freq = 1.0 / (
+ base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
+ )
+ return inv_freq, attention_factor
+
+
+def rotate_half(x):
+ """Rotates half the hidden dims of the input."""
+ x1 = x[..., 0::2]
+ x2 = x[..., 1::2]
+ return torch.stack((-x2, x1), dim=-1).flatten(-2)
+
+
+def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
+ """Applies Rotary Position Embedding to the query and key tensors.
+
+ Args:
+ q (`torch.Tensor`): The query tensor.
+ k (`torch.Tensor`): The key tensor.
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
+ Returns:
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
+ """
+ cos = cos.unsqueeze(unsqueeze_dim)
+ sin = sin.unsqueeze(unsqueeze_dim)
+
+ # Interleave them instead of usual shape
+ cos = cos[..., : cos.shape[-1] // 2].repeat_interleave(2, dim=-1)
+ sin = sin[..., : sin.shape[-1] // 2].repeat_interleave(2, dim=-1)
+
+ # Keep half or full tensor for later concatenation
+ rotary_dim = cos.shape[-1]
+ q_rot, q_pass = q[..., :rotary_dim], q[..., rotary_dim:]
+ k_rot, k_pass = k[..., :rotary_dim], k[..., rotary_dim:]
+
+ # Apply rotary embeddings on the first half or full tensor
+ q_embed = (q_rot * cos) + (rotate_half(q_rot) * sin)
+ k_embed = (k_rot * cos) + (rotate_half(k_rot) * sin)
+
+ # Concatenate back to full shape
+ q_embed = torch.cat([q_embed, q_pass], dim=-1)
+ k_embed = torch.cat([k_embed, k_pass], dim=-1)
+ return q_embed, k_embed
+
+
+class GlmAttention(LlamaAttention):
+ def __init__(self, config: GlmConfig, layer_idx: int | None = None):
+ super().__init__(config, layer_idx)
+ self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
+
+
+class GlmForCausalLM(LlamaForCausalLM):
+ pass
+
+
+class GlmForSequenceClassification(LlamaForSequenceClassification):
+ pass
+
+
+class GlmForTokenClassification(LlamaForTokenClassification):
+ pass
+
+
+__all__ = [
+ "GlmPreTrainedModel", # noqa: F822
+ "GlmModel", # noqa: F822
+ "GlmForCausalLM",
+ "GlmForSequenceClassification",
+ "GlmForTokenClassification",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm46v/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm46v/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..5d6c4b6b007b6c3299545e6c37dd6d50145384d6
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm46v/__init__.py
@@ -0,0 +1,31 @@
+# Copyright 2025 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_glm46v import *
+ from .image_processing_glm46v import *
+ from .image_processing_pil_glm46v import *
+ from .modeling_glm46v import *
+ from .processing_glm46v import *
+ from .video_processing_glm46v import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm46v/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm46v/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fc3188f6bb95bd70739f7c7dbe3277e65efd1b4d
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm46v/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm46v/__pycache__/configuration_glm46v.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm46v/__pycache__/configuration_glm46v.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a3c9336c458233cab50d9fa304a712c625faf354
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm46v/__pycache__/configuration_glm46v.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm46v/__pycache__/image_processing_glm46v.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm46v/__pycache__/image_processing_glm46v.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5f323adb6561367f365192d58cec1ce58cddd749
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm46v/__pycache__/image_processing_glm46v.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm46v/__pycache__/image_processing_pil_glm46v.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm46v/__pycache__/image_processing_pil_glm46v.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..75a395c34e706d7a79c8a2e492ae935480eeeec5
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm46v/__pycache__/image_processing_pil_glm46v.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm46v/__pycache__/modeling_glm46v.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm46v/__pycache__/modeling_glm46v.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0ec32742f71ac4896859dfb8f334a797699ac905
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm46v/__pycache__/modeling_glm46v.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm46v/__pycache__/modular_glm46v.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm46v/__pycache__/modular_glm46v.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e45822056d4e5344274140c15b1d6556febe1c25
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm46v/__pycache__/modular_glm46v.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm46v/__pycache__/processing_glm46v.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm46v/__pycache__/processing_glm46v.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..01c5d7f5c0331e38c337cb33ec0207fe84cdb817
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm46v/__pycache__/processing_glm46v.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm46v/__pycache__/video_processing_glm46v.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm46v/__pycache__/video_processing_glm46v.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b989e6a329a6a0d10fea51d5f57a842f27587c3f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm46v/__pycache__/video_processing_glm46v.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm46v/configuration_glm46v.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm46v/configuration_glm46v.py
new file mode 100644
index 0000000000000000000000000000000000000000..95c62c7c99791693131ba38914c874e22654cc45
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm46v/configuration_glm46v.py
@@ -0,0 +1,85 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/glm46v/modular_glm46v.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_glm46v.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2025 the HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring
+from ..auto import CONFIG_MAPPING, AutoConfig
+
+
+@auto_docstring(checkpoint="zai-org/GLM-4.1V-9B-Thinking")
+@strict
+class Glm46VConfig(PreTrainedConfig):
+ r"""
+ image_start_token_id (`int`, *optional*, defaults to 151339):
+ The image start token index to encode the start of image.
+ image_end_token_id (`int`, *optional*, defaults to 151340):
+ The image end token index to encode the end of image.
+ video_start_token_id (`int`, *optional*, defaults to 151361):
+ The video start token index to encode the start of video.
+ video_end_token_id (`int`, *optional*, defaults to 151362):
+ The video end token index to encode the end of video.
+
+ ```python
+ >>> from transformers import Glm46VForConditionalGeneration, Glm46VConfig
+
+ >>> # Initializing a GLM-4.6V style configuration
+ >>> configuration = Glm46VConfig()
+
+ >>> # Initializing a model from the GLM-4.6V style configuration
+ >>> model = Glm4vForConditionalGeneration(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "glm46v"
+ sub_configs = {"text_config": AutoConfig, "vision_config": AutoConfig}
+ keys_to_ignore_at_inference = ["past_key_values"]
+
+ text_config: dict | PreTrainedConfig | None = None
+ vision_config: dict | PreTrainedConfig | None = None
+ image_token_id: int = 151343
+ video_token_id: int = 151344
+ image_start_token_id: int = 151339
+ image_end_token_id: int = 151340
+ video_start_token_id: int = 151361
+ video_end_token_id: int = 151362
+ tie_word_embeddings: bool = False
+
+ def __post_init__(self, **kwargs):
+ if isinstance(self.vision_config, dict):
+ self.vision_config["model_type"] = self.vision_config.get("model_type", "glm4v_vision")
+ self.vision_config = CONFIG_MAPPING[self.vision_config["model_type"]](**self.vision_config)
+ elif self.vision_config is None:
+ self.vision_config = CONFIG_MAPPING["glm4v_vision"]()
+
+ if isinstance(self.text_config, dict):
+ self.text_config["model_type"] = self.text_config.get("model_type", "glm4v_text")
+ self.text_config = CONFIG_MAPPING[self.text_config["model_type"]](**self.text_config)
+ elif self.text_config is None:
+ self.text_config = CONFIG_MAPPING["glm4v_text"]()
+
+ super().__post_init__(**kwargs)
+
+
+__all__ = ["Glm46VConfig"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm46v/image_processing_glm46v.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm46v/image_processing_glm46v.py
new file mode 100644
index 0000000000000000000000000000000000000000..9ed4ceba6d6e5216d55447d8ef0d3e2dfb49dce5
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm46v/image_processing_glm46v.py
@@ -0,0 +1,260 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/glm46v/modular_glm46v.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_glm46v.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2025 the HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+import math
+
+import torch
+from torchvision.transforms.v2 import functional as tvF
+
+from ...image_processing_backends import TorchvisionBackend
+from ...image_processing_utils import BatchFeature
+from ...image_transforms import group_images_by_shape, reorder_images
+from ...image_utils import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ImageInput, PILImageResampling, SizeDict
+from ...processing_utils import ImagesKwargs, Unpack
+from ...utils import TensorType, auto_docstring
+
+
+class Glm46VImageProcessorKwargs(ImagesKwargs, total=False):
+ """
+ patch_size (`int`, *optional*, defaults to 14):
+ The spatial patch size of the vision encoder.
+ temporal_patch_size (`int`, *optional*, defaults to 2):
+ The temporal patch size of the vision encoder.
+ merge_size (`int`, *optional*, defaults to 2):
+ The merge size of the vision encoder to llm encoder.
+ """
+
+ patch_size: int
+ temporal_patch_size: int
+ merge_size: int
+
+
+def smart_resize(
+ num_frames: int,
+ height: int,
+ width: int,
+ temporal_factor: int = 2,
+ factor: int = 28,
+ min_pixels: int = 112 * 112,
+ max_pixels: int = 14 * 14 * 2 * 2 * 2 * 6144,
+):
+ if num_frames < temporal_factor:
+ raise ValueError(f"t:{num_frames} must be larger than temporal_factor:{temporal_factor}")
+ if height < factor or width < factor:
+ scale = max(factor / height, factor / width)
+ height = int(height * scale)
+ width = int(width * scale)
+
+ if max(height, width) / min(height, width) > 200:
+ raise ValueError(
+ f"absolute aspect ratio must be smaller than 200, got {max(height, width) / min(height, width)}"
+ )
+ h_bar = round(height / factor) * factor
+ w_bar = round(width / factor) * factor
+ t_bar = round(num_frames / temporal_factor) * temporal_factor
+
+ if t_bar * h_bar * w_bar > max_pixels:
+ beta = math.sqrt((num_frames * height * width) / max_pixels)
+ h_bar = max(factor, math.floor(height / beta / factor) * factor)
+ w_bar = max(factor, math.floor(width / beta / factor) * factor)
+ elif t_bar * h_bar * w_bar < min_pixels:
+ beta = math.sqrt(min_pixels / (num_frames * height * width))
+ h_bar = math.ceil(height * beta / factor) * factor
+ w_bar = math.ceil(width * beta / factor) * factor
+
+ return h_bar, w_bar
+
+
+@auto_docstring
+class Glm46VImageProcessor(TorchvisionBackend):
+ do_resize = True
+ resample = PILImageResampling.BICUBIC
+ size = {"shortest_edge": 112 * 112, "longest_edge": 28 * 28 * 15000}
+ default_to_square = False
+ do_rescale = True
+ rescale_factor = 1 / 255
+ do_normalize = True
+ image_mean = OPENAI_CLIP_MEAN
+ image_std = OPENAI_CLIP_STD
+ do_convert_rgb = True
+ patch_size = 14
+ temporal_patch_size = 2
+ merge_size = 2
+ valid_kwargs = Glm46VImageProcessorKwargs
+ model_input_names = ["pixel_values", "image_grid_thw"]
+
+ def __init__(self, **kwargs: Unpack[Glm46VImageProcessorKwargs]):
+ super().__init__(**kwargs)
+ if self.size is not None:
+ if not self.size.shortest_edge or not self.size.longest_edge:
+ raise ValueError("size must contain 'shortest_edge' and 'longest_edge' keys.")
+
+ @auto_docstring
+ def preprocess(self, images: ImageInput, **kwargs: Unpack[Glm46VImageProcessorKwargs]) -> BatchFeature:
+ return super().preprocess(images, **kwargs)
+
+ def _standardize_kwargs(self, **kwargs) -> dict:
+ """
+ Update kwargs that need further processing before being validated
+ Can be overridden by subclasses to customize the processing of kwargs.
+ """
+ kwargs = super()._standardize_kwargs(**kwargs)
+ size = kwargs.get("size", self.size)
+ if not size.shortest_edge or not size.longest_edge:
+ raise ValueError("size must contain 'shortest_edge' and 'longest_edge' keys.")
+
+ return kwargs
+
+ def _preprocess(
+ self,
+ images: list["torch.Tensor"],
+ do_resize: bool,
+ size: SizeDict,
+ resample: "PILImageResampling | tvF.InterpolationMode | int | None",
+ do_rescale: bool,
+ rescale_factor: float,
+ do_normalize: bool,
+ image_mean: float | list[float] | None,
+ image_std: float | list[float] | None,
+ patch_size: int,
+ temporal_patch_size: int,
+ merge_size: int,
+ disable_grouping: bool | None,
+ return_tensors: str | TensorType | None,
+ **kwargs,
+ ) -> BatchFeature:
+ """
+ Preprocess an image or batch of images.
+ """
+
+ grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping)
+ resized_images_grouped = {}
+ for shape, stacked_images in grouped_images.items():
+ height, width = stacked_images.shape[-2:]
+ if do_resize:
+ resized_height, resized_width = smart_resize(
+ num_frames=temporal_patch_size,
+ height=height,
+ width=width,
+ temporal_factor=temporal_patch_size,
+ factor=patch_size * merge_size,
+ min_pixels=size.shortest_edge,
+ max_pixels=size.longest_edge,
+ )
+ stacked_images = self.resize(
+ stacked_images,
+ size=SizeDict(height=resized_height, width=resized_width),
+ resample=resample,
+ )
+ resized_images_grouped[shape] = stacked_images
+
+ resized_images = reorder_images(resized_images_grouped, grouped_images_index)
+
+ grouped_images, grouped_images_index = group_images_by_shape(resized_images, disable_grouping=disable_grouping)
+ processed_images_grouped = {}
+ processed_grids = {}
+
+ for shape, stacked_images in grouped_images.items():
+ resized_height, resized_width = stacked_images.shape[-2:]
+
+ patches = self.rescale_and_normalize(
+ stacked_images, do_rescale, rescale_factor, do_normalize, image_mean, image_std
+ )
+ if patches.ndim == 4: # (B, C, H, W)
+ patches = patches.unsqueeze(1) # (B, T=1, C, H, W)
+
+ if patches.shape[1] % temporal_patch_size != 0:
+ repeats = patches[:, -1:].repeat(
+ 1, temporal_patch_size - (patches.shape[1] % temporal_patch_size), 1, 1, 1
+ )
+ patches = torch.cat([patches, repeats], dim=1)
+
+ batch_size, t_len, channel = patches.shape[:3]
+ grid_t = t_len // temporal_patch_size
+ grid_h, grid_w = resized_height // patch_size, resized_width // patch_size
+
+ patches = patches.view(
+ batch_size,
+ grid_t,
+ temporal_patch_size,
+ channel,
+ grid_h // merge_size,
+ merge_size,
+ patch_size,
+ grid_w // merge_size,
+ merge_size,
+ patch_size,
+ )
+ # (B, grid_t, gh, gw, mh, mw, C, tp, ph, pw)
+ patches = patches.permute(0, 1, 4, 7, 5, 8, 3, 2, 6, 9)
+
+ flatten_patches = patches.reshape(
+ batch_size,
+ grid_t * grid_h * grid_w,
+ channel * temporal_patch_size * patch_size * patch_size,
+ )
+
+ processed_images_grouped[shape] = flatten_patches
+ processed_grids[shape] = [[grid_t, grid_h, grid_w]] * batch_size
+
+ processed_images = reorder_images(processed_images_grouped, grouped_images_index)
+ processed_grids = reorder_images(processed_grids, grouped_images_index)
+
+ pixel_values = torch.cat(processed_images, dim=0)
+ image_grid_thw = torch.tensor(processed_grids)
+
+ return BatchFeature(
+ data={"pixel_values": pixel_values, "image_grid_thw": image_grid_thw}, tensor_type=return_tensors
+ )
+
+ def get_number_of_image_patches(self, height: int, width: int, images_kwargs=None):
+ """
+ A utility that returns number of image patches for a given image size.
+
+ Args:
+ height (`int`):
+ Height of the input image.
+ width (`int`):
+ Width of the input image.
+ images_kwargs (`dict`, *optional*)
+ Any kwargs to override defaults of the image processor.
+ Returns:
+ `int`: Number of image patches per image.
+ """
+ patch_size = images_kwargs.get("patch_size", self.patch_size)
+ merge_size = images_kwargs.get("merge_size", self.merge_size)
+ size = images_kwargs.get("size", self.size)
+
+ factor = patch_size * merge_size
+ resized_height, resized_width = smart_resize(
+ num_frames=self.temporal_patch_size,
+ height=height,
+ width=width,
+ factor=factor,
+ min_pixels=size["shortest_edge"],
+ max_pixels=size["longest_edge"],
+ temporal_factor=self.temporal_patch_size,
+ )
+ grid_h, grid_w = resized_height // patch_size, resized_width // patch_size
+ return grid_h * grid_w
+
+
+__all__ = ["Glm46VImageProcessor"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm46v/image_processing_pil_glm46v.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm46v/image_processing_pil_glm46v.py
new file mode 100644
index 0000000000000000000000000000000000000000..5601e732c2b36002611ef3056ca7f3146acdac67
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm46v/image_processing_pil_glm46v.py
@@ -0,0 +1,263 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/glm46v/modular_glm46v.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_glm46v.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2025 the HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+import math
+
+import numpy as np
+
+from ...image_processing_backends import PilBackend
+from ...image_processing_utils import BatchFeature
+from ...image_utils import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ImageInput, PILImageResampling, SizeDict
+from ...processing_utils import ImagesKwargs, Unpack
+from ...utils import TensorType, auto_docstring
+
+
+class Glm46VImageProcessorKwargs(ImagesKwargs, total=False):
+ """
+ patch_size (`int`, *optional*, defaults to 14):
+ The spatial patch size of the vision encoder.
+ temporal_patch_size (`int`, *optional*, defaults to 2):
+ The temporal patch size of the vision encoder.
+ merge_size (`int`, *optional*, defaults to 2):
+ The merge size of the vision encoder to llm encoder.
+ """
+
+ patch_size: int
+ temporal_patch_size: int
+ merge_size: int
+
+
+# Adapted from transformers.models.glm46v.image_processing_glm46v.smart_resize
+def smart_resize(
+ num_frames: int,
+ height: int,
+ width: int,
+ temporal_factor: int = 2,
+ factor: int = 28,
+ min_pixels: int = 112 * 112,
+ max_pixels: int = 14 * 14 * 2 * 2 * 2 * 6144,
+):
+ if num_frames < temporal_factor:
+ raise ValueError(f"t:{num_frames} must be larger than temporal_factor:{temporal_factor}")
+ if height < factor or width < factor:
+ scale = max(factor / height, factor / width)
+ height = int(height * scale)
+ width = int(width * scale)
+
+ if max(height, width) / min(height, width) > 200:
+ raise ValueError(
+ f"absolute aspect ratio must be smaller than 200, got {max(height, width) / min(height, width)}"
+ )
+ h_bar = round(height / factor) * factor
+ w_bar = round(width / factor) * factor
+ t_bar = round(num_frames / temporal_factor) * temporal_factor
+
+ if t_bar * h_bar * w_bar > max_pixels:
+ beta = math.sqrt((num_frames * height * width) / max_pixels)
+ h_bar = max(factor, math.floor(height / beta / factor) * factor)
+ w_bar = max(factor, math.floor(width / beta / factor) * factor)
+ elif t_bar * h_bar * w_bar < min_pixels:
+ beta = math.sqrt(min_pixels / (num_frames * height * width))
+ h_bar = math.ceil(height * beta / factor) * factor
+ w_bar = math.ceil(width * beta / factor) * factor
+
+ return h_bar, w_bar
+
+
+@auto_docstring
+class Glm46VImageProcessorPil(PilBackend):
+ do_resize = True
+ resample = PILImageResampling.BICUBIC
+ size = {"shortest_edge": 112 * 112, "longest_edge": 28 * 28 * 15000}
+ default_to_square = False
+ do_rescale = True
+ rescale_factor = 1 / 255
+ do_normalize = True
+ image_mean = OPENAI_CLIP_MEAN
+ image_std = OPENAI_CLIP_STD
+ do_convert_rgb = True
+ patch_size = 14
+ temporal_patch_size = 2
+ merge_size = 2
+ valid_kwargs = Glm46VImageProcessorKwargs
+ model_input_names = ["pixel_values", "image_grid_thw"]
+
+ def __init__(self, **kwargs: Unpack[Glm46VImageProcessorKwargs]):
+ super().__init__(**kwargs)
+ if self.size is not None:
+ if not self.size.shortest_edge or not self.size.longest_edge:
+ raise ValueError("size must contain 'shortest_edge' and 'longest_edge' keys.")
+
+ @auto_docstring
+ def preprocess(self, images: ImageInput, **kwargs: Unpack[Glm46VImageProcessorKwargs]) -> BatchFeature:
+ return super().preprocess(images, **kwargs)
+
+ def _standardize_kwargs(self, **kwargs) -> dict:
+ """
+ Update kwargs that need further processing before being validated
+ Can be overridden by subclasses to customize the processing of kwargs.
+ """
+ kwargs = super()._standardize_kwargs(**kwargs)
+ size = kwargs.get("size", self.size)
+ if not size.shortest_edge or not size.longest_edge:
+ raise ValueError("size must contain 'shortest_edge' and 'longest_edge' keys.")
+
+ return kwargs
+
+ def _preprocess(
+ self,
+ images: list[np.ndarray],
+ do_resize: bool,
+ size: SizeDict,
+ resample: "PILImageResampling | None",
+ do_rescale: bool,
+ rescale_factor: float,
+ do_normalize: bool,
+ image_mean: float | list[float] | None,
+ image_std: float | list[float] | None,
+ patch_size: int,
+ temporal_patch_size: int,
+ merge_size: int,
+ return_tensors: str | TensorType | None,
+ **kwargs,
+ ) -> BatchFeature:
+ """
+ Preprocess images one by one for PIL backend.
+ """
+ processed_images = []
+ processed_grids = []
+
+ for image in images:
+ height, width = image.shape[-2:]
+ if do_resize:
+ resized_height, resized_width = smart_resize(
+ num_frames=temporal_patch_size,
+ height=height,
+ width=width,
+ temporal_factor=temporal_patch_size,
+ factor=patch_size * merge_size,
+ min_pixels=size.shortest_edge,
+ max_pixels=size.longest_edge,
+ )
+ image = self.resize(
+ image,
+ size=SizeDict(height=resized_height, width=resized_width),
+ resample=resample,
+ )
+
+ # Rescale and normalize
+ if do_rescale:
+ image = self.rescale(image, rescale_factor)
+ if do_normalize:
+ image = self.normalize(image, image_mean, image_std)
+
+ # Ensure float32 for patch processing
+ image_array = np.asarray(image, dtype=np.float32)
+ if image_array.ndim == 3: # (C, H, W)
+ image_array = np.expand_dims(image_array, axis=0) # (1, C, H, W)
+ if image_array.ndim == 4: # (B, C, H, W)
+ image_array = np.expand_dims(image_array, axis=1) # (B, T=1, C, H, W)
+
+ resized_height, resized_width = image_array.shape[-2:]
+
+ if image_array.shape[1] % temporal_patch_size != 0:
+ repeats = np.repeat(
+ image_array[:, -1:],
+ temporal_patch_size - (image_array.shape[1] % temporal_patch_size),
+ axis=1,
+ )
+ image_array = np.concatenate([image_array, repeats], axis=1)
+
+ batch_size, t_len, channel = image_array.shape[:3]
+ grid_t = t_len // temporal_patch_size
+ grid_h, grid_w = resized_height // patch_size, resized_width // patch_size
+
+ patches = image_array.reshape(
+ batch_size,
+ grid_t,
+ temporal_patch_size,
+ channel,
+ grid_h // merge_size,
+ merge_size,
+ patch_size,
+ grid_w // merge_size,
+ merge_size,
+ patch_size,
+ )
+ # (B, grid_t, gh, gw, mh, mw, C, tp, ph, pw)
+ patches = np.transpose(patches, (0, 1, 4, 7, 5, 8, 3, 2, 6, 9))
+
+ flatten_patches = patches.reshape(
+ batch_size,
+ grid_t * grid_h * grid_w,
+ channel * temporal_patch_size * patch_size * patch_size,
+ )
+
+ # Remove batch dimension and append: shape is (seq_len, hidden_dim)
+ processed_images.append(flatten_patches.squeeze(0))
+ processed_grids.append([grid_t, grid_h, grid_w])
+
+ # Concatenate all images along sequence dimension: (total_seq_len, hidden_dim)
+ pixel_values = np.concatenate(processed_images, axis=0)
+ image_grid_thw = np.array(processed_grids)
+
+ return BatchFeature(
+ data={"pixel_values": pixel_values, "image_grid_thw": image_grid_thw}, tensor_type=return_tensors
+ )
+
+ def get_number_of_image_patches(self, height: int, width: int, images_kwargs=None):
+ """
+ A utility that returns number of image patches for a given image size.
+
+ Args:
+ height (`int`):
+ Height of the input image.
+ width (`int`):
+ Width of the input image.
+ images_kwargs (`dict`, *optional*)
+ Any kwargs to override defaults of the image processor.
+ Returns:
+ `int`: Number of image patches per image.
+ """
+ if images_kwargs is not None:
+ patch_size = images_kwargs.get("patch_size", self.patch_size)
+ merge_size = images_kwargs.get("merge_size", self.merge_size)
+ size = images_kwargs.get("size", {"shortest_edge": 112 * 112, "longest_edge": 28 * 28 * 15000})
+ else:
+ patch_size = self.patch_size
+ merge_size = self.merge_size
+ size = self.size
+
+ factor = patch_size * merge_size
+ resized_height, resized_width = smart_resize(
+ num_frames=self.temporal_patch_size,
+ height=height,
+ width=width,
+ factor=factor,
+ min_pixels=size["shortest_edge"] if isinstance(size, dict) else size.shortest_edge,
+ max_pixels=size["longest_edge"] if isinstance(size, dict) else size.longest_edge,
+ temporal_factor=self.temporal_patch_size,
+ )
+ grid_h, grid_w = resized_height // patch_size, resized_width // patch_size
+ return grid_h * grid_w
+
+
+__all__ = ["Glm46VImageProcessorPil"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm46v/modeling_glm46v.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm46v/modeling_glm46v.py
new file mode 100644
index 0000000000000000000000000000000000000000..a2a2057e6173189ae89db0e594d81e0f3a0f665d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm46v/modeling_glm46v.py
@@ -0,0 +1,856 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/glm46v/modular_glm46v.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_glm46v.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2025 the HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+import itertools
+from dataclasses import dataclass
+from typing import Any
+
+import torch
+import torch.nn as nn
+
+from ...cache_utils import Cache
+from ...generation import GenerationMixin
+from ...modeling_outputs import BaseModelOutputWithPooling, ModelOutput
+from ...modeling_utils import PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import (
+ TransformersKwargs,
+ auto_docstring,
+ can_return_tuple,
+ torch_compilable_check,
+)
+from ...utils.generic import accepts_precomputed_kwargs
+from ..auto import AutoModel
+from .configuration_glm46v import Glm46VConfig
+
+
+@auto_docstring
+class Glm46VPreTrainedModel(PreTrainedModel):
+ config: Glm46VConfig
+ base_model_prefix = "model"
+ input_modalities = ("image", "video", "text")
+ supports_gradient_checkpointing = True
+ _no_split_modules = None
+ _skip_keys_device_placement = ["past_key_values"]
+ _supports_flash_attn = True
+ _supports_sdpa = True
+
+ _can_compile_fullgraph = True
+ _supports_attention_backend = True
+ _can_record_outputs = None
+
+
+@auto_docstring(
+ custom_intro="""
+ Base class for Llava outputs, with hidden states and attentions.
+ """
+)
+@dataclass
+class Glm46VModelOutputWithPast(ModelOutput):
+ r"""
+ past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
+ It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
+
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
+ `past_key_values` input) to speed up sequential decoding.
+ rope_deltas (`torch.LongTensor` of shape `(batch_size, )`, *optional*):
+ The rope index difference between sequence length and multimodal rope.
+ """
+
+ last_hidden_state: torch.FloatTensor | None = None
+ past_key_values: Cache | None = None
+ hidden_states: tuple[torch.FloatTensor] | None = None
+ attentions: tuple[torch.FloatTensor] | None = None
+ rope_deltas: torch.LongTensor | None = None
+
+
+@auto_docstring
+class Glm46VModel(Glm46VPreTrainedModel):
+ base_model_prefix = "model"
+ # Reference: fix gemma3 grad acc #37208
+ accepts_loss_kwargs = False
+ _no_split_modules = None
+
+ def __init__(self, config):
+ super().__init__(config)
+ self.visual = AutoModel.from_config(config.vision_config)
+ self.language_model = AutoModel.from_config(config.text_config)
+ self.rope_deltas = None # cache rope_deltas here
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_vision_position_ids(
+ self,
+ start_position: int,
+ grid_thw: list[int, int, int] | torch.Tensor,
+ temp_merge_size: int = 1,
+ spatial_merge_size: int = 1,
+ time_interval: int = 1,
+ device: str | torch.device | None = None,
+ ):
+ """
+ Compute 3D positional indices for vision tokens derived from a single image or video input.
+
+ The positions are generated from the input grid defined by temporal (T), height (H), and
+ width (W) dimensions. Temporal and spatial dimensions can be downscaled according to the
+ merge sizes used in the vision backbone. The resulting positions are offset by `start_position`.
+
+ Args:
+ start_position (`int`):
+ Offset added to all computed positional indices.
+ grid_thw (`Sequence[int]` or `torch.Tensor` of shape `(3,)`):
+ The (T, H, W) grid representing the feature layout of the current image or video after patch embedding.
+ temp_merge_size (`int`, *optional*):
+ Factor by which the temporal dimension is reduced in the backbone. The temporal grid size is divided
+ by this value. Defaults to 1.
+ spatial_merge_size (`int`, *optional*):
+ Factor by which the spatial dimensions (H and W) are reduced in the backbone. Both H and W are divided
+ by this value. Defaults to 1.
+ time_interval (`int`, *optional*):
+ Spacing factor applied between consecutive temporal position indices.Defaults to 1.
+ device (`str` or `torch.device`, *optional*):
+ Device on which the resulting tensor is allocated. If `None`, uses the current default device.
+
+ Returns:
+ torch.LongTensor of shape (3, sequence_length):
+ Positional indices for temporal, height, and width dimensions,
+ flattened into sequence form and offset by `start_position`.
+ """
+ llm_grid_t, llm_grid_h, llm_grid_w = (
+ grid_thw[0].item() // temp_merge_size,
+ grid_thw[1].item() // spatial_merge_size,
+ grid_thw[2].item() // spatial_merge_size,
+ )
+
+ # Add `start_position` after arange for compile
+ position_temporal = torch.arange(llm_grid_t, device=device) * time_interval
+ position_width = torch.arange(llm_grid_w, device=device) + start_position
+ position_height = torch.arange(llm_grid_h, device=device) + start_position
+
+ # Repeat the positions per each grid and per video frame. Repeat patterns are important
+ # do not modify without checking values!
+ position_width = position_width.repeat(llm_grid_h * llm_grid_t)
+ position_height = position_height.repeat_interleave(llm_grid_w).repeat(llm_grid_t)
+ # Important: add `start_positions` after applying `time_interval`, order matters
+ position_temporal = position_temporal.repeat_interleave(llm_grid_h * llm_grid_w) + start_position
+ vision_position_ids = torch.stack([position_temporal, position_height, position_width], dim=0)
+
+ return vision_position_ids
+
+ def get_rope_index(
+ self,
+ input_ids: torch.LongTensor,
+ mm_token_type_ids: torch.IntTensor,
+ image_grid_thw: torch.LongTensor | None = None,
+ video_grid_thw: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ **kwargs,
+ ) -> tuple[torch.Tensor, torch.Tensor]:
+ """
+ Difference from Qwen2VL/Qwen2.5VL's get_rope_index:
+ - GLM46V uses timestamps to separate each video frame, so the video_grid_thw should also be split too.
+
+ Args:
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
+ it.
+ mm_token_type_ids (`torch.IntTensor` of shape `(batch_size, sequence_length)`):
+ Token type ids matching each modality to a different value in the input sequence, i.e. text (0), image (1), video (2).
+ image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
+ The temporal, height and width of feature shape of each image in LLM.
+ video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*):
+ The temporal, height and width of feature shape of each video in LLM.
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
+
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+
+ Returns:
+ position_ids (`torch.LongTensor` of shape `(3, batch_size, sequence_length)`)
+ mrope_position_deltas (`torch.Tensor` of shape `(batch_size)`)
+ """
+
+ # Separate video grid thw into multiple grids because timestamps are used to separate videos.
+ if video_grid_thw is not None:
+ video_grid_thw = torch.repeat_interleave(video_grid_thw, video_grid_thw[:, 0], dim=0)
+ video_grid_thw[:, 0] = 1
+ spatial_merge_size = self.config.vision_config.spatial_merge_size
+
+ mrope_position_deltas = []
+ position_ids = torch.zeros(
+ 3,
+ input_ids.shape[0],
+ input_ids.shape[1],
+ dtype=input_ids.dtype,
+ device=input_ids.device,
+ )
+ grid_iters = {
+ 1: iter(image_grid_thw) if image_grid_thw is not None else None,
+ 2: iter(video_grid_thw) if video_grid_thw is not None else None,
+ }
+
+ for batch_idx, current_input_ids in enumerate(input_ids):
+ input_token_type = mm_token_type_ids[batch_idx]
+ if attention_mask is not None:
+ current_input_ids = current_input_ids[attention_mask[batch_idx].bool()]
+ input_token_type = input_token_type[attention_mask[batch_idx].bool()]
+
+ input_type_group = []
+ for key, group in itertools.groupby(enumerate(input_token_type.tolist()), lambda x: x[1]):
+ group = list(group)
+ start_index = group[0][0]
+ end_index = group[-1][0] + 1
+ input_type_group.append((key, start_index, end_index))
+
+ current_pos = 0
+ llm_pos_ids_list = []
+ for modality_type, start_idx, end_idx in input_type_group:
+ # text == 0
+ if modality_type == 0:
+ text_len = end_idx - start_idx
+ llm_pos_ids_list.append(
+ torch.arange(text_len, device=input_ids.device).view(1, -1).expand(3, -1) + current_pos
+ )
+ current_pos += text_len
+ # image == 1, video == 2
+ else:
+ grid_thw = next(grid_iters[modality_type])
+ vision_position_ids = self.get_vision_position_ids(
+ current_pos, grid_thw, 1, spatial_merge_size, device=input_ids.device
+ )
+ llm_pos_ids_list.append(vision_position_ids)
+ current_pos += max(grid_thw[1], grid_thw[2]) // spatial_merge_size
+ llm_positions = torch.cat(llm_pos_ids_list, dim=1).reshape(3, -1)
+ if attention_mask is not None:
+ position_ids[:, batch_idx, attention_mask[batch_idx].bool()] = llm_positions.to(position_ids.device)
+ else:
+ position_ids[:, batch_idx] = llm_positions.to(position_ids.device)
+ mrope_position_deltas.append(llm_positions.max() + 1 - len(current_input_ids))
+ mrope_position_deltas = torch.tensor(mrope_position_deltas, device=input_ids.device).unsqueeze(1)
+ return position_ids, mrope_position_deltas
+
+ @accepts_precomputed_kwargs(modality="video")
+ @can_return_tuple
+ @auto_docstring
+ def get_video_features(
+ self,
+ pixel_values_videos: torch.FloatTensor,
+ video_grid_thw: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutputWithPooling:
+ r"""
+ pixel_values_videos (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
+ The tensors corresponding to the input videos.
+ video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*):
+ The temporal, height and width of feature shape of each video in LLM.
+ """
+ pixel_values_videos = pixel_values_videos.type(self.visual.dtype)
+ # reshape video_grid_thw -> [b, 3] -> [1, h, w] * frames
+ t = video_grid_thw[:, 0]
+ hw = video_grid_thw[:, 1:]
+ # repeat each (h,w) row `t` times
+ flattened_hw = torch.repeat_interleave(hw, t, dim=0)
+ prefix_ones = video_grid_thw.new_ones(flattened_hw.shape[0], 1)
+ flattened_video_grid_thw = torch.cat([prefix_ones, flattened_hw], dim=1)
+ vision_outputs = self.visual(
+ pixel_values_videos, grid_thw=flattened_video_grid_thw, return_dict=True, **kwargs
+ )
+ split_sizes = (video_grid_thw.prod(-1) // self.visual.spatial_merge_size**2).tolist()
+ video_embeds = torch.split(vision_outputs.pooler_output, split_sizes)
+ vision_outputs.pooler_output = video_embeds
+
+ return vision_outputs
+
+ @accepts_precomputed_kwargs(modality="image")
+ @can_return_tuple
+ @auto_docstring
+ def get_image_features(
+ self,
+ pixel_values: torch.FloatTensor,
+ image_grid_thw: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutputWithPooling:
+ r"""
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
+ The tensors corresponding to the input images.
+ image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
+ The temporal, height and width of feature shape of each image in LLM.
+ """
+ pixel_values = pixel_values.type(self.visual.dtype)
+ vision_outputs = self.visual(pixel_values, grid_thw=image_grid_thw, **kwargs)
+ split_sizes = (image_grid_thw.prod(-1) // self.visual.spatial_merge_size**2).tolist()
+ image_embeds = torch.split(vision_outputs.pooler_output, split_sizes)
+ vision_outputs.pooler_output = image_embeds
+
+ return vision_outputs
+
+ def get_placeholder_mask(
+ self,
+ input_ids: torch.LongTensor,
+ inputs_embeds: torch.FloatTensor,
+ image_features: torch.FloatTensor | None = None,
+ video_features: torch.FloatTensor | None = None,
+ ):
+ """
+ Obtains multimodal placeholder mask from `input_ids` or `inputs_embeds`, and checks that the placeholder token count is
+ equal to the length of multimodal features. If the lengths are different, an error is raised.
+ """
+ if input_ids is None:
+ special_image_mask = inputs_embeds == self.get_input_embeddings()(
+ torch.tensor(self.config.image_token_id, dtype=torch.long, device=inputs_embeds.device)
+ )
+ special_image_mask = special_image_mask.all(-1)
+ special_video_mask = inputs_embeds == self.get_input_embeddings()(
+ torch.tensor(self.config.video_token_id, dtype=torch.long, device=inputs_embeds.device)
+ )
+ special_video_mask = special_video_mask.all(-1)
+ else:
+ # GLM-4.1V and GLM-4.5V special_video_mask is special_image_mask
+ special_image_mask = input_ids == self.config.image_token_id
+ special_video_mask = input_ids == self.config.image_token_id
+
+ n_image_tokens = special_image_mask.sum()
+ special_image_mask = special_image_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
+ if image_features is not None:
+ torch_compilable_check(
+ inputs_embeds[special_image_mask].numel() == image_features.numel(),
+ f"Image features and image tokens do not match, tokens: {n_image_tokens}, features: {image_features.shape[0]}",
+ )
+
+ n_video_tokens = special_video_mask.sum()
+ special_video_mask = special_video_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
+ if video_features is not None:
+ torch_compilable_check(
+ inputs_embeds[special_video_mask].numel() == video_features.numel(),
+ f"Video features and video tokens do not match, tokens: {n_video_tokens}, features: {video_features.shape[0]}",
+ )
+ return special_image_mask, special_video_mask
+
+ def compute_3d_position_ids(
+ self,
+ input_ids: torch.Tensor | None,
+ inputs_embeds: torch.Tensor | None,
+ image_grid_thw: torch.Tensor | None = None,
+ video_grid_thw: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ past_key_values: torch.Tensor | None = None,
+ mm_token_type_ids: torch.IntTensor | None = None,
+ ) -> torch.Tensor | None:
+ past_key_values_length = 0 if past_key_values is None else past_key_values.get_seq_length()
+ has_multimodal = image_grid_thw is not None or video_grid_thw is not None
+ if has_multimodal and mm_token_type_ids is None and input_ids is not None:
+ raise ValueError(
+ "Multimodal data was passed (via `image_grid_thw` or `video_grid_thw`) but `mm_token_type_ids` is "
+ "missing. Please pass `mm_token_type_ids` to the model so that multimodal RoPE (M-RoPE) can be "
+ "computed correctly. `mm_token_type_ids` is returned by the processor alongside `input_ids`."
+ )
+ can_compute_mrope = input_ids is not None and mm_token_type_ids is not None and has_multimodal
+
+ if can_compute_mrope and (self.rope_deltas is None or past_key_values_length == 0):
+ position_ids, rope_deltas = self.get_rope_index(
+ input_ids,
+ image_grid_thw=image_grid_thw,
+ video_grid_thw=video_grid_thw,
+ attention_mask=attention_mask,
+ mm_token_type_ids=mm_token_type_ids,
+ )
+ self.rope_deltas = rope_deltas
+ # Use pre-calculated rope-deltas to infer correct 3D position ids during incremental
+ # generation (past_key_values_length > 0) or when only inputs_embeds is provided (no input_ids
+ # to recompute from). Skip when input_ids is provided without past_key_values to avoid shape
+ # mismatches from stale rope_deltas (e.g., training forward pass after generation).
+ elif self.rope_deltas is not None and (past_key_values_length > 0 or input_ids is None):
+ batch_size, seq_length, _ = inputs_embeds.shape
+ if attention_mask is not None:
+ position_ids = attention_mask.long().cumsum(-1) - 1
+ position_ids = position_ids.masked_fill(attention_mask == 0, 0)
+ position_ids = position_ids.view(1, batch_size, -1).repeat(3, 1, 1).to(inputs_embeds.device)
+ else:
+ position_ids = torch.arange(past_key_values_length, past_key_values_length + seq_length)
+ position_ids = position_ids.view(1, 1, -1).expand(3, batch_size, -1).to(inputs_embeds.device)
+ delta = self.rope_deltas.repeat_interleave(batch_size // self.rope_deltas.shape[0], dim=0)
+ position_ids = position_ids + delta.to(device=inputs_embeds.device)
+ else:
+ # Can't build correct 3D positions. Let the model infer it
+ position_ids = None
+ return position_ids
+
+ @auto_docstring
+ @can_return_tuple
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ pixel_values: torch.Tensor | None = None,
+ pixel_values_videos: torch.FloatTensor | None = None,
+ image_grid_thw: torch.LongTensor | None = None,
+ video_grid_thw: torch.LongTensor | None = None,
+ rope_deltas: torch.LongTensor | None = None,
+ mm_token_type_ids: torch.IntTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | Glm46VModelOutputWithPast:
+ r"""
+ image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
+ The temporal, height and width of feature shape of each image in LLM.
+ video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*):
+ The temporal, height and width of feature shape of each video in LLM.
+ rope_deltas (`torch.LongTensor` of shape `(batch_size, )`, *optional*):
+ The rope index difference between sequence length and multimodal rope.
+ """
+ if (input_ids is None) ^ (inputs_embeds is not None):
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
+
+ if inputs_embeds is None:
+ inputs_embeds = self.get_input_embeddings()(input_ids)
+
+ if pixel_values is not None:
+ image_embeds = self.get_image_features(
+ pixel_values, image_grid_thw, return_dict=True, **kwargs
+ ).pooler_output
+ image_embeds = torch.cat(image_embeds, dim=0).to(inputs_embeds.device, inputs_embeds.dtype)
+ image_mask, _ = self.get_placeholder_mask(input_ids, inputs_embeds, image_features=image_embeds)
+ inputs_embeds = inputs_embeds.masked_scatter(image_mask, image_embeds)
+
+ if pixel_values_videos is not None:
+ video_embeds = self.get_video_features(
+ pixel_values_videos, video_grid_thw, return_dict=True, **kwargs
+ ).pooler_output
+ video_embeds = torch.cat(video_embeds, dim=0).to(inputs_embeds.device, inputs_embeds.dtype)
+ _, video_mask = self.get_placeholder_mask(input_ids, inputs_embeds, video_features=video_embeds)
+ inputs_embeds = inputs_embeds.masked_scatter(video_mask, video_embeds)
+
+ if position_ids is None:
+ position_ids = self.compute_3d_position_ids(
+ input_ids=input_ids,
+ image_grid_thw=image_grid_thw,
+ video_grid_thw=video_grid_thw,
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ mm_token_type_ids=mm_token_type_ids,
+ )
+
+ outputs = self.language_model(
+ input_ids=None,
+ position_ids=position_ids,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ **kwargs,
+ )
+
+ return Glm46VModelOutputWithPast(
+ **outputs,
+ rope_deltas=self.rope_deltas,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ Base class for Glm46V causal language model (or autoregressive) outputs.
+ """
+)
+@dataclass
+class Glm46VCausalLMOutputWithPast(ModelOutput):
+ r"""
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
+ Language modeling loss (for next-token prediction).
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
+ past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
+ It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
+
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
+ `past_key_values` input) to speed up sequential decoding.
+ rope_deltas (`torch.LongTensor` of shape `(batch_size, )`, *optional*):
+ The rope index difference between sequence length and multimodal rope.
+ """
+
+ loss: torch.FloatTensor | None = None
+ logits: torch.FloatTensor | None = None
+ past_key_values: Cache | None = None
+ hidden_states: tuple[torch.FloatTensor] | None = None
+ attentions: tuple[torch.FloatTensor] | None = None
+ rope_deltas: torch.LongTensor | None = None
+
+
+class Glm46VForConditionalGeneration(Glm46VPreTrainedModel, GenerationMixin):
+ _tied_weights_keys = {"lm_head.weight": "model.language_model.embed_tokens.weight"}
+ # Reference: fix gemma3 grad acc #37208
+ accepts_loss_kwargs = False
+
+ def __init__(self, config):
+ super().__init__(config)
+ self.model = Glm46VModel(config)
+ self.lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.vocab_size, bias=False)
+
+ self.post_init()
+
+ @auto_docstring
+ def get_video_features(
+ self,
+ pixel_values_videos: torch.FloatTensor,
+ video_grid_thw: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutputWithPooling:
+ r"""
+ pixel_values_videos (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
+ The tensors corresponding to the input videos.
+ video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*):
+ The temporal, height and width of feature shape of each video in LLM.
+ """
+ return self.model.get_video_features(pixel_values_videos, video_grid_thw, **kwargs)
+
+ @auto_docstring
+ def get_image_features(
+ self,
+ pixel_values: torch.FloatTensor,
+ image_grid_thw: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutputWithPooling:
+ r"""
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
+ The tensors corresponding to the input images.
+ image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
+ The temporal, height and width of feature shape of each image in LLM.
+ """
+ return self.model.get_image_features(pixel_values, image_grid_thw, **kwargs)
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ pixel_values: torch.Tensor | None = None,
+ pixel_values_videos: torch.FloatTensor | None = None,
+ image_grid_thw: torch.LongTensor | None = None,
+ video_grid_thw: torch.LongTensor | None = None,
+ mm_token_type_ids: torch.IntTensor | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | Glm46VCausalLMOutputWithPast:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
+ image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
+ The temporal, height and width of feature shape of each image in LLM.
+ video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*):
+ The temporal, height and width of feature shape of each video in LLM.
+
+ Example:
+
+ ```python
+ >>> from PIL import Image
+ >>> import httpx
+ >>> from io import BytesIO
+ >>> from transformers import AutoProcessor, Glm46VForConditionalGeneration
+
+ >>> model = Glm46VForConditionalGeneration.from_pretrained("zai-org/GLM-4.1V-9B-Thinking")
+ >>> processor = AutoProcessor.from_pretrained("zai-org/GLM-4.1V-9B-Thinking")
+
+ >>> messages = [
+ {
+ "role": "user",
+ "content": [
+ {"type": "image", "url": "https://www.ilankelman.org/stopsigns/australia.jpg"},
+ {"type": "text", "text": "What is shown in this image?"},
+ ],
+ },
+ ]
+ >>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
+ >>> with httpx.stream("GET", url) as response:
+ ... image = Image.open(BytesIO(response.read()))
+
+ >>> text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
+ >>> inputs = processor(text=[text], images=[image], vision_infos=[vision_infos])
+
+ >>> # Generate
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
+ "The image shows a street scene with a red stop sign in the foreground. In the background, there is a large red gate with Chinese characters ..."
+ ```"""
+ outputs = self.model(
+ input_ids=input_ids,
+ pixel_values=pixel_values,
+ pixel_values_videos=pixel_values_videos,
+ image_grid_thw=image_grid_thw,
+ video_grid_thw=video_grid_thw,
+ mm_token_type_ids=mm_token_type_ids,
+ position_ids=position_ids,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ **kwargs,
+ )
+
+ hidden_states = outputs[0]
+
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.text_config.vocab_size)
+
+ return Glm46VCausalLMOutputWithPast(
+ loss=loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ rope_deltas=outputs.rope_deltas,
+ )
+
+ def prepare_inputs_for_generation(
+ self,
+ input_ids,
+ past_key_values=None,
+ attention_mask=None,
+ inputs_embeds=None,
+ position_ids=None,
+ use_cache=True,
+ pixel_values=None,
+ pixel_values_videos=None,
+ image_grid_thw=None,
+ video_grid_thw=None,
+ is_first_iteration=False,
+ **kwargs,
+ ):
+ # Overwritten -- in specific circumstances we don't want to forward image inputs to the model
+
+ model_inputs = super().prepare_inputs_for_generation(
+ input_ids,
+ past_key_values=past_key_values,
+ attention_mask=attention_mask,
+ inputs_embeds=inputs_embeds,
+ position_ids=position_ids,
+ pixel_values=pixel_values,
+ pixel_values_videos=pixel_values_videos,
+ image_grid_thw=image_grid_thw,
+ video_grid_thw=video_grid_thw,
+ use_cache=use_cache,
+ is_first_iteration=is_first_iteration,
+ **kwargs,
+ )
+
+ if not is_first_iteration and use_cache:
+ model_inputs["pixel_values"] = None
+ model_inputs["pixel_values_videos"] = None
+
+ return model_inputs
+
+ def _prepare_position_ids_for_generation(self, inputs_tensor, model_kwargs):
+ # Overwritten -- requires 3D position ids
+
+ text_positions = super()._prepare_position_ids_for_generation(inputs_tensor, model_kwargs)
+
+ # Early exit in case we are continuing generation from past kv
+ past_length = 0
+ if (cache := model_kwargs.get("past_key_values")) is not None:
+ past_length = cache.get_seq_length()
+ if past_length != 0 and self.model.rope_deltas is not None:
+ position_ids = text_positions[None, ...] + self.model.rope_deltas
+ return position_ids
+
+ # Otherwise compute 3d position ids for vision tokens and concat with text position ids
+ if "input_ids" in model_kwargs and model_kwargs["input_ids"].shape[1] > 0:
+ inputs_tensor = model_kwargs["input_ids"]
+
+ is_input_ids = len(inputs_tensor.shape) == 2 and inputs_tensor.dtype in [torch.int, torch.long]
+ if (
+ is_input_ids
+ and model_kwargs.get("mm_token_type_ids") is not None
+ and (model_kwargs.get("image_grid_thw") is not None or model_kwargs.get("video_grid_thw") is not None)
+ ):
+ model_kwargs = {k: v for k, v in model_kwargs.items() if k != "input_ids"}
+ vision_positions, rope_deltas = self.model.get_rope_index(inputs_tensor, **model_kwargs)
+ self.model.rope_deltas = rope_deltas
+ else:
+ vision_positions = text_positions.unsqueeze(0).expand(3, -1, -1)
+ self.model.rope_deltas = torch.zeros(
+ inputs_tensor.shape[0], 1, dtype=torch.long, device=inputs_tensor.device
+ )
+
+ # Concatenate "text + vision" positions into [4, bs, seq-len]
+ text_positions = text_positions[None, ...]
+ position_ids = torch.cat([text_positions, vision_positions], dim=0)
+
+ return position_ids
+
+ def _get_image_nums_and_video_nums(
+ self,
+ input_ids: torch.LongTensor | None,
+ inputs_embeds: torch.Tensor | None = None,
+ ) -> tuple[torch.Tensor, torch.Tensor]:
+ """
+ Get the number of images and videos for each sample to calculate the separation length of the sample tensor.
+ These parameters are not passed through the processor to avoid unpredictable impacts from interface modifications.
+
+ Args:
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary.
+
+ Returns:
+ image_nums (`torch.LongTensor` of shape `(batch_size, num_images_sample)`)
+ video_nums (`torch.LongTensor` of shape `(batch_size, num_videos_sample)`)
+ """
+
+ if inputs_embeds is not None:
+ is_image = (
+ inputs_embeds
+ == self.get_input_embeddings()(
+ torch.tensor(self.config.image_start_token_id, dtype=torch.long, device=inputs_embeds.device)
+ )
+ )[..., 0]
+ is_video_start = (
+ inputs_embeds
+ == self.get_input_embeddings()(
+ torch.tensor(self.config.video_start_token_id, dtype=torch.long, device=inputs_embeds.device)
+ )
+ )[..., 0]
+ is_video_end = (
+ inputs_embeds
+ == self.get_input_embeddings()(
+ torch.tensor(self.config.video_end_token_id, dtype=torch.long, device=inputs_embeds.device)
+ )
+ )[..., 0]
+ else:
+ is_image = input_ids == self.config.image_start_token_id
+ is_video_start = input_ids == self.config.video_start_token_id
+ is_video_end = input_ids == self.config.video_end_token_id
+
+ # Cumulative sum to track if we're inside a video span
+ # We'll assume well-formed video tags (i.e. matching starts and ends)
+ video_level = torch.cumsum(is_video_start.int() - is_video_end.int(), dim=1)
+ inside_video = video_level > 0 # shape (batch_size, seq_length)
+
+ # Mask out image tokens that are inside video spans
+ standalone_images = is_image & (~inside_video)
+
+ # Count per batch
+ image_counts = standalone_images.sum(dim=1)
+ video_counts = is_video_start.sum(dim=1)
+
+ return image_counts, video_counts
+
+ def _expand_inputs_for_generation(
+ self,
+ expand_size: int = 1,
+ is_encoder_decoder: bool = False,
+ input_ids: torch.LongTensor | None = None,
+ **model_kwargs,
+ ) -> tuple[torch.LongTensor, dict[str, Any]]:
+ # Overwritten -- Support for expanding tensors without a batch size dimension
+ # e.g., pixel_values, image_grid_thw, pixel_values_videos, video_grid_thw, second_per_grid_t
+ # pixel_values.shape[0] is sum(seqlen_images for samples)
+ # image_grid_thw.shape[0] is sum(num_images for samples)
+
+ if expand_size == 1:
+ return input_ids, model_kwargs
+
+ visual_keys = ["pixel_values", "image_grid_thw", "pixel_values_videos", "video_grid_thw", "second_per_grid_ts"]
+
+ def _expand_dict_for_generation_visual(dict_to_expand):
+ image_grid_thw = model_kwargs.get("image_grid_thw", None)
+ video_grid_thw = model_kwargs.get("video_grid_thw", None)
+ image_nums, video_nums = self._get_image_nums_and_video_nums(
+ input_ids, inputs_embeds=model_kwargs.get("inputs_embeds", None)
+ )
+
+ def _repeat_interleave_samples(x, lengths, repeat_times):
+ samples = torch.split(x, lengths)
+ repeat_args = [repeat_times] + [1] * (x.dim() - 1)
+ result = torch.cat([sample.repeat(*repeat_args) for sample in samples], dim=0)
+ return result
+
+ for key in dict_to_expand:
+ if key == "pixel_values":
+ # split images into samples
+ samples = torch.split(image_grid_thw, list(image_nums))
+ # compute the sequence length of images for each sample
+ lengths = [torch.prod(sample, dim=1).sum() for sample in samples]
+ dict_to_expand[key] = _repeat_interleave_samples(
+ dict_to_expand[key], lengths=lengths, repeat_times=expand_size
+ )
+ elif key == "image_grid_thw":
+ # get the num of images for each sample
+ lengths = list(image_nums)
+ dict_to_expand[key] = _repeat_interleave_samples(
+ dict_to_expand[key], lengths=lengths, repeat_times=expand_size
+ )
+ elif key == "pixel_values_videos":
+ samples = torch.split(video_grid_thw, list(video_nums))
+ lengths = [torch.prod(sample, dim=1).sum() for sample in samples]
+ dict_to_expand[key] = _repeat_interleave_samples(
+ dict_to_expand[key], lengths=lengths, repeat_times=expand_size
+ )
+ elif key == "video_grid_thw":
+ lengths = list(video_nums)
+ dict_to_expand[key] = _repeat_interleave_samples(
+ dict_to_expand[key], lengths=lengths, repeat_times=expand_size
+ )
+ elif key == "second_per_grid_ts":
+ dict_to_expand[key] = _repeat_interleave_samples(
+ dict_to_expand[key], lengths=list(video_nums), repeat_times=expand_size
+ )
+ return dict_to_expand
+
+ def _expand_dict_for_generation(dict_to_expand):
+ for key in dict_to_expand:
+ if key == "position_ids" and dict_to_expand[key].ndim == 3:
+ dict_to_expand[key] = dict_to_expand[key].repeat_interleave(expand_size, dim=1)
+ elif (
+ dict_to_expand[key] is not None
+ and isinstance(dict_to_expand[key], torch.Tensor)
+ and key not in visual_keys
+ ):
+ dict_to_expand[key] = dict_to_expand[key].repeat_interleave(expand_size, dim=0)
+ return dict_to_expand
+
+ model_kwargs = _expand_dict_for_generation_visual(model_kwargs)
+
+ if input_ids is not None:
+ input_ids = input_ids.repeat_interleave(expand_size, dim=0)
+
+ model_kwargs = _expand_dict_for_generation(model_kwargs)
+
+ if is_encoder_decoder:
+ if model_kwargs.get("encoder_outputs") is None:
+ raise ValueError("If `is_encoder_decoder` is True, make sure that `encoder_outputs` is defined.")
+ model_kwargs["encoder_outputs"] = _expand_dict_for_generation(model_kwargs["encoder_outputs"])
+
+ return input_ids, model_kwargs
+
+
+__all__ = ["Glm46VModel", "Glm46VPreTrainedModel", "Glm46VForConditionalGeneration"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm46v/modular_glm46v.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm46v/modular_glm46v.py
new file mode 100644
index 0000000000000000000000000000000000000000..0fdcef45136f8f18f10403e0582ca4c3bd0dd722
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm46v/modular_glm46v.py
@@ -0,0 +1,197 @@
+# Copyright 2025 the HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+import numpy as np
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring
+from ...video_utils import VideoMetadata
+from ..auto import CONFIG_MAPPING, AutoConfig, AutoModel
+from ..glm4v.image_processing_glm4v import Glm4vImageProcessor
+from ..glm4v.image_processing_pil_glm4v import Glm4vImageProcessorPil
+from ..glm4v.modeling_glm4v import Glm4vForConditionalGeneration, Glm4vModel, Glm4vPreTrainedModel
+from ..glm4v.processing_glm4v import Glm4vProcessor
+from ..glm4v.video_processing_glm4v import Glm4vVideoProcessor
+
+
+@auto_docstring(checkpoint="zai-org/GLM-4.1V-9B-Thinking")
+@strict
+class Glm46VConfig(PreTrainedConfig):
+ r"""
+ image_start_token_id (`int`, *optional*, defaults to 151339):
+ The image start token index to encode the start of image.
+ image_end_token_id (`int`, *optional*, defaults to 151340):
+ The image end token index to encode the end of image.
+ video_start_token_id (`int`, *optional*, defaults to 151361):
+ The video start token index to encode the start of video.
+ video_end_token_id (`int`, *optional*, defaults to 151362):
+ The video end token index to encode the end of video.
+
+ ```python
+ >>> from transformers import Glm46VForConditionalGeneration, Glm46VConfig
+
+ >>> # Initializing a GLM-4.6V style configuration
+ >>> configuration = Glm46VConfig()
+
+ >>> # Initializing a model from the GLM-4.6V style configuration
+ >>> model = Glm4vForConditionalGeneration(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "glm46v"
+ sub_configs = {"text_config": AutoConfig, "vision_config": AutoConfig}
+ keys_to_ignore_at_inference = ["past_key_values"]
+
+ text_config: dict | PreTrainedConfig | None = None
+ vision_config: dict | PreTrainedConfig | None = None
+ image_token_id: int = 151343
+ video_token_id: int = 151344
+ image_start_token_id: int = 151339
+ image_end_token_id: int = 151340
+ video_start_token_id: int = 151361
+ video_end_token_id: int = 151362
+ tie_word_embeddings: bool = False
+
+ def __post_init__(self, **kwargs):
+ if isinstance(self.vision_config, dict):
+ self.vision_config["model_type"] = self.vision_config.get("model_type", "glm4v_vision")
+ self.vision_config = CONFIG_MAPPING[self.vision_config["model_type"]](**self.vision_config)
+ elif self.vision_config is None:
+ self.vision_config = CONFIG_MAPPING["glm4v_vision"]()
+
+ if isinstance(self.text_config, dict):
+ self.text_config["model_type"] = self.text_config.get("model_type", "glm4v_text")
+ self.text_config = CONFIG_MAPPING[self.text_config["model_type"]](**self.text_config)
+ elif self.text_config is None:
+ self.text_config = CONFIG_MAPPING["glm4v_text"]()
+
+ super().__post_init__(**kwargs)
+
+
+class Glm46VPreTrainedModel(Glm4vPreTrainedModel):
+ _can_record_outputs = None
+ _no_split_modules = None
+
+ def _init_weights(self, module):
+ raise AttributeError("Not needed")
+
+
+class Glm46VModel(Glm4vModel):
+ _no_split_modules = None
+
+ def __init__(self, config):
+ super().__init__(config)
+ self.visual = AutoModel.from_config(config.vision_config)
+ self.language_model = AutoModel.from_config(config.text_config)
+
+
+class Glm46VForConditionalGeneration(Glm4vForConditionalGeneration):
+ pass
+
+
+class Glm46VProcessor(Glm4vProcessor):
+ def replace_frame_token_id(self, timestamp_sec):
+ return f"<|begin_of_image|>{self.image_token}<|end_of_image|>{timestamp_sec:.1f} seconds"
+
+
+class Glm46VImageProcessorPil(Glm4vImageProcessorPil):
+ pass
+
+
+class Glm46VImageProcessor(Glm4vImageProcessor):
+ pass
+
+
+class Glm46VVideoProcessor(Glm4vVideoProcessor):
+ def sample_frames(
+ self,
+ metadata: VideoMetadata,
+ fps: int | float | None = None,
+ **kwargs,
+ ):
+ if metadata is None or getattr(metadata, "fps", None) is None:
+ raise ValueError(
+ "Asked to sample frames per second but no video metadata was provided which is required when sampling in Glm46V. "
+ "Please pass in `VideoMetadata` object or set `do_sample_frames=False`"
+ )
+
+ total_frames = metadata.total_num_frames
+ max_frame_idx = total_frames - 1
+ duration = metadata.duration or round(max_frame_idx / metadata.fps) + 1
+
+ DYNAMIC_FPS_THRES = {30: 3, 300: 1, 2400: 0.5}
+ MAX_FRAME_COUNT_DYNAMIC = 640
+ MAX_DURATION = 2400
+ effective_duration = min(duration, MAX_DURATION)
+ if effective_duration <= 30:
+ target_fps = DYNAMIC_FPS_THRES[30]
+ elif effective_duration <= 300:
+ target_fps = DYNAMIC_FPS_THRES[300]
+ else:
+ target_fps = DYNAMIC_FPS_THRES[2400]
+ extract_t = int(effective_duration * target_fps * self.temporal_patch_size)
+ extract_t = min(extract_t, MAX_FRAME_COUNT_DYNAMIC)
+
+ duration_per_frame = 1 / metadata.fps
+ timestamps = [i * duration_per_frame for i in range(total_frames)]
+ max_second = int(duration)
+
+ if total_frames < extract_t:
+ frame_indices = np.linspace(0, total_frames - 1, extract_t, dtype=int).tolist()
+ else:
+ frame_indices = []
+ current_second = 0
+ inv_fps = 1 / (self.temporal_patch_size * target_fps)
+ for frame_index in range(total_frames):
+ if timestamps[frame_index] >= current_second:
+ current_second += inv_fps
+ frame_indices.append(frame_index)
+ if current_second >= max_second:
+ break
+
+ if len(frame_indices) < extract_t:
+ if len(frame_indices) == 0:
+ start, end = 0, max(total_frames - 1, 0)
+ else:
+ start, end = frame_indices[0], frame_indices[-1]
+ frame_indices = np.linspace(start, end, extract_t, dtype=int).tolist()
+ elif len(frame_indices) > extract_t:
+ frame_indices = np.linspace(0, total_frames - 1, extract_t, dtype=int).tolist()
+
+ seen, uniq = set(), []
+ for idx in frame_indices:
+ if idx not in seen:
+ seen.add(idx)
+ uniq.append(idx)
+
+ if len(uniq) & 1:
+ uniq.append(uniq[-1])
+
+ return np.array(uniq)
+
+
+__all__ = [
+ "Glm46VConfig",
+ "Glm46VModel",
+ "Glm46VPreTrainedModel",
+ "Glm46VForConditionalGeneration",
+ "Glm46VProcessor",
+ "Glm46VImageProcessor",
+ "Glm46VImageProcessorPil",
+ "Glm46VVideoProcessor",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm46v/processing_glm46v.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm46v/processing_glm46v.py
new file mode 100644
index 0000000000000000000000000000000000000000..9dcf7c4856e644417eceae69dc5654564ee36162
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm46v/processing_glm46v.py
@@ -0,0 +1,271 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/glm46v/modular_glm46v.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_glm46v.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2025 the HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+import numpy as np
+
+from ...image_processing_utils import BatchFeature
+from ...image_utils import ImageInput
+from ...processing_utils import MultiModalData, ProcessingKwargs, ProcessorMixin, Unpack
+from ...tokenization_utils_base import PreTokenizedInput, TextInput
+from ...utils import auto_docstring, logging
+from ...video_utils import VideoInput
+
+
+logger = logging.get_logger(__name__)
+
+
+class Glm46VProcessorKwargs(ProcessingKwargs, total=False):
+ _defaults = {
+ "text_kwargs": {
+ "padding": False,
+ "return_token_type_ids": False,
+ "return_mm_token_type_ids": True,
+ },
+ "videos_kwargs": {"return_metadata": True},
+ }
+
+
+@auto_docstring
+class Glm46VProcessor(ProcessorMixin):
+ def __init__(self, image_processor=None, tokenizer=None, video_processor=None, chat_template=None, **kwargs):
+ self.image_token = "<|image|>" if not hasattr(tokenizer, "image_token") else tokenizer.image_token
+ self.video_token = "<|video|>" if not hasattr(tokenizer, "video_token") else tokenizer.video_token
+ self.image_token_id = (
+ tokenizer.image_token_id
+ if getattr(tokenizer, "image_token_id", None)
+ else tokenizer.convert_tokens_to_ids(self.image_token)
+ )
+ self.video_token_id = (
+ tokenizer.video_token_id
+ if getattr(tokenizer, "video_token_id", None)
+ else tokenizer.convert_tokens_to_ids(self.video_token)
+ )
+ super().__init__(image_processor, tokenizer, video_processor, chat_template=chat_template)
+ self.video_start_id = tokenizer.convert_tokens_to_ids("<|begin_of_video|>")
+ self.video_end_id = tokenizer.convert_tokens_to_ids("<|end_of_video|>")
+
+ @auto_docstring
+ def __call__(
+ self,
+ images: ImageInput | None = None,
+ text: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] = None,
+ videos: VideoInput | None = None,
+ **kwargs: Unpack[Glm46VProcessorKwargs],
+ ) -> BatchFeature:
+ r"""
+ Returns:
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
+
+ - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
+ `None`).
+ - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
+ - **pixel_values_videos** -- Pixel values of videos to be fed to a model. Returned when `videos` is not `None`.
+ - **image_grid_thw** -- List of image 3D grid in LLM. Returned when `images` is not `None`.
+ - **video_grid_thw** -- List of video 3D grid in LLM. Returned when `videos` is not `None`.
+ """
+ output_kwargs = self._merge_kwargs(
+ Glm46VProcessorKwargs,
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
+ **kwargs,
+ )
+ if images is not None:
+ image_inputs = self.image_processor(images=images, **output_kwargs["images_kwargs"])
+ image_grid_thw = image_inputs["image_grid_thw"]
+ else:
+ image_inputs = {}
+ image_grid_thw = None
+
+ if videos is not None:
+ videos_inputs = self.video_processor(videos=videos, **output_kwargs["videos_kwargs"])
+ # If user has not requested video metadata, pop it
+ if not kwargs.get("return_metadata"):
+ video_metadata = videos_inputs.pop("video_metadata")
+ else:
+ video_metadata = videos_inputs["video_metadata"]
+ video_grid_thw = videos_inputs["video_grid_thw"]
+ else:
+ videos_inputs = {}
+ video_grid_thw = None
+
+ if not isinstance(text, list):
+ text = [text]
+
+ text = text.copy() # below lines change text in-place
+ if image_grid_thw is not None:
+ merge_length = self.image_processor.merge_size**2
+ index = 0
+ for i in range(len(text)):
+ while self.image_token in text[i]:
+ num_image_tokens = image_grid_thw[index].prod() // merge_length
+ text[i] = text[i].replace(self.image_token, "<|placeholder|>" * num_image_tokens, 1)
+ index += 1
+ text[i] = text[i].replace("<|placeholder|>", self.image_token)
+
+ if video_grid_thw is not None:
+ merge_length = self.video_processor.merge_size**2
+ video_index = 0
+ for i in range(len(text)):
+ while self.video_token in text[i]:
+ num_frames = video_grid_thw[video_index][0]
+ video_structure = ""
+
+ metadata = video_metadata[video_index]
+ if metadata.fps is None:
+ logger.warning_once(
+ "SmolVLM requires frame timestamps to construct prompts, but the `fps` of the input video could not be inferred. "
+ "Probably `video_metadata` was missing from inputs and you passed pre-sampled frames. "
+ "Defaulting to `fps=24`. Please provide `video_metadata` for more accurate results."
+ )
+ metadata.fps = 24 if metadata.fps is None else metadata.fps
+ timestamps = metadata.timestamps[::2] # mrope
+
+ unique_timestamps = []
+ for idx in range(0, len(timestamps)):
+ unique_timestamps.append(timestamps[idx])
+
+ selected_timestamps = unique_timestamps[:num_frames]
+ while len(selected_timestamps) < num_frames:
+ selected_timestamps.append(selected_timestamps[-1] if selected_timestamps else 0)
+
+ for frame_idx in range(num_frames):
+ timestamp_sec = selected_timestamps[frame_idx]
+ frame_structure = self.replace_frame_token_id(timestamp_sec)
+ video_structure += frame_structure
+
+ text[i] = text[i].replace(self.video_token, video_structure, 1)
+ num_image_tokens = (
+ video_grid_thw[video_index].prod() // merge_length // video_grid_thw[video_index][0]
+ )
+ for frame_idx in range(num_frames):
+ if self.image_token in text[i]:
+ text[i] = text[i].replace(self.image_token, "<|placeholder|>" * num_image_tokens, 1)
+
+ video_index += 1
+
+ text[i] = text[i].replace("<|placeholder|>", self.image_token)
+ return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None)
+ return_mm_token_type_ids = output_kwargs["text_kwargs"].pop("return_mm_token_type_ids", False)
+ text_inputs = self.tokenizer(text, **output_kwargs["text_kwargs"])
+ self._check_special_mm_tokens(text, text_inputs, modalities=["image", "video"])
+
+ if return_mm_token_type_ids:
+ text_inputs["mm_token_type_ids"] = self.create_mm_token_type_ids(text_inputs["input_ids"])
+ return BatchFeature(data={**text_inputs, **image_inputs, **videos_inputs}, tensor_type=return_tensors)
+
+ def _get_num_multimodal_tokens(self, image_sizes=None, video_sizes=None, **kwargs):
+ """
+ Computes the number of placeholder tokens needed for multimodal inputs with the given sizes.
+ Args:
+ image_sizes (`list[list[int]]`, *optional*):
+ The input sizes formatted as (height, width) per each image.
+ video_sizes (`list[list[int]]`, *optional*):
+ The input sizes formatted as (num_frames, height, width) per each video.
+ Returns:
+ `MultiModalData`: A `MultiModalData` object holding number of tokens per each of the provided
+ input modalities, along with other useful data.
+ """
+
+ vision_data = {}
+ if image_sizes is not None:
+ images_kwargs = Glm46VProcessorKwargs._defaults.get("images_kwargs", {})
+ images_kwargs.update(kwargs)
+ merge_size = images_kwargs.get("merge_size", None) or self.image_processor.merge_size
+
+ num_image_patches = [
+ self.image_processor.get_number_of_image_patches(*image_size, images_kwargs)
+ for image_size in image_sizes
+ ]
+ num_image_tokens = [(num_patches // merge_size**2) for num_patches in num_image_patches]
+ vision_data.update({"num_image_tokens": num_image_tokens, "num_image_patches": num_image_patches})
+
+ if video_sizes is not None:
+ videos_kwargs = Glm46VProcessorKwargs._defaults.get("videos_kwargs", {})
+ videos_kwargs.update(kwargs)
+ num_video_patches = [
+ self.video_processor.get_number_of_video_patches(*video_size, videos_kwargs)
+ for video_size in video_sizes
+ ]
+ num_video_tokens = [(num_patches // merge_size**2) for num_patches in num_video_patches]
+ vision_data["num_video_tokens"] = num_video_tokens
+
+ return MultiModalData(**vision_data)
+
+ def post_process_image_text_to_text(
+ self, generated_outputs, skip_special_tokens=True, clean_up_tokenization_spaces=False, **kwargs
+ ):
+ """
+ Post-process the output of the model to decode the text.
+
+ Args:
+ generated_outputs (`torch.Tensor` or `np.ndarray`):
+ The output of the model `generate` function. The output is expected to be a tensor of shape `(batch_size, sequence_length)`
+ or `(sequence_length,)`.
+ skip_special_tokens (`bool`, *optional*, defaults to `True`):
+ Whether or not to remove special tokens in the output. Argument passed to the tokenizer's `batch_decode` method.
+ clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`):
+ Whether or not to clean up the tokenization spaces. Argument passed to the tokenizer's `batch_decode` method.
+ **kwargs:
+ Additional arguments to be passed to the tokenizer's `batch_decode method`.
+
+ Returns:
+ `list[str]`: The decoded text.
+ """
+ return self.tokenizer.batch_decode(
+ generated_outputs,
+ skip_special_tokens=skip_special_tokens,
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
+ **kwargs,
+ )
+
+ @property
+ def model_input_names(self):
+ model_input_names = super().model_input_names
+ model_input_names.append("mm_token_type_ids")
+ return model_input_names
+
+ def create_mm_token_type_ids(self, input_ids: list) -> list[list[int]]:
+ # We have to iterate for each list separately because inputs
+ # might be non-padded lists and we can't cast numpy on that!
+ # Then cast numpy as each input for faster indexing
+ mm_token_type_ids = []
+ for input in input_ids:
+ array_ids = np.array(input)
+ mm_token_types = np.zeros_like(input)
+
+ # Replace 0 -> 2 only inside video segments because Glm46V
+ # uses the same special token to denote images and video
+ # Otherwise replace 0 -> 1 for image modality
+ starts = np.cumsum(array_ids == self.video_start_id, axis=0)
+ ends = np.cumsum(array_ids == self.video_end_id, axis=0)
+ is_video_modality = starts > ends
+
+ mm_token_types[(array_ids == self.image_token_id) & is_video_modality] = 2
+ mm_token_types[(array_ids == self.image_token_id) & (~is_video_modality)] = 1
+ mm_token_type_ids.append(mm_token_types.tolist())
+ return mm_token_type_ids
+
+ def replace_frame_token_id(self, timestamp_sec):
+ return f"<|begin_of_image|>{self.image_token}<|end_of_image|>{timestamp_sec:.1f} seconds"
+
+
+__all__ = ["Glm46VProcessor"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm46v/video_processing_glm46v.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm46v/video_processing_glm46v.py
new file mode 100644
index 0000000000000000000000000000000000000000..5ca284d618561f742601b9180b0d944751cd2669
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm46v/video_processing_glm46v.py
@@ -0,0 +1,273 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/glm46v/modular_glm46v.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_glm46v.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2025 the HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+import numpy as np
+import torch
+from torchvision.transforms.v2 import functional as tvF
+
+from ...image_processing_utils import BatchFeature
+from ...image_utils import (
+ OPENAI_CLIP_MEAN,
+ OPENAI_CLIP_STD,
+ ChannelDimension,
+ PILImageResampling,
+ SizeDict,
+ get_image_size,
+)
+from ...processing_utils import Unpack, VideosKwargs
+from ...utils import TensorType, add_start_docstrings
+from ...video_processing_utils import BASE_VIDEO_PROCESSOR_DOCSTRING, BaseVideoProcessor
+from ...video_utils import VideoMetadata, group_videos_by_shape, reorder_videos
+from .image_processing_glm46v import smart_resize
+
+
+class Glm46VVideoProcessorInitKwargs(VideosKwargs, total=False):
+ max_image_size: dict[str, int]
+ patch_size: int
+ temporal_patch_size: int
+ merge_size: int
+ max_duration: int
+
+
+@add_start_docstrings(
+ "Constructs a fast GLM-4V image processor that dynamically resizes videos based on the original videos.",
+ BASE_VIDEO_PROCESSOR_DOCSTRING,
+ """
+ patch_size (`int`, *optional*, defaults to 14):
+ The spacial patch size of the vision encoder.
+ temporal_patch_size (`int`, *optional*, defaults to 2):
+ The temporal patch size of the vision encoder.
+ merge_size (`int`, *optional*, defaults to 2):
+ The merge size of the vision encoder to llm encoder.
+ """,
+)
+class Glm46VVideoProcessor(BaseVideoProcessor):
+ resample = PILImageResampling.BICUBIC
+ size = {"shortest_edge": 112 * 112, "longest_edge": 28 * 28 * 2 * 30000}
+ max_image_size = {"longest_edge": 28 * 28 * 2 * 30000}
+ image_mean = OPENAI_CLIP_MEAN
+ image_std = OPENAI_CLIP_STD
+ do_resize = True
+ do_rescale = True
+ do_normalize = True
+ do_convert_rgb = True
+ do_sample_frames = True
+ patch_size = 14
+ temporal_patch_size = 2
+ max_duration = 300
+ merge_size = 2
+ valid_kwargs = Glm46VVideoProcessorInitKwargs
+ num_frames = 16
+ fps = 2
+
+ model_input_names = ["pixel_values_videos", "video_grid_thw"]
+
+ def __init__(self, **kwargs: Unpack[Glm46VVideoProcessorInitKwargs]):
+ super().__init__(**kwargs)
+
+ def _standardize_kwargs(self, **kwargs) -> dict:
+ """
+ Update kwargs that need further processing before being validated
+ Can be overridden by subclasses to customize the processing of kwargs.
+ """
+ kwargs = super()._standardize_kwargs(**kwargs)
+ size = kwargs.get("size", self.size)
+ if not size.shortest_edge or not size.longest_edge:
+ raise ValueError("size must contain 'shortest_edge' and 'longest_edge' keys.")
+ return kwargs
+
+ def sample_frames(
+ self,
+ metadata: VideoMetadata,
+ fps: int | float | None = None,
+ **kwargs,
+ ):
+ """
+ Args:
+ metadata (`VideoMetadata`):
+ Metadata of the video containing information about total duration, fps and total number of frames.
+ fps (`int` or `float`, *optional*):
+ Target frames to sample per second. Defaults to `self.fps`.
+ Returns:
+ np.ndarray:
+ Indices to sample video frames.
+ """
+ if metadata is None or getattr(metadata, "fps", None) is None:
+ raise ValueError(
+ "Asked to sample frames per second but no video metadata was provided which is required when sampling in Glm46V. "
+ "Please pass in `VideoMetadata` object or set `do_sample_frames=False`"
+ )
+
+ total_frames = metadata.total_num_frames
+ max_frame_idx = total_frames - 1
+ duration = metadata.duration or round(max_frame_idx / metadata.fps) + 1
+
+ DYNAMIC_FPS_THRES = {30: 3, 300: 1, 2400: 0.5}
+ MAX_FRAME_COUNT_DYNAMIC = 640
+ MAX_DURATION = 2400
+ effective_duration = min(duration, MAX_DURATION)
+ if effective_duration <= 30:
+ target_fps = DYNAMIC_FPS_THRES[30]
+ elif effective_duration <= 300:
+ target_fps = DYNAMIC_FPS_THRES[300]
+ else:
+ target_fps = DYNAMIC_FPS_THRES[2400]
+ extract_t = int(effective_duration * target_fps * self.temporal_patch_size)
+ extract_t = min(extract_t, MAX_FRAME_COUNT_DYNAMIC)
+
+ duration_per_frame = 1 / metadata.fps
+ timestamps = [i * duration_per_frame for i in range(total_frames)]
+ max_second = int(duration)
+
+ if total_frames < extract_t:
+ frame_indices = np.linspace(0, total_frames - 1, extract_t, dtype=int).tolist()
+ else:
+ frame_indices = []
+ current_second = 0
+ inv_fps = 1 / (self.temporal_patch_size * target_fps)
+ for frame_index in range(total_frames):
+ if timestamps[frame_index] >= current_second:
+ current_second += inv_fps
+ frame_indices.append(frame_index)
+ if current_second >= max_second:
+ break
+
+ if len(frame_indices) < extract_t:
+ if len(frame_indices) == 0:
+ start, end = 0, max(total_frames - 1, 0)
+ else:
+ start, end = frame_indices[0], frame_indices[-1]
+ frame_indices = np.linspace(start, end, extract_t, dtype=int).tolist()
+ elif len(frame_indices) > extract_t:
+ frame_indices = np.linspace(0, total_frames - 1, extract_t, dtype=int).tolist()
+
+ seen, uniq = set(), []
+ for idx in frame_indices:
+ if idx not in seen:
+ seen.add(idx)
+ uniq.append(idx)
+
+ if len(uniq) & 1:
+ uniq.append(uniq[-1])
+
+ return np.array(uniq)
+
+ def _preprocess(
+ self,
+ videos: list[torch.Tensor],
+ do_convert_rgb: bool = True,
+ do_resize: bool = True,
+ size: SizeDict | None = None,
+ resample: "PILImageResampling | tvF.InterpolationMode | int | None" = PILImageResampling.BICUBIC,
+ do_rescale: bool = True,
+ rescale_factor: float = 1 / 255.0,
+ do_normalize: bool = True,
+ image_mean: float | list[float] | None = None,
+ image_std: float | list[float] | None = None,
+ patch_size: int | None = None,
+ temporal_patch_size: int | None = None,
+ merge_size: int | None = None,
+ return_tensors: str | TensorType | None = None,
+ **kwargs,
+ ):
+ grouped_videos, grouped_videos_index = group_videos_by_shape(videos)
+ resized_videos_grouped = {}
+
+ for shape, stacked_videos in grouped_videos.items():
+ B, T, C, H, W = stacked_videos.shape
+ num_frames, height, width = T, H, W
+ if do_resize:
+ resized_height, resized_width = smart_resize(
+ num_frames=num_frames,
+ height=height,
+ width=width,
+ temporal_factor=temporal_patch_size,
+ factor=patch_size * merge_size,
+ min_pixels=size.shortest_edge,
+ max_pixels=size.longest_edge,
+ )
+ stacked_videos = stacked_videos.view(B * T, C, H, W)
+ stacked_videos = self.resize(
+ stacked_videos,
+ size=SizeDict(height=resized_height, width=resized_width),
+ resample=resample,
+ )
+ stacked_videos = stacked_videos.view(B, T, C, resized_height, resized_width)
+ resized_videos_grouped[shape] = stacked_videos
+ resized_videos = reorder_videos(resized_videos_grouped, grouped_videos_index)
+
+ # Group videos by size for further processing
+ # Needed in case do_resize is False, or resize returns videos with different sizes
+ grouped_videos, grouped_videos_index = group_videos_by_shape(resized_videos)
+ processed_videos_grouped = {}
+ processed_grids = {}
+ for shape, stacked_videos in grouped_videos.items():
+ resized_height, resized_width = get_image_size(stacked_videos[0], channel_dim=ChannelDimension.FIRST)
+
+ # Fused rescale and normalize
+ stacked_videos = self.rescale_and_normalize(
+ stacked_videos, do_rescale, rescale_factor, do_normalize, image_mean, image_std
+ )
+ patches = stacked_videos
+
+ # Check that videos have `num_frames` divisible by `temporal_patch_size`
+ if patches.shape[1] % temporal_patch_size != 0:
+ repeats = patches[:, -1:].repeat(1, temporal_patch_size - 1, 1, 1, 1)
+ patches = torch.cat([patches, repeats], dim=1)
+ batch_size, grid_t, channel = patches.shape[:3]
+ grid_t = grid_t // temporal_patch_size
+ grid_h, grid_w = resized_height // patch_size, resized_width // patch_size
+
+ patches = patches.view(
+ batch_size,
+ grid_t,
+ temporal_patch_size,
+ channel,
+ grid_h // merge_size,
+ merge_size,
+ patch_size,
+ grid_w // merge_size,
+ merge_size,
+ patch_size,
+ )
+ patches = patches.permute(0, 1, 4, 7, 5, 8, 3, 2, 6, 9)
+ flatten_patches = patches.reshape(
+ batch_size,
+ grid_t * grid_h * grid_w,
+ channel * temporal_patch_size * patch_size * patch_size,
+ )
+
+ processed_videos_grouped[shape] = flatten_patches
+ processed_grids[shape] = [[grid_t, grid_h, grid_w]] * batch_size
+
+ processed_videos = reorder_videos(processed_videos_grouped, grouped_videos_index)
+ processed_grids = reorder_videos(processed_grids, grouped_videos_index)
+ pixel_values_videos = torch.cat(processed_videos, dim=0)
+ video_grid_thw = torch.tensor(processed_grids)
+ data = {
+ "pixel_values_videos": pixel_values_videos,
+ "video_grid_thw": video_grid_thw,
+ }
+
+ return BatchFeature(data=data, tensor_type=return_tensors)
+
+
+__all__ = ["Glm46VVideoProcessor"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm4_moe_lite/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm4_moe_lite/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..54baf09a1ec8bbfcbcfe7b8fdcb518adb64d5962
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm4_moe_lite/__init__.py
@@ -0,0 +1,28 @@
+# Copyright 2025 the HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_glm4_moe_lite import *
+ from .modeling_glm4_moe_lite import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm4_moe_lite/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm4_moe_lite/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f46a30473ed18141d8c38ce088b25df6fd579341
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm4_moe_lite/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm4_moe_lite/__pycache__/configuration_glm4_moe_lite.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm4_moe_lite/__pycache__/configuration_glm4_moe_lite.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..27569570fbe517c767d36a745efa460de60afc09
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm4_moe_lite/__pycache__/configuration_glm4_moe_lite.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm4_moe_lite/__pycache__/modeling_glm4_moe_lite.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm4_moe_lite/__pycache__/modeling_glm4_moe_lite.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6aefb14998f01e4c7c1cc7f95434d25ea697f872
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm4_moe_lite/__pycache__/modeling_glm4_moe_lite.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm4_moe_lite/__pycache__/modular_glm4_moe_lite.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm4_moe_lite/__pycache__/modular_glm4_moe_lite.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fba8667ba813d44f50c55bf5b932173f8f87cd61
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm4_moe_lite/__pycache__/modular_glm4_moe_lite.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm4_moe_lite/configuration_glm4_moe_lite.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm4_moe_lite/configuration_glm4_moe_lite.py
new file mode 100644
index 0000000000000000000000000000000000000000..a9518ed9c5d3a2b1b603c4e6f5d90446f0e84c5a
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm4_moe_lite/configuration_glm4_moe_lite.py
@@ -0,0 +1,119 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/glm4_moe_lite/modular_glm4_moe_lite.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_glm4_moe_lite.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2025 the HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...modeling_rope_utils import RopeParameters
+from ...utils import auto_docstring
+
+
+@auto_docstring(checkpoint="zai-org/GLM-4.5")
+@strict
+class Glm4MoeLiteConfig(PreTrainedConfig):
+ r"""
+ n_group (`int`, *optional*, defaults to 1):
+ Number of groups for routed experts.
+ rope_interleave (`bool`, *optional*, defaults to `True`):
+ Whether to interleave the rotary position embeddings.
+ mlp_layer_types (`list`, *optional*):
+ MLP (Moe vs Dense) pattern for each layer.
+
+ Example:
+
+ ```python
+ >>> from transformers import Glm4MoeLiteModel, Glm4MoeLiteConfig
+
+ >>> # Initializing a Deepseek-V3 style configuration
+ >>> configuration = Glm4MoeLiteConfig()
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "glm4_moe_lite"
+ keys_to_ignore_at_inference = ["past_key_values"]
+ base_model_tp_plan = {
+ "layers.*.self_attn.q_b_proj": "colwise",
+ "layers.*.self_attn.kv_a_proj_with_mqa": "mla_kv_a_proj",
+ "layers.*.self_attn.kv_b_proj": "colwise",
+ "layers.*.self_attn.o_proj": "rowwise",
+ "layers.*.mlp.experts.gate_up_proj": "packed_colwise",
+ "layers.*.mlp.experts.down_proj": "rowwise",
+ "layers.*.mlp.experts": "moe_tp_experts",
+ "layers.*.mlp.gate_proj": "colwise",
+ "layers.*.mlp.up_proj": "colwise",
+ "layers.*.mlp.down_proj": "rowwise",
+ }
+ base_model_pp_plan = {
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
+ "norm": (["hidden_states"], ["hidden_states"]),
+ }
+ attribute_map = {
+ "num_local_experts": "n_routed_experts",
+ "head_dim": "qk_rope_head_dim",
+ }
+
+ vocab_size: int = 154880
+ hidden_size: int = 2048
+ intermediate_size: int = 10240
+ moe_intermediate_size: int = 1536
+ num_hidden_layers: int = 47
+ num_attention_heads: int = 20
+ num_key_value_heads: int = 20
+ n_shared_experts: int = 1
+ n_routed_experts: int = 64
+ routed_scaling_factor: float = 1.8
+ kv_lora_rank: int = 512
+ q_lora_rank: int | None = 768
+ qk_rope_head_dim: int = 64
+ v_head_dim: int = 256
+ qk_nope_head_dim: int = 192
+ n_group: int = 1
+ topk_group: int = 1
+ num_experts_per_tok: int = 4
+ norm_topk_prob: bool = True
+ hidden_act: str = "silu"
+ max_position_embeddings: int = 202752
+ initializer_range: float = 0.02
+ rms_norm_eps: float = 1e-5
+ use_cache: bool = True
+ pad_token_id: int | None = None
+ bos_token_id: int | None = 0
+ eos_token_id: int | list[int] | None = 1
+ pretraining_tp: int = 1
+ tie_word_embeddings: bool = False
+ rope_parameters: RopeParameters | dict | None = None
+ rope_interleave: bool = True
+ mlp_layer_types: list[str] | None = None
+ attention_bias: bool = False
+ attention_dropout: float | int = 0.0
+
+ def __post_init__(self, **kwargs):
+ # Default to MoE from the second layer and on
+ if self.mlp_layer_types is None:
+ self.mlp_layer_types = ["dense"] + ["sparse"] * (self.num_hidden_layers - 1)
+ self.qk_head_dim = self.qk_nope_head_dim + self.qk_rope_head_dim
+ super().__post_init__(**kwargs)
+
+
+__all__ = ["Glm4MoeLiteConfig"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm4_moe_lite/modeling_glm4_moe_lite.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm4_moe_lite/modeling_glm4_moe_lite.py
new file mode 100644
index 0000000000000000000000000000000000000000..0b8ccc865775368e48b1457e754075f7557bffc5
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm4_moe_lite/modeling_glm4_moe_lite.py
@@ -0,0 +1,725 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/glm4_moe_lite/modular_glm4_moe_lite.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_glm4_moe_lite.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2025 the HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+import math
+from collections.abc import Callable
+from typing import Optional
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...cache_utils import Cache, DynamicCache
+from ...generation import GenerationMixin
+from ...integrations import use_experts_implementation, use_kernel_forward_from_hub, use_kernel_func_from_hub
+from ...masking_utils import create_causal_mask
+from ...modeling_flash_attention_utils import FlashAttentionKwargs
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
+from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import TransformersKwargs, auto_docstring, can_return_tuple
+from ...utils.generic import is_flash_attention_requested, maybe_autocast, merge_with_config_defaults
+from ...utils.output_capturing import capture_outputs
+from .configuration_glm4_moe_lite import Glm4MoeLiteConfig
+
+
+class Glm4MoeLiteRotaryEmbedding(nn.Module):
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
+
+ def __init__(self, config: Glm4MoeLiteConfig, device=None):
+ super().__init__()
+ self.max_seq_len_cached = config.max_position_embeddings
+ self.original_max_seq_len = config.max_position_embeddings
+
+ self.config = config
+
+ self.rope_type = self.config.rope_parameters["rope_type"]
+ rope_init_fn: Callable = self.compute_default_rope_parameters
+ if self.rope_type != "default":
+ rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
+ inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
+
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
+ self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
+
+ @staticmethod
+ def compute_default_rope_parameters(
+ config: Glm4MoeLiteConfig | None = None,
+ device: Optional["torch.device"] = None,
+ seq_len: int | None = None,
+ ) -> tuple["torch.Tensor", float]:
+ """
+ Computes the inverse frequencies according to the original RoPE implementation
+ Args:
+ config ([`~transformers.PreTrainedConfig`]):
+ The model configuration.
+ device (`torch.device`):
+ The device to use for initialization of the inverse frequencies.
+ seq_len (`int`, *optional*):
+ The current sequence length. Unused for this type of RoPE.
+ Returns:
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
+ """
+ base = config.rope_parameters["rope_theta"]
+ partial_rotary_factor = config.rope_parameters.get("partial_rotary_factor", 1.0)
+ head_dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
+ dim = int(head_dim * partial_rotary_factor)
+
+ attention_factor = 1.0 # Unused in this type of RoPE
+
+ # Compute the inverse frequencies
+ inv_freq = 1.0 / (
+ base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
+ )
+ return inv_freq, attention_factor
+
+ @torch.no_grad()
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
+ def forward(self, x, position_ids):
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
+ position_ids_expanded = position_ids[:, None, :].float()
+
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
+ with maybe_autocast(device_type=device_type, enabled=False): # Force float32
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
+ emb = torch.cat((freqs, freqs), dim=-1)
+ cos = emb.cos() * self.attention_scaling
+ sin = emb.sin() * self.attention_scaling
+
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
+
+
+def rotate_half(x):
+ """Rotates half the hidden dims of the input."""
+ x1 = x[..., : x.shape[-1] // 2]
+ x2 = x[..., x.shape[-1] // 2 :]
+ return torch.cat((-x2, x1), dim=-1)
+
+
+@use_kernel_func_from_hub("rotary_pos_emb")
+def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
+ """Applies Rotary Position Embedding to the query and key tensors.
+
+ Args:
+ q (`torch.Tensor`): The query tensor.
+ k (`torch.Tensor`): The key tensor.
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
+ Returns:
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
+ """
+ cos = cos.unsqueeze(unsqueeze_dim)
+ sin = sin.unsqueeze(unsqueeze_dim)
+ q_embed = (q * cos) + (rotate_half(q) * sin)
+ k_embed = (k * cos) + (rotate_half(k) * sin)
+ return q_embed, k_embed
+
+
+def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
+ """
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
+ """
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
+ if n_rep == 1:
+ return hidden_states
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
+
+
+def eager_attention_forward(
+ module: nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: torch.Tensor | None,
+ scaling: float,
+ dropout: float = 0.0,
+ **kwargs: Unpack[TransformersKwargs],
+):
+ key_states = repeat_kv(key, module.num_key_value_groups)
+ value_states = repeat_kv(value, module.num_key_value_groups)
+
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
+ if attention_mask is not None:
+ attn_weights = attn_weights + attention_mask
+
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
+ attn_output = torch.matmul(attn_weights, value_states)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+
+ return attn_output, attn_weights
+
+
+def apply_rotary_pos_emb_interleave(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
+ r"""
+ TODO let's just use the original freqcis computation to not have the view
+ transpose + reshape! This is not optimized!
+ Applies Rotary Position Embedding to the query and key tensors.
+
+ Args:
+ q (`torch.Tensor`): The query tensor.
+ k (`torch.Tensor`): The key tensor.
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
+ position_ids (`torch.Tensor`):
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
+ used to pass offsetted position ids when working with a KV-cache.
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
+ Returns:
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
+ """
+ cos = cos.unsqueeze(unsqueeze_dim)
+ sin = sin.unsqueeze(unsqueeze_dim)
+
+ b, h, s, d = q.shape
+ q = q.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
+
+ b, h, s, d = k.shape
+ k = k.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
+
+ q_embed = (q * cos) + (rotate_half(q) * sin)
+ k_embed = (k * cos) + (rotate_half(k) * sin)
+ return q_embed, k_embed
+
+
+def yarn_get_mscale(scale=1, mscale=1):
+ if scale <= 1:
+ return 1.0
+ return 0.1 * mscale * math.log(scale) + 1.0
+
+
+class Glm4MoeLiteAttention(nn.Module):
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
+
+ def __init__(self, config: Glm4MoeLiteConfig, layer_idx: int):
+ super().__init__()
+ self.config = config
+ self.layer_idx = layer_idx
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
+ self.attention_dropout = config.attention_dropout
+ self.num_heads = config.num_attention_heads
+
+ self.q_lora_rank = config.q_lora_rank
+ self.qk_rope_head_dim = config.qk_rope_head_dim
+ self.kv_lora_rank = config.kv_lora_rank
+ self.v_head_dim = config.v_head_dim
+ self.qk_nope_head_dim = config.qk_nope_head_dim
+ self.qk_head_dim = config.qk_head_dim
+
+ self.is_causal = True
+ if self.q_lora_rank is None:
+ self.q_proj = nn.Linear(config.hidden_size, self.num_heads * self.qk_head_dim, bias=False)
+ else:
+ self.q_a_proj = nn.Linear(config.hidden_size, config.q_lora_rank, bias=config.attention_bias)
+ self.q_a_layernorm = Glm4MoeLiteRMSNorm(config.q_lora_rank)
+ self.q_b_proj = nn.Linear(config.q_lora_rank, self.num_heads * self.qk_head_dim, bias=False)
+
+ self.kv_a_proj_with_mqa = nn.Linear(
+ config.hidden_size,
+ self.kv_lora_rank + self.qk_rope_head_dim,
+ bias=config.attention_bias,
+ )
+ self.kv_a_layernorm = Glm4MoeLiteRMSNorm(self.kv_lora_rank)
+ self.kv_b_proj = nn.Linear(
+ self.kv_lora_rank,
+ self.num_heads * (self.qk_nope_head_dim + self.v_head_dim),
+ bias=False,
+ )
+
+ self.o_proj = nn.Linear(
+ self.num_heads * self.v_head_dim,
+ config.hidden_size,
+ bias=config.attention_bias,
+ )
+
+ self.scaling = self.qk_head_dim ** (-0.5)
+ if self.config.rope_parameters.get("rope_type", "default") != "default":
+ mscale_all_dim = self.config.rope_parameters.get("mscale_all_dim", 0)
+ scaling_factor = self.config.rope_parameters["factor"]
+ if mscale_all_dim:
+ mscale = yarn_get_mscale(scaling_factor, mscale_all_dim)
+ self.scaling = self.scaling * mscale * mscale
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
+ attention_mask: torch.Tensor | None,
+ past_key_values: Cache | None = None,
+ **kwargs: Unpack[FlashAttentionKwargs],
+ ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
+ batch_size, seq_length = hidden_states.shape[:-1]
+ query_shape = (batch_size, seq_length, -1, self.qk_head_dim)
+ key_shape = (batch_size, seq_length, -1, self.qk_nope_head_dim + self.v_head_dim)
+
+ if self.q_lora_rank is None:
+ q_states = self.q_proj(hidden_states)
+ else:
+ q_states = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
+ q_states = q_states.view(query_shape).transpose(1, 2)
+ q_pass, q_rot = torch.split(q_states, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1)
+
+ compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
+ k_pass, k_rot = torch.split(compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1)
+
+ k_pass = self.kv_b_proj(self.kv_a_layernorm(k_pass)).view(key_shape).transpose(1, 2)
+ k_pass, value_states = torch.split(k_pass, [self.qk_nope_head_dim, self.v_head_dim], dim=-1)
+
+ k_rot = k_rot.view(batch_size, 1, seq_length, self.qk_rope_head_dim)
+
+ cos, sin = position_embeddings
+ if self.config.rope_interleave: # support using interleaved weights for efficiency
+ q_rot, k_rot = apply_rotary_pos_emb_interleave(q_rot, k_rot, cos, sin)
+ else:
+ q_rot, k_rot = apply_rotary_pos_emb(q_rot, k_rot, cos, sin)
+ k_rot = k_rot.expand(*k_pass.shape[:-1], -1)
+
+ query_states = torch.cat((q_pass, q_rot), dim=-1)
+ key_states = torch.cat((k_pass, k_rot), dim=-1)
+
+ if past_key_values is not None:
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
+
+ if is_flash_attention_requested(self.config) and self.qk_head_dim != self.v_head_dim:
+ value_states = F.pad(value_states, [0, self.qk_head_dim - self.v_head_dim])
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_states,
+ key_states,
+ value_states,
+ attention_mask,
+ dropout=0.0 if not self.training else self.attention_dropout,
+ scaling=self.scaling,
+ **kwargs,
+ )
+
+ if is_flash_attention_requested(self.config) and self.qk_head_dim != self.v_head_dim:
+ attn_output = attn_output[:, :, :, : self.v_head_dim]
+
+ attn_output = attn_output.reshape(batch_size, seq_length, -1).contiguous()
+ attn_output = self.o_proj(attn_output)
+ return attn_output, attn_weights
+
+
+class Glm4MoeLiteMLP(nn.Module):
+ def __init__(self, config, intermediate_size=None):
+ super().__init__()
+ self.config = config
+ self.hidden_size = config.hidden_size
+ self.intermediate_size = config.intermediate_size if intermediate_size is None else intermediate_size
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
+ self.act_fn = ACT2FN[config.hidden_act]
+
+ def forward(self, x):
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
+ return down_proj
+
+
+class Glm4MoeLiteTopkRouter(nn.Module):
+ def __init__(self, config: Glm4MoeLiteConfig):
+ super().__init__()
+ self.config = config
+ self.top_k = config.num_experts_per_tok
+ self.n_routed_experts = config.n_routed_experts
+ self.routed_scaling_factor = config.routed_scaling_factor
+ self.n_group = config.n_group
+ self.topk_group = config.topk_group
+ self.norm_topk_prob = config.norm_topk_prob
+
+ self.weight = nn.Parameter(torch.empty((self.n_routed_experts, config.hidden_size)))
+ self.register_buffer("e_score_correction_bias", torch.zeros((self.n_routed_experts), dtype=torch.float32))
+
+ def forward(self, hidden_states):
+ hidden_states = hidden_states.view(-1, self.config.hidden_size)
+ router_logits = F.linear(hidden_states.type(torch.float32), self.weight.type(torch.float32))
+ return router_logits
+
+
+@use_kernel_forward_from_hub("RMSNorm")
+class Glm4MoeLiteRMSNorm(nn.Module):
+ def __init__(self, hidden_size, eps: float = 1e-6) -> None:
+ """
+ Glm4MoeLiteRMSNorm is equivalent to T5LayerNorm
+ """
+ super().__init__()
+ self.weight = nn.Parameter(torch.ones(hidden_size))
+ self.variance_epsilon = eps
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ input_dtype = hidden_states.dtype
+ hidden_states = hidden_states.to(torch.float32)
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
+ return self.weight * hidden_states.to(input_dtype)
+
+ def extra_repr(self):
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
+
+
+@use_experts_implementation
+class Glm4MoeLiteNaiveMoe(nn.Module):
+ """Collection of expert weights stored as 3D tensors."""
+
+ def __init__(self, config):
+ super().__init__()
+ self.num_experts = config.num_local_experts
+ self.hidden_dim = config.hidden_size
+ self.intermediate_dim = config.moe_intermediate_size
+ self.gate_up_proj = nn.Parameter(torch.empty(self.num_experts, 2 * self.intermediate_dim, self.hidden_dim))
+ self.down_proj = nn.Parameter(torch.empty(self.num_experts, self.hidden_dim, self.intermediate_dim))
+ self.act_fn = ACT2FN[config.hidden_act]
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ top_k_index: torch.Tensor,
+ top_k_weights: torch.Tensor,
+ ) -> torch.Tensor:
+ final_hidden_states = torch.zeros_like(hidden_states)
+ with torch.no_grad():
+ expert_mask = torch.nn.functional.one_hot(top_k_index, num_classes=self.num_experts)
+ expert_mask = expert_mask.permute(2, 1, 0)
+ expert_hit = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero()
+
+ for expert_idx in expert_hit:
+ expert_idx = expert_idx[0]
+ if expert_idx == self.num_experts:
+ continue
+ top_k_pos, token_idx = torch.where(expert_mask[expert_idx])
+ current_state = hidden_states[token_idx]
+ gate, up = nn.functional.linear(current_state, self.gate_up_proj[expert_idx]).chunk(2, dim=-1)
+ current_hidden_states = self.act_fn(gate) * up
+ current_hidden_states = nn.functional.linear(current_hidden_states, self.down_proj[expert_idx])
+ current_hidden_states = current_hidden_states * top_k_weights[token_idx, top_k_pos, None]
+ final_hidden_states.index_add_(0, token_idx, current_hidden_states.to(final_hidden_states.dtype))
+
+ return final_hidden_states
+
+
+class Glm4MoeLiteMoE(nn.Module):
+ """
+ A mixed expert module containing shared experts.
+ """
+
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.experts = Glm4MoeLiteNaiveMoe(config)
+ self.gate = Glm4MoeLiteTopkRouter(config)
+ self.shared_experts = Glm4MoeLiteMLP(
+ config=config, intermediate_size=config.moe_intermediate_size * config.n_shared_experts
+ )
+ self.n_routed_experts = config.n_routed_experts
+ self.n_group = config.n_group
+ self.topk_group = config.topk_group
+ self.norm_topk_prob = config.norm_topk_prob
+ self.routed_scaling_factor = config.routed_scaling_factor
+ self.top_k = config.num_experts_per_tok
+
+ def route_tokens_to_experts(self, router_logits):
+ router_logits = router_logits.sigmoid()
+ router_logits_for_choice = router_logits + self.gate.e_score_correction_bias
+ group_scores = (
+ router_logits_for_choice.view(-1, self.n_group, self.n_routed_experts // self.n_group)
+ .topk(2, dim=-1)[0]
+ .sum(dim=-1)
+ )
+ group_idx = torch.topk(group_scores, k=self.topk_group, dim=-1, sorted=False)[1]
+ group_mask = torch.zeros_like(group_scores)
+ group_mask.scatter_(1, group_idx, 1)
+ score_mask = (
+ group_mask.unsqueeze(-1)
+ .expand(-1, self.n_group, self.n_routed_experts // self.n_group)
+ .reshape(-1, self.n_routed_experts)
+ )
+ scores_for_choice = router_logits_for_choice.masked_fill(~score_mask.bool(), float("-inf"))
+ topk_indices = torch.topk(scores_for_choice, k=self.top_k, dim=-1, sorted=False)[1]
+ topk_weights = router_logits.gather(1, topk_indices)
+ if self.norm_topk_prob:
+ denominator = topk_weights.sum(dim=-1, keepdim=True) + 1e-20
+ topk_weights /= denominator
+ topk_weights = topk_weights * self.routed_scaling_factor
+ return topk_indices, topk_weights
+
+ def forward(self, hidden_states):
+ residuals = hidden_states
+ orig_shape = hidden_states.shape
+ router_logits = self.gate(hidden_states)
+ topk_indices, topk_weights = self.route_tokens_to_experts(router_logits)
+ hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
+ hidden_states = self.experts(hidden_states, topk_indices, topk_weights).view(*orig_shape)
+ hidden_states = hidden_states + self.shared_experts(residuals)
+ return hidden_states
+
+
+class Glm4MoeLiteDecoderLayer(GradientCheckpointingLayer):
+ def __init__(self, config: Glm4MoeLiteConfig, layer_idx: int):
+ super().__init__()
+ self.hidden_size = config.hidden_size
+ self.self_attn = Glm4MoeLiteAttention(config, layer_idx)
+
+ if config.mlp_layer_types[layer_idx] == "sparse":
+ self.mlp = Glm4MoeLiteMoE(config)
+ else:
+ self.mlp = Glm4MoeLiteMLP(config)
+
+ self.input_layernorm = Glm4MoeLiteRMSNorm(config.hidden_size, config.rms_norm_eps)
+ self.post_attention_layernorm = Glm4MoeLiteRMSNorm(config.hidden_size, config.rms_norm_eps)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ use_cache: bool | None = False,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.Tensor:
+ residual = hidden_states
+ hidden_states = self.input_layernorm(hidden_states)
+ # Self Attention
+ hidden_states, _ = self.self_attn(
+ hidden_states=hidden_states,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ position_embeddings=position_embeddings,
+ **kwargs,
+ )
+ hidden_states = residual + hidden_states
+
+ # Fully Connected
+ residual = hidden_states
+ hidden_states = self.post_attention_layernorm(hidden_states)
+ hidden_states = self.mlp(hidden_states)
+ hidden_states = residual + hidden_states
+ return hidden_states
+
+
+@auto_docstring
+class Glm4MoeLitePreTrainedModel(PreTrainedModel):
+ config: Glm4MoeLiteConfig
+ base_model_prefix = "model"
+ supports_gradient_checkpointing = True
+ _no_split_modules = ["Glm4MoeLiteDecoderLayer"]
+ _skip_keys_device_placement = ["past_key_values"]
+ _supports_flash_attn = True
+ _supports_sdpa = True
+ _supports_flex_attn = True
+
+ _can_compile_fullgraph = True
+ _supports_attention_backend = True
+ _can_record_outputs = {
+ "hidden_states": Glm4MoeLiteDecoderLayer,
+ "attentions": Glm4MoeLiteAttention,
+ }
+ _keep_in_fp32_modules_strict = ["e_score_correction_bias"]
+ _keys_to_ignore_on_load_unexpected = [r"model\.layers\.47.*"]
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ super()._init_weights(module)
+ if isinstance(module, Glm4MoeLiteTopkRouter):
+ init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
+ init.zeros_(module.e_score_correction_bias)
+ elif isinstance(module, Glm4MoeLiteNaiveMoe):
+ init.normal_(module.gate_up_proj, mean=0.0, std=self.config.initializer_range)
+ init.normal_(module.down_proj, mean=0.0, std=self.config.initializer_range)
+
+
+@auto_docstring
+class Glm4MoeLiteModel(Glm4MoeLitePreTrainedModel):
+ def __init__(self, config: Glm4MoeLiteConfig):
+ super().__init__(config)
+ self.padding_idx = config.pad_token_id
+ self.vocab_size = config.vocab_size
+
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
+ self.layers = nn.ModuleList(
+ [Glm4MoeLiteDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
+ )
+ self.norm = Glm4MoeLiteRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.rotary_emb = Glm4MoeLiteRotaryEmbedding(config=config)
+ self.gradient_checkpointing = False
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @merge_with_config_defaults
+ @capture_outputs
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ use_cache: bool | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> BaseModelOutputWithPast:
+ if (input_ids is None) ^ (inputs_embeds is not None):
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
+
+ if inputs_embeds is None:
+ inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)
+
+ if use_cache and past_key_values is None:
+ past_key_values = DynamicCache(config=self.config)
+
+ if position_ids is None:
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
+ position_ids = position_ids.unsqueeze(0)
+
+ causal_mask = create_causal_mask(
+ config=self.config,
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ position_ids=position_ids,
+ )
+
+ hidden_states = inputs_embeds
+ position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
+
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
+ hidden_states = decoder_layer(
+ hidden_states,
+ attention_mask=causal_mask,
+ position_embeddings=position_embeddings,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ **kwargs,
+ )
+
+ hidden_states = self.norm(hidden_states)
+ return BaseModelOutputWithPast(
+ last_hidden_state=hidden_states,
+ past_key_values=past_key_values,
+ )
+
+
+@auto_docstring
+class Glm4MoeLiteForCausalLM(Glm4MoeLitePreTrainedModel, GenerationMixin):
+ _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
+ _tp_plan = {"lm_head": "colwise_gather_output"}
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
+
+ def __init__(self, config):
+ super().__init__(config)
+ self.model = Glm4MoeLiteModel(config)
+ self.vocab_size = config.vocab_size
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ use_cache: bool | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> CausalLMOutputWithPast:
+ r"""
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, Glm4MoeLiteForCausalLM
+
+ >>> model = Glm4MoeLiteForCausalLM.from_pretrained("meta-glm4_moe_lite/Glm4MoeLite-2-7b-hf")
+ >>> tokenizer = AutoTokenizer.from_pretrained("meta-glm4_moe_lite/Glm4MoeLite-2-7b-hf")
+
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
+
+ >>> # Generate
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
+ ```"""
+ outputs: BaseModelOutputWithPast = self.model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ **kwargs,
+ )
+
+ hidden_states = outputs.last_hidden_state
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
+
+ return CausalLMOutputWithPast(
+ loss=loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+__all__ = ["Glm4MoeLitePreTrainedModel", "Glm4MoeLiteModel", "Glm4MoeLiteForCausalLM"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm4_moe_lite/modular_glm4_moe_lite.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm4_moe_lite/modular_glm4_moe_lite.py
new file mode 100644
index 0000000000000000000000000000000000000000..1f65f44a525ae885c7cd612b689f82c74c70a9e4
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm4_moe_lite/modular_glm4_moe_lite.py
@@ -0,0 +1,187 @@
+# Copyright 2025 the HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+import torch.nn as nn
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...modeling_rope_utils import RopeParameters
+from ...utils import auto_docstring
+from ..deepseek_v3.modeling_deepseek_v3 import DeepseekV3Attention
+from ..glm4_moe.modeling_glm4_moe import (
+ Glm4MoeDecoderLayer,
+ Glm4MoeForCausalLM,
+ Glm4MoeMLP,
+ Glm4MoeModel,
+ Glm4MoeMoE,
+ Glm4MoeNaiveMoe,
+ Glm4MoePreTrainedModel,
+ Glm4MoeRMSNorm,
+ Glm4MoeRotaryEmbedding,
+ Glm4MoeTopkRouter,
+)
+
+
+@auto_docstring(checkpoint="zai-org/GLM-4.5")
+@strict
+class Glm4MoeLiteConfig(PreTrainedConfig):
+ r"""
+ n_group (`int`, *optional*, defaults to 1):
+ Number of groups for routed experts.
+ rope_interleave (`bool`, *optional*, defaults to `True`):
+ Whether to interleave the rotary position embeddings.
+ mlp_layer_types (`list`, *optional*):
+ MLP (Moe vs Dense) pattern for each layer.
+
+ Example:
+
+ ```python
+ >>> from transformers import Glm4MoeLiteModel, Glm4MoeLiteConfig
+
+ >>> # Initializing a Deepseek-V3 style configuration
+ >>> configuration = Glm4MoeLiteConfig()
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "glm4_moe_lite"
+ keys_to_ignore_at_inference = ["past_key_values"]
+ base_model_tp_plan = {
+ "layers.*.self_attn.q_b_proj": "colwise",
+ "layers.*.self_attn.kv_a_proj_with_mqa": "mla_kv_a_proj",
+ "layers.*.self_attn.kv_b_proj": "colwise",
+ "layers.*.self_attn.o_proj": "rowwise",
+ "layers.*.mlp.experts.gate_up_proj": "packed_colwise",
+ "layers.*.mlp.experts.down_proj": "rowwise",
+ "layers.*.mlp.experts": "moe_tp_experts",
+ "layers.*.mlp.gate_proj": "colwise",
+ "layers.*.mlp.up_proj": "colwise",
+ "layers.*.mlp.down_proj": "rowwise",
+ }
+ base_model_pp_plan = {
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
+ "norm": (["hidden_states"], ["hidden_states"]),
+ }
+ attribute_map = {
+ "num_local_experts": "n_routed_experts",
+ "head_dim": "qk_rope_head_dim",
+ }
+
+ vocab_size: int = 154880
+ hidden_size: int = 2048
+ intermediate_size: int = 10240
+ moe_intermediate_size: int = 1536
+ num_hidden_layers: int = 47
+ num_attention_heads: int = 20
+ num_key_value_heads: int = 20
+ n_shared_experts: int = 1
+ n_routed_experts: int = 64
+ routed_scaling_factor: float = 1.8
+ kv_lora_rank: int = 512
+ q_lora_rank: int | None = 768
+ qk_rope_head_dim: int = 64
+ v_head_dim: int = 256
+ qk_nope_head_dim: int = 192
+ n_group: int = 1
+ topk_group: int = 1
+ num_experts_per_tok: int = 4
+ norm_topk_prob: bool = True
+ hidden_act: str = "silu"
+ max_position_embeddings: int = 202752
+ initializer_range: float = 0.02
+ rms_norm_eps: float = 1e-5
+ use_cache: bool = True
+ pad_token_id: int | None = None
+ bos_token_id: int | None = 0
+ eos_token_id: int | list[int] | None = 1
+ pretraining_tp: int = 1
+ tie_word_embeddings: bool = False
+ rope_parameters: RopeParameters | dict | None = None
+ rope_interleave: bool = True
+ mlp_layer_types: list[str] | None = None
+ attention_bias: bool = False
+ attention_dropout: float | int = 0.0
+
+ def __post_init__(self, **kwargs):
+ # Default to MoE from the second layer and on
+ if self.mlp_layer_types is None:
+ self.mlp_layer_types = ["dense"] + ["sparse"] * (self.num_hidden_layers - 1)
+ self.qk_head_dim = self.qk_nope_head_dim + self.qk_rope_head_dim
+ super().__post_init__(**kwargs)
+
+
+class Glm4MoeLiteRotaryEmbedding(Glm4MoeRotaryEmbedding):
+ pass
+
+
+class Glm4MoeLiteAttention(DeepseekV3Attention):
+ pass
+
+
+class Glm4MoeLiteMLP(Glm4MoeMLP):
+ pass
+
+
+class Glm4MoeLiteTopkRouter(Glm4MoeTopkRouter):
+ pass
+
+
+class Glm4MoeLiteRMSNorm(Glm4MoeRMSNorm):
+ pass
+
+
+class Glm4MoeLiteNaiveMoe(Glm4MoeNaiveMoe):
+ pass
+
+
+class Glm4MoeLiteMoE(Glm4MoeMoE):
+ pass
+
+
+class Glm4MoeLiteDecoderLayer(Glm4MoeDecoderLayer, nn.Module):
+ def __init__(self, config: Glm4MoeLiteConfig, layer_idx: int):
+ nn.Module.__init__(self)
+ self.hidden_size = config.hidden_size
+ self.self_attn = Glm4MoeLiteAttention(config, layer_idx)
+
+ if config.mlp_layer_types[layer_idx] == "sparse":
+ self.mlp = Glm4MoeLiteMoE(config)
+ else:
+ self.mlp = Glm4MoeLiteMLP(config)
+
+ self.input_layernorm = Glm4MoeLiteRMSNorm(config.hidden_size, config.rms_norm_eps)
+ self.post_attention_layernorm = Glm4MoeLiteRMSNorm(config.hidden_size, config.rms_norm_eps)
+
+
+class Glm4MoeLitePreTrainedModel(Glm4MoePreTrainedModel):
+ _keys_to_ignore_on_load_unexpected = [r"model\.layers\.47.*"]
+
+
+class Glm4MoeLiteModel(Glm4MoeModel):
+ pass
+
+
+class Glm4MoeLiteForCausalLM(Glm4MoeForCausalLM):
+ pass
+
+
+__all__ = [
+ "Glm4MoeLiteConfig",
+ "Glm4MoeLitePreTrainedModel",
+ "Glm4MoeLiteModel",
+ "Glm4MoeLiteForCausalLM",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm4v/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm4v/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..423b4cd1dc17dfecd84fc02463687dabc02b8fd6
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm4v/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm4v/__pycache__/configuration_glm4v.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm4v/__pycache__/configuration_glm4v.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9058300da10e91418539149b214a77960941624c
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm4v/__pycache__/configuration_glm4v.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm4v/__pycache__/image_processing_glm4v.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm4v/__pycache__/image_processing_glm4v.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b93a49ad68637387222f4bfc9a87827de09b8c39
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm4v/__pycache__/image_processing_glm4v.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm4v/__pycache__/image_processing_pil_glm4v.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm4v/__pycache__/image_processing_pil_glm4v.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d17715f4f7d469a05a3a600e33e0b349bfb8d8dc
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm4v/__pycache__/image_processing_pil_glm4v.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm4v/__pycache__/modeling_glm4v.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm4v/__pycache__/modeling_glm4v.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c6b6b977d6b0f9ad1e77757ddc7107030a8f1bc0
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm4v/__pycache__/modeling_glm4v.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm4v/__pycache__/modular_glm4v.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm4v/__pycache__/modular_glm4v.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1085acdfda4185b3d6c278f44f3a45b270bac065
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm4v/__pycache__/modular_glm4v.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm4v/__pycache__/processing_glm4v.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm4v/__pycache__/processing_glm4v.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..826592f36fa5cc07263f2678238874d741ef0c29
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm4v/__pycache__/processing_glm4v.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm4v/__pycache__/video_processing_glm4v.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm4v/__pycache__/video_processing_glm4v.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3cea5f5ddc2d454731e2dacf71c6871f255707c9
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glm4v/__pycache__/video_processing_glm4v.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glmasr/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glmasr/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..8e0700978b78ab4406f97eebc1c176abd8165c3d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glmasr/__init__.py
@@ -0,0 +1,29 @@
+# Copyright 2025 the HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_glmasr import *
+ from .modeling_glmasr import *
+ from .processing_glmasr import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glmasr/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glmasr/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..252cc03760431c1151d14da973419ac272f8dc54
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glmasr/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glmasr/__pycache__/configuration_glmasr.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glmasr/__pycache__/configuration_glmasr.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6a2462362fe852b3f5bcd79338c758faa09dbc9e
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glmasr/__pycache__/configuration_glmasr.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glmasr/__pycache__/modeling_glmasr.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glmasr/__pycache__/modeling_glmasr.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0f3974f8474329a257c668684424694e5ec84e06
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glmasr/__pycache__/modeling_glmasr.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glmasr/__pycache__/modular_glmasr.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glmasr/__pycache__/modular_glmasr.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8df12402ebf72f41f6381547b5c0ab3557b738eb
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glmasr/__pycache__/modular_glmasr.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glmasr/__pycache__/processing_glmasr.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glmasr/__pycache__/processing_glmasr.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0e6400b99fc9cae34c184a5a54fb5286b87aecfb
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glmasr/__pycache__/processing_glmasr.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glmasr/configuration_glmasr.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glmasr/configuration_glmasr.py
new file mode 100644
index 0000000000000000000000000000000000000000..c3d320bb1db47c29f093d979b602f1460d571599
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glmasr/configuration_glmasr.py
@@ -0,0 +1,123 @@
+# Copyright 2025 the HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring
+from ..auto import CONFIG_MAPPING, AutoConfig
+
+
+@auto_docstring(checkpoint="zai-org/GLM-ASR-Nano-2512")
+@strict
+class GlmAsrEncoderConfig(PreTrainedConfig):
+ r"""
+ Example:
+
+ ```python
+ >>> from transformers import GlmAsrEncoderConfig, GlmAsrEncoder
+
+ >>> # Initializing a GlmAsrEncoderConfig
+ >>> configuration = GlmAsrEncoderConfig()
+
+ >>> # Initializing a GlmAsrEncoder (with random weights)
+ >>> model = GlmAsrEncoder(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "glmasr_encoder"
+
+ hidden_size: int = 1280
+ intermediate_size: int = 5120
+ num_hidden_layers: int = 32
+ num_attention_heads: int = 20
+ num_key_value_heads: int | None = None
+ hidden_act: str = "gelu"
+ max_position_embeddings: int = 1500
+ initializer_range: float = 0.02
+ rope_parameters: dict | None = None
+ attention_dropout: float | int = 0.0
+ num_mel_bins: int = 128
+
+ def __post_init__(self, **kwargs):
+ if self.num_key_value_heads is None:
+ self.num_key_value_heads = self.num_attention_heads
+
+ kwargs.setdefault("partial_rotary_factor", 0.5)
+ super().__post_init__(**kwargs)
+
+
+@auto_docstring(checkpoint="zai-org/GLM-ASR-Nano-2512")
+@strict
+class GlmAsrConfig(PreTrainedConfig):
+ r"""
+ Example:
+
+ ```python
+ >>> from transformers import GlmAsrForConditionalGeneration, GlmAsrConfig
+
+ >>> # Initializing a glmasr configuration
+ >>> configuration = GlmAsrConfig()
+
+ >>> # Initializing a GLM-ASR-Nano-2512 model with random weights
+ >>> model = GlmAsrForConditionalGeneration(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "glmasr"
+ sub_configs = {"text_config": AutoConfig, "audio_config": AutoConfig}
+
+ _default_text_config_kwargs = {
+ "vocab_size": 59264,
+ "hidden_size": 2048,
+ "intermediate_size": 6144,
+ "num_hidden_layers": 28,
+ "num_attention_heads": 16,
+ "num_key_value_heads": 4,
+ "max_position_embeddings": 8192,
+ "rms_norm_eps": 1e-05,
+ "use_cache": True,
+ "eos_token_id": [59246, 59253, 59255],
+ "rope_parameters": {"rope_theta": 10000.0, "rope_type": "default"},
+ }
+
+ audio_config: dict | PreTrainedConfig | None = None
+ text_config: dict | PreTrainedConfig | None = None
+ audio_token_id: int = 59260
+ projector_hidden_act: str = "gelu"
+
+ def __post_init__(self, **kwargs):
+ if isinstance(self.audio_config, dict):
+ self.audio_config["model_type"] = self.audio_config.get("model_type", "glmasr_encoder")
+ self.audio_config = CONFIG_MAPPING[self.audio_config["model_type"]](**self.audio_config)
+ elif self.audio_config is None:
+ self.audio_config = CONFIG_MAPPING["glmasr_encoder"]()
+
+ if isinstance(self.text_config, dict):
+ self.text_config["model_type"] = self.text_config.get("model_type", "llama")
+ self.text_config = CONFIG_MAPPING[self.text_config["model_type"]](
+ **{**self._default_text_config_kwargs, **self.text_config}
+ )
+ elif self.text_config is None:
+ self.text_config = CONFIG_MAPPING["llama"](**self._default_text_config_kwargs)
+
+ super().__post_init__(**kwargs)
+
+
+__all__ = ["GlmAsrEncoderConfig", "GlmAsrConfig"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glmasr/modeling_glmasr.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glmasr/modeling_glmasr.py
new file mode 100644
index 0000000000000000000000000000000000000000..74c762f5c0bfce0df2f40ca4d650a56ce4e68a5c
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glmasr/modeling_glmasr.py
@@ -0,0 +1,531 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/glmasr/modular_glmasr.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_glmasr.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2025 the HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from collections.abc import Callable
+from typing import Optional
+
+from ...activations import ACT2FN
+from ...cache_utils import Cache
+from ...generation import GenerationMixin
+from ...integrations import use_kernelized_func
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import BaseModelOutputWithPooling, CausalLMOutputWithPast
+from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import TransformersKwargs, auto_docstring, is_torch_available, torch_compilable_check
+from ...utils.generic import can_return_tuple, maybe_autocast, merge_with_config_defaults
+from ...utils.output_capturing import capture_outputs
+from ..auto import AutoModel, AutoModelForCausalLM
+from .configuration_glmasr import GlmAsrConfig, GlmAsrEncoderConfig
+
+
+if is_torch_available():
+ import torch
+ from torch import nn
+
+
+class GlmAsrRotaryEmbedding(nn.Module):
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
+
+ def __init__(self, config: GlmAsrConfig, device=None):
+ super().__init__()
+ self.max_seq_len_cached = config.max_position_embeddings
+ self.original_max_seq_len = config.max_position_embeddings
+
+ self.config = config
+
+ self.rope_type = self.config.rope_parameters["rope_type"]
+ rope_init_fn: Callable = self.compute_default_rope_parameters
+ if self.rope_type != "default":
+ rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
+ inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
+
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
+ self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
+
+ @staticmethod
+ def compute_default_rope_parameters(
+ config: GlmAsrConfig | None = None,
+ device: Optional["torch.device"] = None,
+ seq_len: int | None = None,
+ ) -> tuple["torch.Tensor", float]:
+ """
+ Computes the inverse frequencies according to the original RoPE implementation
+ Args:
+ config ([`~transformers.PreTrainedConfig`]):
+ The model configuration.
+ device (`torch.device`):
+ The device to use for initialization of the inverse frequencies.
+ seq_len (`int`, *optional*):
+ The current sequence length. Unused for this type of RoPE.
+ Returns:
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
+ """
+ base = config.rope_parameters["rope_theta"]
+ partial_rotary_factor = config.rope_parameters.get("partial_rotary_factor", 1.0)
+ head_dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
+ dim = int(head_dim * partial_rotary_factor)
+
+ attention_factor = 1.0 # Unused in this type of RoPE
+
+ # Compute the inverse frequencies
+ inv_freq = 1.0 / (
+ base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
+ )
+ return inv_freq, attention_factor
+
+ @torch.no_grad()
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
+ def forward(self, x, position_ids):
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
+ position_ids_expanded = position_ids[:, None, :].float()
+
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
+ with maybe_autocast(device_type=device_type, enabled=False): # Force float32
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
+ emb = torch.cat((freqs, freqs), dim=-1)
+ cos = emb.cos() * self.attention_scaling
+ sin = emb.sin() * self.attention_scaling
+
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
+
+
+def rotate_half(x):
+ """Rotates half the hidden dims of the input."""
+ x1 = x[..., : x.shape[-1] // 2]
+ x2 = x[..., x.shape[-1] // 2 :]
+ return torch.cat((-x2, x1), dim=-1)
+
+
+def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
+ """
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
+ """
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
+ if n_rep == 1:
+ return hidden_states
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
+
+
+def eager_attention_forward(
+ module: nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: torch.Tensor | None,
+ scaling: float,
+ dropout: float = 0.0,
+ **kwargs: Unpack[TransformersKwargs],
+):
+ key_states = repeat_kv(key, module.num_key_value_groups)
+ value_states = repeat_kv(value, module.num_key_value_groups)
+
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
+ if attention_mask is not None:
+ attn_weights = attn_weights + attention_mask
+
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
+ attn_output = torch.matmul(attn_weights, value_states)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+
+ return attn_output, attn_weights
+
+
+def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
+ cos = cos.unsqueeze(unsqueeze_dim)
+ sin = sin.unsqueeze(unsqueeze_dim)
+
+ rotary_dim = cos.shape[-1]
+ q_rot, q_pass = q[..., :rotary_dim], q[..., rotary_dim:]
+ k_rot, k_pass = k[..., :rotary_dim], k[..., rotary_dim:]
+
+ # Apply rotary embeddings on the first half or full tensor
+ q_embed = (q_rot * cos) + (rotate_half(q_rot) * sin)
+ k_embed = (k_rot * cos) + (rotate_half(k_rot) * sin)
+
+ # Concatenate back to full shape
+ q_embed = torch.cat([q_embed, q_pass], dim=-1)
+ k_embed = torch.cat([k_embed, k_pass], dim=-1)
+ return q_embed, k_embed
+
+
+@use_kernelized_func(apply_rotary_pos_emb)
+class GlmAsrAttention(nn.Module):
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
+
+ def __init__(self, config: GlmAsrConfig, layer_idx: int):
+ super().__init__()
+ self.config = config
+ self.layer_idx = layer_idx
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
+ self.scaling = self.head_dim**-0.5
+ self.attention_dropout = config.attention_dropout
+ self.is_causal = False
+ self.q_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=True)
+ self.k_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=False)
+ self.v_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=True)
+ self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=True)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor, torch.Tensor]:
+ input_shape = hidden_states.shape[:-1]
+ hidden_shape = (*input_shape, -1, self.head_dim)
+
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+
+ cos, sin = position_embeddings
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_states,
+ key_states,
+ value_states,
+ attention_mask=None,
+ dropout=0.0 if not self.training else self.attention_dropout,
+ scaling=self.scaling,
+ **kwargs,
+ )
+
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ attn_output = self.o_proj(attn_output)
+ return attn_output, attn_weights
+
+
+class GlmAsrMLP(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
+ self.act_fn = ACT2FN[config.hidden_act]
+
+ def forward(self, hidden_states: torch.Tensor):
+ hidden_states = self.fc1(hidden_states)
+ hidden_states = self.act_fn(hidden_states)
+ hidden_states = self.fc2(hidden_states)
+ return hidden_states
+
+
+class GlmAsrEncoderLayer(GradientCheckpointingLayer):
+ def __init__(self, config: GlmAsrConfig, layer_idx: int):
+ super().__init__()
+ self.hidden_size = config.hidden_size
+
+ self.self_attn = GlmAsrAttention(config=config, layer_idx=layer_idx)
+
+ self.mlp = GlmAsrMLP(config)
+ self.input_layernorm = nn.LayerNorm(config.hidden_size)
+ self.post_attention_layernorm = nn.LayerNorm(config.hidden_size)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.Tensor:
+ residual = hidden_states
+ hidden_states = self.input_layernorm(hidden_states)
+ # Self Attention
+ hidden_states, _ = self.self_attn(
+ hidden_states=hidden_states,
+ position_embeddings=position_embeddings,
+ **kwargs,
+ )
+ hidden_states = residual + hidden_states
+
+ # Fully Connected
+ residual = hidden_states
+ hidden_states = self.post_attention_layernorm(hidden_states)
+ hidden_states = self.mlp(hidden_states)
+ hidden_states = residual + hidden_states
+ return hidden_states
+
+
+@auto_docstring
+class GlmAsrPreTrainedModel(PreTrainedModel):
+ config: GlmAsrConfig
+ base_model_prefix = "model"
+ input_modalities = ("audio", "text")
+ supports_gradient_checkpointing = True
+ _no_split_modules = ["GlmAsrAttention"]
+ _skip_keys_device_placement = ["past_key_values"]
+ _supports_flash_attn = True
+ _supports_sdpa = True
+
+
+# TODO: @eustlb, this is what WhisperEncoder should look like
+class GlmAsrEncoder(GlmAsrPreTrainedModel):
+ config: GlmAsrEncoderConfig
+ main_input_name = "input_features"
+ input_modalities = "audio"
+ _no_split_modules = ["GlmAsrEncoderLayer"]
+ _can_record_outputs = {
+ "hidden_states": GlmAsrEncoderLayer,
+ "attentions": GlmAsrAttention,
+ }
+
+ def __init__(self, config: GlmAsrEncoderConfig):
+ super().__init__(config)
+ self.conv1 = nn.Conv1d(config.num_mel_bins, config.hidden_size, kernel_size=3, padding=1)
+ self.conv2 = nn.Conv1d(config.hidden_size, config.hidden_size, kernel_size=3, stride=2, padding=1)
+
+ self.layers = nn.ModuleList(
+ [GlmAsrEncoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
+ )
+ self.norm = nn.LayerNorm(config.hidden_size)
+ self.rotary_emb = GlmAsrRotaryEmbedding(config=config)
+ self.gradient_checkpointing = False
+ self.post_init()
+
+ @merge_with_config_defaults
+ @capture_outputs
+ @auto_docstring
+ def forward(self, input_features, **kwargs: Unpack[TransformersKwargs]):
+ inputs_embeds = nn.functional.gelu(self.conv1(input_features))
+ inputs_embeds = nn.functional.gelu(self.conv2(inputs_embeds))
+ inputs_embeds = inputs_embeds.transpose(1, 2)
+
+ hidden_states = inputs_embeds
+ position_embeddings = self.rotary_emb(
+ hidden_states, position_ids=torch.arange(hidden_states.shape[1], device=hidden_states.device)[None, :]
+ )
+
+ for encoder_layer in self.layers:
+ hidden_states = encoder_layer(hidden_states, position_embeddings=position_embeddings, **kwargs)
+
+ hidden_states = self.norm(hidden_states)
+ return BaseModelOutputWithPooling(last_hidden_state=hidden_states)
+
+
+class GlmAsrMultiModalProjector(nn.Module):
+ """
+ Audio adaptor (small MLP) that projects GlmAsrEncoder features
+ to the LLM embedding space so they can replace `` tokens.
+ """
+
+ def __init__(self, config: GlmAsrConfig):
+ super().__init__()
+ self.linear_1 = nn.Linear(config.audio_config.intermediate_size, config.text_config.hidden_size * 2)
+ self.act = ACT2FN[config.projector_hidden_act]
+ self.linear_2 = nn.Linear(config.text_config.hidden_size * 2, config.text_config.hidden_size)
+
+ def forward(self, audio_features):
+ hidden_states = self.linear_1(audio_features)
+ hidden_states = self.act(hidden_states)
+ hidden_states = self.linear_2(hidden_states)
+ return hidden_states
+
+
+@auto_docstring(
+ custom_intro="""
+ The GlmAsr model which consists of a fine-tuned Whisper encoder, a multi-modal projector and a Llama language model.
+ """
+)
+class GlmAsrForConditionalGeneration(GlmAsrPreTrainedModel, GenerationMixin):
+ _keep_in_fp32_modules_strict = None
+ _supports_attention_backend = True
+ _tp_plan = None
+ _pp_plan = None
+
+ def __init__(self, config):
+ super().__init__(config)
+ self.vocab_size = config.text_config.vocab_size
+ self.audio_tower = AutoModel.from_config(config.audio_config)
+ self.language_model = AutoModelForCausalLM.from_config(config.text_config)
+ self.multi_modal_projector = GlmAsrMultiModalProjector(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_output_embeddings(self):
+ return self.language_model.get_output_embeddings()
+
+ def set_output_embeddings(self, new_embeddings):
+ self.language_model.set_output_embeddings(new_embeddings)
+
+ def set_decoder(self, decoder):
+ self.language_model.set_decoder(decoder)
+
+ def get_decoder(self):
+ return self.language_model.get_decoder()
+
+ @can_return_tuple
+ @auto_docstring(
+ custom_intro="Compute audio embeddings from log-mel input features using the audio encoder and multi-modal projector."
+ )
+ def get_audio_features(
+ self,
+ input_features: torch.FloatTensor,
+ input_features_mask: torch.Tensor,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutputWithPooling:
+ r"""
+ input_features (`torch.FloatTensor`):
+ Float values of mel features extracted from the raw speech waveform. Raw speech waveform can be
+ obtained by loading a `.flac` or `.wav` audio file into an array of type `list[float]` or a
+ `numpy.ndarray`, *e.g.* via the soundfile library (`pip install soundfile`). To prepare the array into
+ `input_features`, the [`AutoFeatureExtractor`] should be used for extracting the mel features, padding
+ and conversion into a tensor of type `torch.FloatTensor`. See [`~WhisperFeatureExtractor.__call__`]
+ input_features_mask (`torch.Tensor` of shape `(batch_size, feature_sequence_length)`):
+ Mask to avoid performing attention on padded feature indices.
+ """
+ audio_outputs = self.audio_tower(input_features, return_dict=True, **kwargs)
+ audio_hidden_states = audio_outputs.last_hidden_state
+ audio_hidden_states = audio_hidden_states.reshape(
+ input_features.shape[0], -1, self.config.audio_config.intermediate_size
+ )
+ audio_embeds = self.multi_modal_projector(audio_hidden_states)
+
+ audio_lengths = input_features_mask.sum(-1)
+ for padding, kernel_size, stride in [(1, 3, 1), (1, 3, 2)]:
+ audio_lengths = (audio_lengths + 2 * padding - (kernel_size - 1) - 1) // stride + 1
+ merge_factor = 4
+ post_lengths = (audio_lengths - merge_factor) // merge_factor + 1
+
+ valid_mask = torch.arange(audio_embeds.shape[1], device=post_lengths.device)[None, :] < post_lengths[:, None]
+ audio_outputs.pooler_output = audio_embeds[valid_mask.to(audio_embeds.device)]
+
+ return audio_outputs
+
+ def get_placeholder_mask(
+ self, input_ids: torch.LongTensor, inputs_embeds: torch.FloatTensor, audio_features: torch.FloatTensor
+ ):
+ """
+ Obtains multimodal placeholder mask from `input_ids` or `inputs_embeds`, and checks that the placeholder token count is
+ equal to the length of multimodal features. If the lengths are different, an error is raised.
+ """
+ if input_ids is None:
+ special_audio_mask = inputs_embeds == self.get_input_embeddings()(
+ torch.tensor(self.config.audio_token_id, dtype=torch.long, device=inputs_embeds.device)
+ )
+ special_audio_mask = special_audio_mask.all(-1)
+ else:
+ special_audio_mask = input_ids == self.config.audio_token_id
+
+ n_audio_tokens = special_audio_mask.sum()
+ n_audio_features = audio_features.shape[0]
+ special_audio_mask = special_audio_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
+ torch_compilable_check(
+ inputs_embeds[special_audio_mask].numel() == audio_features.numel(),
+ f"Audio features and audio tokens do not match, tokens: {n_audio_tokens}, features: {n_audio_features}",
+ )
+ return special_audio_mask
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ input_features: torch.FloatTensor | None = None,
+ input_features_mask: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ use_cache: bool | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> CausalLMOutputWithPast:
+ r"""
+ input_features_mask (`torch.Tensor` of shape `(batch_size, feature_sequence_length)`):
+ Mask to avoid performing attention on padding feature indices. Mask values selected in `[0, 1]`:
+
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
+
+ Example:
+
+ ```python
+ >>> from transformers import GlmAsrForConditionalGeneration, AutoProcessor
+
+ >>> model_id = "zai-org/GLM-ASR-Nano-2512"
+ >>> processor = AutoProcessor.from_pretrained(model_id)
+ >>> model = GlmAsrForConditionalGeneration.from_pretrained(model_id, dtype="auto", device_map="auto")
+ >>> inputs = processor.apply_transcription_request("https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/bcn_weather.mp3")
+
+ >>> inputs = inputs.to(model.device, dtype=model.dtype)
+
+ >>> outputs = model.generate(**inputs, do_sample=False, max_new_tokens=500)
+
+ >>> decoded_outputs = processor.batch_decode(outputs[:, inputs.input_ids.shape[1] :], skip_special_tokens=True)
+ >>> print(decoded_outputs)
+ ```"""
+
+ if inputs_embeds is None:
+ inputs_embeds = self.get_input_embeddings()(input_ids)
+
+ if input_features is not None and input_ids is not None:
+ audio_embeds = self.get_audio_features(input_features, input_features_mask, return_dict=True).pooler_output
+
+ # replace text-audio token placeholders with audio embeddings
+ special_audio_mask = self.get_placeholder_mask(
+ input_ids, inputs_embeds=inputs_embeds, audio_features=audio_embeds
+ )
+ inputs_embeds = inputs_embeds.masked_scatter(special_audio_mask, audio_embeds.to(inputs_embeds.device))
+
+ outputs: CausalLMOutputWithPast = self.language_model(
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ labels=labels,
+ use_cache=use_cache,
+ logits_to_keep=logits_to_keep,
+ **kwargs,
+ )
+ return outputs
+
+ def prepare_inputs_for_generation(self, *args, is_first_iteration: bool = False, **kwargs):
+ input_features = kwargs.pop("input_features", None)
+ input_features_mask = kwargs.pop("input_features_mask", None)
+
+ model_inputs = super().prepare_inputs_for_generation(*args, **kwargs)
+
+ if is_first_iteration or not model_inputs.get("use_cache", False):
+ if input_features is not None:
+ model_inputs["input_features"] = input_features
+ if input_features_mask is not None:
+ model_inputs["input_features_mask"] = input_features_mask
+
+ return model_inputs
+
+
+__all__ = ["GlmAsrEncoder", "GlmAsrForConditionalGeneration", "GlmAsrPreTrainedModel"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glmasr/modular_glmasr.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glmasr/modular_glmasr.py
new file mode 100644
index 0000000000000000000000000000000000000000..2c6085eb3a1882eed7f92db7da5eca2f35f9fed0
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glmasr/modular_glmasr.py
@@ -0,0 +1,445 @@
+# Copyright 2025 the HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from collections.abc import Callable
+
+import numpy as np
+
+from ...activations import ACT2FN
+from ...audio_utils import AudioInput, make_list_of_audio
+from ...cache_utils import Cache
+from ...feature_extraction_utils import BatchFeature
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import BaseModelOutputWithPooling, CausalLMOutputWithPast
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS
+from ...processing_utils import Unpack
+from ...utils import TransformersKwargs, auto_docstring, is_torch_available, logging
+from ...utils.generic import can_return_tuple, merge_with_config_defaults
+from ...utils.output_capturing import capture_outputs
+from ..audioflamingo3.modeling_audioflamingo3 import (
+ AudioFlamingo3ForConditionalGeneration,
+ AudioFlamingo3MultiModalProjector,
+ AudioFlamingo3PreTrainedModel,
+)
+from ..audioflamingo3.processing_audioflamingo3 import AudioFlamingo3Processor, AudioFlamingo3ProcessorKwargs
+from ..glm.modeling_glm import GlmRotaryEmbedding
+from ..llama.modeling_llama import LlamaAttention, eager_attention_forward, rotate_half
+from .configuration_glmasr import GlmAsrConfig, GlmAsrEncoderConfig
+
+
+if is_torch_available():
+ import torch
+ from torch import nn
+
+
+logger = logging.get_logger(__name__)
+
+
+class GlmAsrProcessorKwargs(AudioFlamingo3ProcessorKwargs): ...
+
+
+class GlmAsrProcessor(AudioFlamingo3Processor):
+ r"""
+ Constructs an GlmAsr processor which wraps an GlmAsr feature extractor and an GlmAsr
+ tokenizer into a single processor.
+
+ [`GlmAsrProcessor`] offers all the functionalities of [`WhisperFeatureExtractor`] and
+ [`Qwen2TokenizerFast`]. See the [`~GlmAsrProcessor.__call__`] for more information.
+
+ Args:
+ feature_extractor ([`WhisperFeatureExtractor`]):
+ The feature extractor is a required input.
+ tokenizer ([`Qwen2TokenizerFast`]):
+ The tokenizer is a required input.
+ chat_template (`Optional[str]`, *optional*):
+ The Jinja template to use for formatting the conversation. If not provided, the tokenizer's default chat
+ template will be used.
+ audio_token (`Optional[str]`, *optional*, defaults to `"<|pad|>`"):
+ Special token used to represent audio inputs in the chat template.
+ default_transcription_prompt (`str`, *optional*, defaults to `"Please transcribe this audio into text"`):
+ Default prompt to use for transcription tasks when applying transcription requests.
+ max_audio_len (`int`, *optional*, defaults to 655):
+ Maximum length of audio sequences in seconds. Audio longer than this will be truncated.
+ 655 gives approximately 8192 tokens, corresponding to the maximum sequence length of the text model.
+ """
+
+ def __init__(
+ self,
+ feature_extractor,
+ tokenizer,
+ chat_template=None,
+ audio_token="<|pad|>",
+ default_transcription_prompt="Please transcribe this audio into text",
+ max_audio_len=655,
+ ):
+ super().__init__(
+ feature_extractor,
+ tokenizer,
+ chat_template=chat_template,
+ audio_token=audio_token,
+ default_transcription_prompt=default_transcription_prompt,
+ max_audio_len=max_audio_len,
+ )
+
+ def _get_audio_token_length(self, audio_lengths: "torch.Tensor") -> "torch.Tensor":
+ merge_factor = 4
+ for padding, kernel_size, stride in [(1, 3, 1), (1, 3, 2)]:
+ audio_lengths = (audio_lengths + 2 * padding - (kernel_size - 1) - 1) // stride + 1
+
+ num_tokens = (audio_lengths - merge_factor) // merge_factor + 1
+ return num_tokens
+
+ def apply_transcription_request(
+ self,
+ audio: str | list[str] | AudioInput,
+ prompt: str | list[str] | None = None,
+ **kwargs: Unpack[GlmAsrProcessorKwargs],
+ ) -> BatchFeature:
+ """
+ Prepare inputs for automatic speech recognition without manually writing the default transcription prompt.
+
+ Args:
+ audio (`str`, `list[str]`, `np.ndarray`, `torch.Tensor`, `list[np.ndarray]`, `list[torch.Tensor]`):
+ Audio to transcribe. Strings are interpreted as local paths or URLs and will be loaded automatically by
+ the chat template loader; NumPy arrays and PyTorch tensors are forwarded directly.
+ prompt (`str` or `list[str]`, *optional*):
+ Custom prompt(s) to include in the user turn. A list must be the same length as the batch. When `None`,
+ each sample uses `"Transcribe the input speech."`.
+ **kwargs:
+ Additional keyword arguments forwarded to [`~GlmAsrProcessor.apply_chat_template`] (for example
+ `text_kwargs`, `audio_kwargs`, ...).
+
+ Returns:
+ [`BatchFeature`]: Processor outputs ready to be passed to [`GlmAsrForConditionalGeneration.generate`].
+
+ """
+
+ if isinstance(audio, str):
+ audio_items: list[str | np.ndarray] = [audio]
+ elif isinstance(audio, (list, tuple)) and audio and all(isinstance(el, str) for el in audio):
+ audio_items = list(audio)
+ else:
+ audio_items = list(make_list_of_audio(audio))
+ if is_torch_available():
+ audio_items = [el.detach().cpu().numpy() if isinstance(el, torch.Tensor) else el for el in audio_items]
+
+ batch_size = len(audio_items)
+ if batch_size == 0:
+ raise ValueError("`audio` must contain at least one sample.")
+
+ if prompt is None:
+ prompts = [self.default_transcription_prompt] * batch_size
+ elif isinstance(prompt, str):
+ prompts = [prompt] * batch_size
+ elif isinstance(prompt, (list, tuple)):
+ if len(prompt) != batch_size:
+ raise ValueError(
+ f"Received {len(prompt)} prompt(s) for {batch_size} audio sample(s); counts must match."
+ )
+ prompts = []
+ for item in prompt:
+ if item is None:
+ prompts.append(self.default_transcription_prompt)
+ elif isinstance(item, str):
+ prompts.append(item)
+ else:
+ raise TypeError("Each prompt must be a string or `None`.")
+ else:
+ raise TypeError("`prompt` must be a string, a sequence of strings, or `None`.")
+
+ conversations = [
+ [
+ {
+ "role": "user",
+ "content": [
+ {"type": "audio", "path": audio_item}
+ if isinstance(audio_item, str)
+ else {"type": "audio", "audio": audio_item},
+ {"type": "text", "text": prompt_text},
+ ],
+ }
+ ]
+ for prompt_text, audio_item in zip(prompts, audio_items)
+ ]
+
+ return self.apply_chat_template(
+ conversations,
+ tokenize=True,
+ add_generation_prompt=True,
+ return_dict=True,
+ **kwargs,
+ )
+
+
+class GlmAsrRotaryEmbedding(GlmRotaryEmbedding): ...
+
+
+def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
+ cos = cos.unsqueeze(unsqueeze_dim)
+ sin = sin.unsqueeze(unsqueeze_dim)
+
+ rotary_dim = cos.shape[-1]
+ q_rot, q_pass = q[..., :rotary_dim], q[..., rotary_dim:]
+ k_rot, k_pass = k[..., :rotary_dim], k[..., rotary_dim:]
+
+ # Apply rotary embeddings on the first half or full tensor
+ q_embed = (q_rot * cos) + (rotate_half(q_rot) * sin)
+ k_embed = (k_rot * cos) + (rotate_half(k_rot) * sin)
+
+ # Concatenate back to full shape
+ q_embed = torch.cat([q_embed, q_pass], dim=-1)
+ k_embed = torch.cat([k_embed, k_pass], dim=-1)
+ return q_embed, k_embed
+
+
+class GlmAsrAttention(LlamaAttention):
+ def __init__(self, config: GlmAsrConfig, layer_idx: int):
+ super().__init__(config, layer_idx)
+ self.is_causal = False
+ self.q_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=True)
+ self.k_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=False)
+ self.v_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=True)
+ self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=True)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor, torch.Tensor]:
+ input_shape = hidden_states.shape[:-1]
+ hidden_shape = (*input_shape, -1, self.head_dim)
+
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+
+ cos, sin = position_embeddings
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_states,
+ key_states,
+ value_states,
+ attention_mask=None,
+ dropout=0.0 if not self.training else self.attention_dropout,
+ scaling=self.scaling,
+ **kwargs,
+ )
+
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ attn_output = self.o_proj(attn_output)
+ return attn_output, attn_weights
+
+
+class GlmAsrMLP(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
+ self.act_fn = ACT2FN[config.hidden_act]
+
+ def forward(self, hidden_states: torch.Tensor):
+ hidden_states = self.fc1(hidden_states)
+ hidden_states = self.act_fn(hidden_states)
+ hidden_states = self.fc2(hidden_states)
+ return hidden_states
+
+
+class GlmAsrEncoderLayer(GradientCheckpointingLayer):
+ def __init__(self, config: GlmAsrConfig, layer_idx: int):
+ super().__init__()
+ self.hidden_size = config.hidden_size
+
+ self.self_attn = GlmAsrAttention(config=config, layer_idx=layer_idx)
+
+ self.mlp = GlmAsrMLP(config)
+ self.input_layernorm = nn.LayerNorm(config.hidden_size)
+ self.post_attention_layernorm = nn.LayerNorm(config.hidden_size)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.Tensor:
+ residual = hidden_states
+ hidden_states = self.input_layernorm(hidden_states)
+ # Self Attention
+ hidden_states, _ = self.self_attn(
+ hidden_states=hidden_states,
+ position_embeddings=position_embeddings,
+ **kwargs,
+ )
+ hidden_states = residual + hidden_states
+
+ # Fully Connected
+ residual = hidden_states
+ hidden_states = self.post_attention_layernorm(hidden_states)
+ hidden_states = self.mlp(hidden_states)
+ hidden_states = residual + hidden_states
+ return hidden_states
+
+
+class GlmAsrPreTrainedModel(AudioFlamingo3PreTrainedModel): ...
+
+
+# TODO: @eustlb, this is what WhisperEncoder should look like
+class GlmAsrEncoder(GlmAsrPreTrainedModel):
+ config: GlmAsrEncoderConfig
+ main_input_name = "input_features"
+ input_modalities = "audio"
+ _no_split_modules = ["GlmAsrEncoderLayer"]
+ _can_record_outputs = {
+ "hidden_states": GlmAsrEncoderLayer,
+ "attentions": GlmAsrAttention,
+ }
+
+ def __init__(self, config: GlmAsrEncoderConfig):
+ super().__init__(config)
+ self.conv1 = nn.Conv1d(config.num_mel_bins, config.hidden_size, kernel_size=3, padding=1)
+ self.conv2 = nn.Conv1d(config.hidden_size, config.hidden_size, kernel_size=3, stride=2, padding=1)
+
+ self.layers = nn.ModuleList(
+ [GlmAsrEncoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
+ )
+ self.norm = nn.LayerNorm(config.hidden_size)
+ self.rotary_emb = GlmAsrRotaryEmbedding(config=config)
+ self.gradient_checkpointing = False
+ self.post_init()
+
+ @merge_with_config_defaults
+ @capture_outputs
+ @auto_docstring
+ def forward(self, input_features, **kwargs: Unpack[TransformersKwargs]):
+ inputs_embeds = nn.functional.gelu(self.conv1(input_features))
+ inputs_embeds = nn.functional.gelu(self.conv2(inputs_embeds))
+ inputs_embeds = inputs_embeds.transpose(1, 2)
+
+ hidden_states = inputs_embeds
+ position_embeddings = self.rotary_emb(
+ hidden_states, position_ids=torch.arange(hidden_states.shape[1], device=hidden_states.device)[None, :]
+ )
+
+ for encoder_layer in self.layers:
+ hidden_states = encoder_layer(hidden_states, position_embeddings=position_embeddings, **kwargs)
+
+ hidden_states = self.norm(hidden_states)
+ return BaseModelOutputWithPooling(last_hidden_state=hidden_states)
+
+
+class GlmAsrMultiModalProjector(AudioFlamingo3MultiModalProjector):
+ def __init__(self, config: GlmAsrConfig):
+ super().__init__()
+ self.linear_1 = nn.Linear(config.audio_config.intermediate_size, config.text_config.hidden_size * 2)
+ self.linear_2 = nn.Linear(config.text_config.hidden_size * 2, config.text_config.hidden_size)
+
+
+@auto_docstring(
+ custom_intro="""
+ The GlmAsr model which consists of a fine-tuned Whisper encoder, a multi-modal projector and a Llama language model.
+ """
+)
+class GlmAsrForConditionalGeneration(AudioFlamingo3ForConditionalGeneration):
+ _supports_attention_backend = True
+
+ @can_return_tuple
+ @auto_docstring(
+ custom_intro="Compute audio embeddings from log-mel input features using the audio encoder and multi-modal projector."
+ )
+ def get_audio_features(
+ self,
+ input_features: torch.FloatTensor,
+ input_features_mask: torch.Tensor,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutputWithPooling:
+ audio_outputs = self.audio_tower(input_features, return_dict=True, **kwargs)
+ audio_hidden_states = audio_outputs.last_hidden_state
+ audio_hidden_states = audio_hidden_states.reshape(
+ input_features.shape[0], -1, self.config.audio_config.intermediate_size
+ )
+ audio_embeds = self.multi_modal_projector(audio_hidden_states)
+
+ audio_lengths = input_features_mask.sum(-1)
+ for padding, kernel_size, stride in [(1, 3, 1), (1, 3, 2)]:
+ audio_lengths = (audio_lengths + 2 * padding - (kernel_size - 1) - 1) // stride + 1
+ merge_factor = 4
+ post_lengths = (audio_lengths - merge_factor) // merge_factor + 1
+
+ valid_mask = torch.arange(audio_embeds.shape[1], device=post_lengths.device)[None, :] < post_lengths[:, None]
+ audio_outputs.pooler_output = audio_embeds[valid_mask.to(audio_embeds.device)]
+
+ return audio_outputs
+
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ input_features: torch.FloatTensor | None = None,
+ input_features_mask: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ use_cache: bool | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> CausalLMOutputWithPast:
+ r"""
+ input_features_mask (`torch.Tensor` of shape `(batch_size, feature_sequence_length)`):
+ Mask to avoid performing attention on padding feature indices. Mask values selected in `[0, 1]`:
+
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
+
+ Example:
+
+ ```python
+ >>> from transformers import GlmAsrForConditionalGeneration, AutoProcessor
+
+ >>> model_id = "zai-org/GLM-ASR-Nano-2512"
+ >>> processor = AutoProcessor.from_pretrained(model_id)
+ >>> model = GlmAsrForConditionalGeneration.from_pretrained(model_id, dtype="auto", device_map="auto")
+ >>> inputs = processor.apply_transcription_request("https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/bcn_weather.mp3")
+
+ >>> inputs = inputs.to(model.device, dtype=model.dtype)
+
+ >>> outputs = model.generate(**inputs, do_sample=False, max_new_tokens=500)
+
+ >>> decoded_outputs = processor.batch_decode(outputs[:, inputs.input_ids.shape[1] :], skip_special_tokens=True)
+ >>> print(decoded_outputs)
+ ```"""
+ return super().forward(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ labels=labels,
+ use_cache=use_cache,
+ logits_to_keep=logits_to_keep,
+ **kwargs,
+ )
+
+
+__all__ = ["GlmAsrEncoder", "GlmAsrForConditionalGeneration", "GlmAsrProcessor", "GlmAsrPreTrainedModel"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glmasr/processing_glmasr.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glmasr/processing_glmasr.py
new file mode 100644
index 0000000000000000000000000000000000000000..cfd38e423da268afa1a2c7f7722fae63571610f5
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/glmasr/processing_glmasr.py
@@ -0,0 +1,340 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/glmasr/modular_glmasr.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_glmasr.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2025 the HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+import re
+
+import numpy as np
+
+from ...audio_utils import AudioInput, make_list_of_audio
+from ...feature_extraction_utils import BatchFeature
+from ...processing_utils import ProcessingKwargs, ProcessorMixin, Unpack
+from ...tokenization_utils_base import TextInput
+from ...utils import is_torch_available, logging
+
+
+if is_torch_available():
+ import torch
+
+
+logger = logging.get_logger(__name__)
+
+
+class GlmAsrProcessorKwargs(ProcessingKwargs, total=False):
+ _defaults = {
+ "text_kwargs": {
+ "padding": True,
+ },
+ "audio_kwargs": {
+ "sampling_rate": 16000,
+ "return_attention_mask": True,
+ "padding": "max_length",
+ },
+ "common_kwargs": {
+ "return_tensors": "pt",
+ "padding_side": "left",
+ },
+ }
+
+
+class GlmAsrProcessor(ProcessorMixin):
+ r"""
+ Constructs an GlmAsr processor which wraps an GlmAsr feature extractor and an GlmAsr
+ tokenizer into a single processor.
+
+ [`GlmAsrProcessor`] offers all the functionalities of [`WhisperFeatureExtractor`] and
+ [`Qwen2TokenizerFast`]. See the [`~GlmAsrProcessor.__call__`] for more information.
+
+ Args:
+ feature_extractor ([`WhisperFeatureExtractor`]):
+ The feature extractor is a required input.
+ tokenizer ([`Qwen2TokenizerFast`]):
+ The tokenizer is a required input.
+ chat_template (`Optional[str]`, *optional*):
+ The Jinja template to use for formatting the conversation. If not provided, the tokenizer's default chat
+ template will be used.
+ audio_token (`Optional[str]`, *optional*, defaults to `"<|pad|>`"):
+ Special token used to represent audio inputs in the chat template.
+ default_transcription_prompt (`str`, *optional*, defaults to `"Please transcribe this audio into text"`):
+ Default prompt to use for transcription tasks when applying transcription requests.
+ max_audio_len (`int`, *optional*, defaults to 655):
+ Maximum length of audio sequences in seconds. Audio longer than this will be truncated.
+ 655 gives approximately 8192 tokens, corresponding to the maximum sequence length of the text model.
+ """
+
+ def __init__(
+ self,
+ feature_extractor,
+ tokenizer,
+ chat_template=None,
+ audio_token="<|pad|>",
+ default_transcription_prompt="Please transcribe this audio into text",
+ max_audio_len=655,
+ ):
+ self.audio_token = audio_token
+ self.audio_token_id = tokenizer.convert_tokens_to_ids(audio_token)
+ self.default_transcription_prompt = default_transcription_prompt
+ self.max_audio_len = max_audio_len
+ super().__init__(feature_extractor, tokenizer, chat_template=chat_template)
+
+ def _get_audio_token_length(self, audio_lengths: "torch.Tensor") -> "torch.Tensor":
+ merge_factor = 4
+ for padding, kernel_size, stride in [(1, 3, 1), (1, 3, 2)]:
+ audio_lengths = (audio_lengths + 2 * padding - (kernel_size - 1) - 1) // stride + 1
+
+ num_tokens = (audio_lengths - merge_factor) // merge_factor + 1
+ return num_tokens
+
+ def _expand_audio_tokens(self, text, padding_mask, per_sample_windows):
+ audio_lengths = torch.stack([s.sum() for s in torch.split(padding_mask.sum(-1), per_sample_windows)])
+ audio_tokens_lengths = self._get_audio_token_length(audio_lengths)
+ audio_token_pattern = re.compile(re.escape(self.audio_token))
+ for i, audio_length in enumerate(audio_tokens_lengths):
+ text[i] = audio_token_pattern.sub(self.audio_token * audio_length, text[i])
+ return text
+
+ def _get_audio_tokens_mask(self, input_ids):
+ return input_ids == self.audio_token_id
+
+ def __call__(
+ self,
+ text: TextInput | list[TextInput],
+ audio: AudioInput | None = None,
+ output_labels: bool | None = False,
+ **kwargs: Unpack[GlmAsrProcessorKwargs],
+ ) -> BatchFeature:
+ r"""
+ Main method to prepare one or several text sequence(s) and audio waveform(s) for the model. This
+ method expands `` placeholders in the text based on the post-pool frame counts of the
+ audio windows, then tokenizes the provided strings as-is, and extracts log-mel features
+ with [`WhisperFeatureExtractor`]. If `audio` is `None`, no audio processing is performed and
+ the text is tokenized as-is (LM-only behavior).
+
+ Args:
+ text (`str` or `list[str]`):
+ Input sequence or batch of sequences.
+ audio (`np.ndarray` or `list[np.ndarray]`):
+ Input audio or batch of audios as NumPy arrays. If provided, there must be as many `text` inputs as
+ `audio` inputs.
+ output_labels (bool, *optional*, default=False):
+ Whether to return labels for training.
+
+ Returns:
+ [`BatchFeature`]: A dictionary with tokenized text (`input_ids`, `attention_mask`) and
+ audio features (`input_features`, `input_features_mask`).
+ """
+
+ # Merge defaults with user kwargs
+ call_kwargs = self._merge_kwargs(
+ GlmAsrProcessorKwargs,
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
+ **kwargs,
+ )
+
+ text_kwargs = call_kwargs["text_kwargs"]
+ audio_kwargs = call_kwargs["audio_kwargs"]
+ return_tensors = text_kwargs.get("return_tensors")
+ if return_tensors != "pt":
+ raise ValueError(f"{self.__class__.__name__} only supports `return_tensors='pt'`.")
+
+ if isinstance(text, str):
+ text = [text]
+ elif not (isinstance(text, (list, tuple)) and all(isinstance(t, str) for t in text)):
+ raise ValueError("Invalid input text. Please provide a string, or a list of strings")
+
+ audio_inputs = {}
+ if audio is not None:
+ audio = make_list_of_audio(audio)
+ if len(text) != len(audio):
+ raise ValueError(f"Got {len(text)} text but {len(audio)} audios; they must match 1:1.")
+
+ # Determine number of chunks per sample, and flatten
+ window_size = int(audio_kwargs["sampling_rate"] * self.feature_extractor.chunk_length)
+ max_windows = int(self.max_audio_len // self.feature_extractor.chunk_length)
+
+ per_sample_windows: list[int] = []
+ flat_chunks: list[np.ndarray] = []
+
+ for audio_el in audio:
+ n_samples = int(audio_el.shape[0])
+ n_win = max(1, (n_samples + window_size - 1) // window_size)
+ if n_win > max_windows:
+ logger.warning(
+ f"Audio duration ({n_samples / audio_kwargs['sampling_rate']:.1f}s) exceeds {self.max_audio_len}s; truncating to first {self.max_audio_len}s."
+ )
+ n_win = max_windows
+ per_sample_windows.append(n_win)
+
+ time_cap = min(n_samples, n_win * window_size)
+ for i in range(n_win):
+ start = i * window_size
+ end = min((i + 1) * window_size, time_cap)
+ flat_chunks.append(audio_el[start:end])
+
+ # Feature extraction
+ audio_inputs = self.feature_extractor(flat_chunks, **audio_kwargs)
+ padding_mask = audio_inputs.pop("attention_mask")
+ audio_inputs["input_features_mask"] = padding_mask
+
+ # Expand audio tokens in text
+ text = self._expand_audio_tokens(text, padding_mask, per_sample_windows)
+
+ # Tokenize
+ text_inputs = self.tokenizer(text, **text_kwargs)
+
+ data = {**text_inputs, **audio_inputs}
+ if output_labels:
+ labels = data["input_ids"].clone()
+ labels[self._get_audio_tokens_mask(labels)] = -100
+ labels[labels == self.tokenizer.pad_token_id] = -100
+ data["labels"] = labels
+
+ return BatchFeature(data=data, tensor_type=return_tensors)
+
+ @property
+ def model_input_names(self) -> list[str]:
+ tok_names = self.tokenizer.model_input_names
+ fea_names = self.feature_extractor.model_input_names
+ return list(dict.fromkeys(tok_names + fea_names + ["input_features_mask"]))
+
+ def apply_transcription_request(
+ self,
+ audio: str | list[str] | AudioInput,
+ prompt: str | list[str] | None = None,
+ **kwargs: Unpack[GlmAsrProcessorKwargs],
+ ) -> BatchFeature:
+ """
+ Prepare inputs for automatic speech recognition without manually writing the default transcription prompt.
+
+ Args:
+ audio (`str`, `list[str]`, `np.ndarray`, `torch.Tensor`, `list[np.ndarray]`, `list[torch.Tensor]`):
+ Audio to transcribe. Strings are interpreted as local paths or URLs and will be loaded automatically by
+ the chat template loader; NumPy arrays and PyTorch tensors are forwarded directly.
+ prompt (`str` or `list[str]`, *optional*):
+ Custom prompt(s) to include in the user turn. A list must be the same length as the batch. When `None`,
+ each sample uses `"Transcribe the input speech."`.
+ **kwargs:
+ Additional keyword arguments forwarded to [`~GlmAsrProcessor.apply_chat_template`] (for example
+ `text_kwargs`, `audio_kwargs`, ...).
+
+ Returns:
+ [`BatchFeature`]: Processor outputs ready to be passed to [`GlmAsrForConditionalGeneration.generate`].
+
+ """
+
+ if isinstance(audio, str):
+ audio_items: list[str | np.ndarray] = [audio]
+ elif isinstance(audio, (list, tuple)) and audio and all(isinstance(el, str) for el in audio):
+ audio_items = list(audio)
+ else:
+ audio_items = list(make_list_of_audio(audio))
+ if is_torch_available():
+ audio_items = [el.detach().cpu().numpy() if isinstance(el, torch.Tensor) else el for el in audio_items]
+
+ batch_size = len(audio_items)
+ if batch_size == 0:
+ raise ValueError("`audio` must contain at least one sample.")
+
+ if prompt is None:
+ prompts = [self.default_transcription_prompt] * batch_size
+ elif isinstance(prompt, str):
+ prompts = [prompt] * batch_size
+ elif isinstance(prompt, (list, tuple)):
+ if len(prompt) != batch_size:
+ raise ValueError(
+ f"Received {len(prompt)} prompt(s) for {batch_size} audio sample(s); counts must match."
+ )
+ prompts = []
+ for item in prompt:
+ if item is None:
+ prompts.append(self.default_transcription_prompt)
+ elif isinstance(item, str):
+ prompts.append(item)
+ else:
+ raise TypeError("Each prompt must be a string or `None`.")
+ else:
+ raise TypeError("`prompt` must be a string, a sequence of strings, or `None`.")
+
+ conversations = [
+ [
+ {
+ "role": "user",
+ "content": [
+ {"type": "audio", "path": audio_item}
+ if isinstance(audio_item, str)
+ else {"type": "audio", "audio": audio_item},
+ {"type": "text", "text": prompt_text},
+ ],
+ }
+ ]
+ for prompt_text, audio_item in zip(prompts, audio_items)
+ ]
+
+ return self.apply_chat_template(
+ conversations,
+ tokenize=True,
+ add_generation_prompt=True,
+ return_dict=True,
+ **kwargs,
+ )
+
+ def decode(self, *args, strip_prefix=False, **kwargs):
+ """
+ Forward arguments to [`~PreTrainedTokenizer.decode`] and optionally remove the assistant framing the model
+ was trained to produce.
+
+ AF3 transcription requests respond with sentences such as `"The spoken content of the audio is \"...\"."`.
+ Setting `strip_prefix=True` trims the fixed prefix for just the transcription text.
+ """
+ decoded = self.tokenizer.decode(*args, **kwargs)
+ if strip_prefix:
+ decoded = [self._strip_assistant_prefix_and_quotes(text) for text in decoded]
+ return decoded
+
+ def batch_decode(self, *args, **kwargs):
+ """BC as previous examples used batch_decode"""
+ return self.decode(*args, **kwargs)
+
+ def _strip_assistant_prefix_and_quotes(self, text: str) -> str:
+ """
+ Remove the assistant prefix and surrounding quotes from a decoded transcription string.
+ """
+
+ stripped = text.strip()
+
+ for prefix in (
+ "The spoken content of the audio is",
+ "The transcription of the audio is",
+ "The content of the input audio is",
+ ):
+ if stripped.startswith(prefix):
+ stripped = stripped[len(prefix) :].strip()
+ break
+
+ if stripped.endswith("."):
+ stripped = stripped[:-1].strip()
+
+ if len(stripped) >= 2 and stripped[0] == stripped[-1] and stripped[0] in {"'", '"'}:
+ stripped = stripped[1:-1].strip()
+
+ return stripped
+
+
+__all__ = ["GlmAsrProcessor"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/got_ocr2/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/got_ocr2/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..39a2e4ce07d9e197920f97b428ede3b77deb7eb6
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/got_ocr2/__init__.py
@@ -0,0 +1,32 @@
+# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_got_ocr2 import *
+ from .image_processing_got_ocr2 import *
+ from .image_processing_pil_got_ocr2 import *
+ from .modeling_got_ocr2 import *
+ from .processing_got_ocr2 import *
+
+
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/got_ocr2/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/got_ocr2/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d6644ae945060ae0008d8aa3282436cceffabe9d
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/got_ocr2/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/got_ocr2/__pycache__/configuration_got_ocr2.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/got_ocr2/__pycache__/configuration_got_ocr2.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..30c0132bfbbe64f71fc395d696dde849f4a915a6
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/got_ocr2/__pycache__/configuration_got_ocr2.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/got_ocr2/__pycache__/image_processing_got_ocr2.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/got_ocr2/__pycache__/image_processing_got_ocr2.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2880874cf76ce93f5b0797c7f93d1fdf6d076540
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/got_ocr2/__pycache__/image_processing_got_ocr2.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/got_ocr2/__pycache__/image_processing_pil_got_ocr2.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/got_ocr2/__pycache__/image_processing_pil_got_ocr2.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e284bbfd86d7ca1737ebd73e0c119e67dd1c577e
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/got_ocr2/__pycache__/image_processing_pil_got_ocr2.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/got_ocr2/__pycache__/modeling_got_ocr2.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/got_ocr2/__pycache__/modeling_got_ocr2.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5ccefc4d86311c3697bfb6a56127197573751724
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/got_ocr2/__pycache__/modeling_got_ocr2.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/got_ocr2/__pycache__/modular_got_ocr2.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/got_ocr2/__pycache__/modular_got_ocr2.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1a108f98b2bfe417e64b031fe2431987849b419e
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/got_ocr2/__pycache__/modular_got_ocr2.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/got_ocr2/__pycache__/processing_got_ocr2.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/got_ocr2/__pycache__/processing_got_ocr2.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0f096d9e75fa4d424d2d7be2268e218fc3282f72
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/got_ocr2/__pycache__/processing_got_ocr2.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/got_ocr2/configuration_got_ocr2.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/got_ocr2/configuration_got_ocr2.py
new file mode 100644
index 0000000000000000000000000000000000000000..66ef97abfdc3b1a20af26a65ce93e911a74e66b5
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/got_ocr2/configuration_got_ocr2.py
@@ -0,0 +1,132 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/got_ocr2/modular_got_ocr2.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_got_ocr2.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2024 HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring
+from ..auto import CONFIG_MAPPING, AutoConfig
+
+
+@auto_docstring(checkpoint="facebook/sam-vit-huge")
+@strict
+class GotOcr2VisionConfig(PreTrainedConfig):
+ r"""
+ output_channels (`int`, *optional*, defaults to 256):
+ Dimensionality of the output channels in the Patch Encoder.
+ use_abs_pos (`bool`, *optional*, defaults to `True`):
+ Whether to use absolute position embedding.
+ use_rel_pos (`bool`, *optional*, defaults to `True`):
+ Whether to use relative position embedding.
+ window_size (`int`, *optional*, defaults to 14):
+ Window size for relative position.
+ global_attn_indexes (`list[int]`, *optional*, defaults to `[2, 5, 8, 11]`):
+ The indexes of the global attention layers.
+ mlp_dim (`int`, *optional*, defaults to 3072):
+ The dimensionality of the MLP layer in the Transformer encoder.
+ """
+
+ base_config_key = "vision_config"
+ hidden_size: int = 768
+ output_channels: int = 256
+ num_hidden_layers: int = 12
+ num_attention_heads: int = 12
+ num_channels: int = 3
+ image_size: int | list[int] | tuple[int, int] = 1024
+ patch_size: int | list[int] | tuple[int, int] = 16
+ hidden_act: str = "gelu"
+ layer_norm_eps: float = 1e-06
+ attention_dropout: float | int = 0.0
+ initializer_range: float = 1e-10
+ qkv_bias: bool = True
+ use_abs_pos: bool = True
+ use_rel_pos: bool = True
+ window_size: int = 14
+ global_attn_indexes: list[int] | tuple[int, ...] = (2, 5, 8, 11)
+ mlp_dim: int = 3072
+
+
+@auto_docstring(checkpoint="facebook/sam-vit-huge")
+@strict
+class GotOcr2Config(PreTrainedConfig):
+ r"""
+ Example:
+
+ ```python
+ >>> from transformers import GotOcr2ForConditionalGeneration, GotOcr2Config
+
+ >>> # Initializing a GotOcr2 style configuration
+ >>> configuration = GotOcr2Config()
+
+ >>> # Initializing a model from the Qwen2-VL-7B style configuration
+ >>> model = GotOcr2ForConditionalGeneration(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "got_ocr2"
+ attribute_map = {
+ "image_token_id": "image_token_index",
+ }
+ sub_configs = {"text_config": AutoConfig, "vision_config": GotOcr2VisionConfig}
+
+ vision_config: dict | PreTrainedConfig | None = None
+ text_config: dict | PreTrainedConfig | None = None
+ image_token_index: int = 151859
+ image_seq_length: int = 576
+ tie_word_embeddings: bool = True
+
+ def __post_init__(self, **kwargs):
+ if self.vision_config is None:
+ self.vision_config = GotOcr2VisionConfig()
+ elif isinstance(self.vision_config, dict):
+ self.vision_config = GotOcr2VisionConfig(**self.vision_config)
+
+ if isinstance(self.text_config, dict):
+ self.text_config["model_type"] = self.text_config.get("model_type", "qwen2")
+ self.text_config = CONFIG_MAPPING[self.text_config["model_type"]](**self.text_config)
+ elif self.text_config is None:
+ self.text_config = CONFIG_MAPPING["qwen2"](
+ vocab_size=151860,
+ hidden_size=1024,
+ intermediate_size=2816,
+ num_hidden_layers=24,
+ num_attention_heads=16,
+ num_key_value_heads=16,
+ hidden_act="silu",
+ max_position_embeddings=32768,
+ initializer_range=0.02,
+ rms_norm_eps=1e-6,
+ use_cache=True,
+ tie_word_embeddings=self.tie_word_embeddings,
+ rope_theta=1000000.0,
+ rope_parameters=None,
+ use_sliding_window=False,
+ sliding_window=4096,
+ max_window_layers=21,
+ attention_dropout=0.0,
+ )
+
+ super().__post_init__(**kwargs)
+
+
+__all__ = ["GotOcr2VisionConfig", "GotOcr2Config"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/got_ocr2/image_processing_got_ocr2.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/got_ocr2/image_processing_got_ocr2.py
new file mode 100644
index 0000000000000000000000000000000000000000..d035921873db5a08cd306fee5fc3ec50b3c723eb
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/got_ocr2/image_processing_got_ocr2.py
@@ -0,0 +1,307 @@
+# Copyright 2025 HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Image processor class for Got-OCR-2."""
+
+from functools import lru_cache
+
+import torch
+from torchvision.transforms.v2 import functional as tvF
+
+from ...image_processing_backends import TorchvisionBackend
+from ...image_processing_utils import BatchFeature
+from ...image_transforms import group_images_by_shape, reorder_images
+from ...image_utils import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, PILImageResampling, SizeDict
+from ...processing_utils import ImagesKwargs, Unpack
+from ...utils import (
+ TensorType,
+ auto_docstring,
+)
+
+
+class GotOcr2ImageProcessorKwargs(ImagesKwargs, total=False):
+ r"""
+ crop_to_patches (`bool`, *optional*, defaults to `self.crop_to_patches`):
+ Whether to crop the image to patches. Can be overridden by the `crop_to_patches` parameter in the
+ `preprocess` method.
+ min_patches (`int`, *optional*, defaults to `self.min_patches`):
+ The minimum number of patches to be extracted from the image. Only has an effect if `crop_to_patches` is
+ set to `True`. Can be overridden by the `min_patches` parameter in the `preprocess` method.
+ max_patches (`int`, *optional*, defaults to `self.max_patches`):
+ The maximum number of patches to be extracted from the image. Only has an effect if `crop_to_patches` is
+ set to `True`. Can be overridden by the `max_patches` parameter in the `preprocess` method.
+ """
+
+ crop_to_patches: bool
+ min_patches: int
+ max_patches: int
+
+
+@lru_cache(maxsize=10)
+def get_all_supported_aspect_ratios(min_image_tiles: int, max_image_tiles: int) -> list[tuple[int, int]]:
+ """
+ Computes all allowed aspect ratios for a given minimum and maximum number of input tiles.
+
+ This function calculates all possible arrangements of tiles that can be formed
+ within the constraint of the minimum and maximum number of tiles. Each arrangement is
+ represented by its aspect ratio (width/height) and the corresponding tile configuration.
+
+ Args:
+ min_image_tiles (`int`):
+ The minimum number of tiles allowed.
+ max_image_tiles (`int`):
+ The maximum number of tiles allowed.
+
+ Returns:
+ `list[tuple[int, int]]`: A list of tuples, each tuple representing a valid (width, height)
+ configuration in terms of number of tiles.
+
+ Example:
+ >>> get_all_supported_aspect_ratios(1, 4)
+ [(1, 1), (1, 2), (2, 1), (1, 3), (3, 1), (1, 4), (2, 2), (4, 1)]
+
+ """
+ aspect_ratios = []
+ for width in range(1, max_image_tiles + 1):
+ for height in range(1, max_image_tiles + 1):
+ if width * height <= max_image_tiles and width * height >= min_image_tiles:
+ aspect_ratios.append((width, height))
+
+ aspect_ratios = sorted(aspect_ratios, key=lambda x: x[0] * x[1])
+
+ return aspect_ratios
+
+
+@lru_cache(maxsize=100)
+def get_optimal_tiled_canvas(
+ original_image_size: tuple[int, int],
+ target_tile_size: tuple[int, int],
+ min_image_tiles: int,
+ max_image_tiles: int,
+) -> tuple[int, int]:
+ """
+ Given a minimum and maximum number of tiles, find the canvas with the closest aspect ratio to the
+ original image aspect ratio.
+ In case of tie-breaking condition when two canvases have the same aspect ratio difference, we favor the canvas with
+ more tiles, until the area covered by the tiles is more than twice the target area, in order to avoid unnecessarily
+ excessive tiling.
+ """
+ possible_tile_arrangements = get_all_supported_aspect_ratios(min_image_tiles, max_image_tiles)
+
+ original_height, original_width = original_image_size
+ target_tile_height, target_tile_width = target_tile_size
+ aspect_ratio = original_width / original_height
+ area = original_width * original_height
+
+ # find the grid with the best aspect ratio
+ best_ratio_diff = float("inf")
+ best_grid = (1, 1)
+ for grid in possible_tile_arrangements:
+ grid_aspect_ratio = grid[0] / grid[1]
+ ratio_diff = abs(aspect_ratio - grid_aspect_ratio)
+ if ratio_diff < best_ratio_diff:
+ best_ratio_diff = ratio_diff
+ best_grid = grid
+ elif ratio_diff == best_ratio_diff:
+ # if the aspect ratio difference is the same, we favor the grid with more patches
+ # until the area covered by the patches is more than twice the original image area
+ if area > 0.5 * target_tile_height * target_tile_width * grid[0] * grid[1]:
+ best_grid = grid
+
+ return best_grid
+
+
+@auto_docstring
+class GotOcr2ImageProcessor(TorchvisionBackend):
+ valid_kwargs = GotOcr2ImageProcessorKwargs
+ resample = PILImageResampling.BICUBIC
+ image_mean = OPENAI_CLIP_MEAN
+ image_std = OPENAI_CLIP_STD
+ size = {"height": 384, "width": 384}
+ do_resize = True
+ do_rescale = True
+ do_normalize = True
+ do_convert_rgb = True
+ crop_to_patches = False
+ min_patches = 1
+ max_patches = 12
+
+ def __init__(self, **kwargs: Unpack[GotOcr2ImageProcessorKwargs]):
+ super().__init__(**kwargs)
+
+ def crop_image_to_patches(
+ self,
+ images: "torch.Tensor",
+ min_patches: int,
+ max_patches: int,
+ use_thumbnail: bool = True,
+ patch_size: SizeDict | None = None,
+ resample: "PILImageResampling | tvF.InterpolationMode | int | None" = None,
+ ):
+ """
+ Crop the images to patches and return a list of cropped images.
+ The number of patches and their grid arrangement are determined by the original image size,
+ the target patch size and the minimum and maximum number of patches.
+ The aspect ratio of the patches grid is chosen to be the closest to the original image aspect ratio.
+
+ Args:
+ images (`torch.Tensor`):
+ The images to be cropped.
+ min_patches (`int`):
+ The minimum number of patches to be extracted from the image.
+ max_patches (`int`):
+ The maximum number of patches to be extracted from the image.
+ use_thumbnail (`bool`, *optional*, defaults to `True`):
+ Whether to add a thumbnail image to the list of cropped patches.
+ patch_size (`SizeDict`, *optional*):
+ The size of the output patches.
+ resample (`PILImageResampling | tvF.InterpolationMode | int | None`, *optional*):
+ Resampling filter to use when resizing.
+ """
+ patch_size_height, patch_size_width = patch_size.height, patch_size.width
+ original_height, original_width = images.shape[-2:]
+ # find the closest aspect ratio to the target
+ num_columns, num_rows = get_optimal_tiled_canvas(
+ (original_height, original_width), (patch_size_height, patch_size_width), min_patches, max_patches
+ )
+
+ # calculate the target width and height
+ target_width = patch_size_width * num_columns
+ target_height = patch_size_height * num_rows
+ num_blocks = num_columns * num_rows
+
+ # resize the image so that each patch is of patch_size
+ resized_image = self.resize(images, SizeDict(height=target_height, width=target_width), resample=resample)
+ # split the image into patches
+ processed_images = []
+ for i in range(num_blocks):
+ column = i % num_columns
+ row = i // num_columns
+ box = (
+ column * patch_size_width,
+ row * patch_size_height,
+ (column + 1) * patch_size_width,
+ (row + 1) * patch_size_height,
+ )
+ # split the image
+ patch_image = resized_image[..., box[1] : box[3], box[0] : box[2]]
+ processed_images.append(patch_image)
+
+ if use_thumbnail and len(processed_images) != 1:
+ thumbnail_img = self.resize(images, patch_size, resample=resample)
+ processed_images.append(thumbnail_img)
+
+ processed_images = torch.stack(processed_images, dim=0).transpose(0, 1).contiguous()
+
+ return processed_images
+
+ def _preprocess(
+ self,
+ images: list["torch.Tensor"],
+ do_resize: bool,
+ size: SizeDict,
+ resample: "PILImageResampling | tvF.InterpolationMode | int | None",
+ do_rescale: bool,
+ rescale_factor: float,
+ do_normalize: bool,
+ image_mean: float | list[float] | None,
+ image_std: float | list[float] | None,
+ disable_grouping: bool | None,
+ return_tensors: str | TensorType | None,
+ crop_to_patches: bool = False,
+ min_patches: int = 1,
+ max_patches: int = 12,
+ **kwargs,
+ ) -> BatchFeature:
+ if crop_to_patches:
+ grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping)
+ processed_images_grouped = {}
+ num_patches = {}
+ for shape, stacked_images in grouped_images.items():
+ stacked_images = self.crop_image_to_patches(
+ stacked_images,
+ min_patches,
+ max_patches,
+ patch_size=size,
+ resample=resample,
+ )
+ processed_images_grouped[shape] = stacked_images
+ num_patches[shape] = [stacked_images.shape[1]] * stacked_images.shape[0]
+ images = reorder_images(processed_images_grouped, grouped_images_index)
+ images = [image for images_list in images for image in images_list]
+ num_patches = reorder_images(num_patches, grouped_images_index)
+ else:
+ num_patches = [1] * len(images)
+
+ # Group images by size for batched resizing
+ grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping)
+ resized_images_grouped = {}
+ for shape, stacked_images in grouped_images.items():
+ if do_resize:
+ stacked_images = self.resize(image=stacked_images, size=size, resample=resample)
+ resized_images_grouped[shape] = stacked_images
+ resized_images = reorder_images(resized_images_grouped, grouped_images_index)
+
+ # Group images by size for further processing
+ # Needed in case do_resize is False, or resize returns images with different sizes
+ grouped_images, grouped_images_index = group_images_by_shape(resized_images, disable_grouping=disable_grouping)
+ processed_images_grouped = {}
+ for shape, stacked_images in grouped_images.items():
+ stacked_images = self.rescale_and_normalize(
+ stacked_images, do_rescale, rescale_factor, do_normalize, image_mean, image_std
+ )
+ processed_images_grouped[shape] = stacked_images
+
+ processed_images = reorder_images(processed_images_grouped, grouped_images_index)
+
+ return BatchFeature(
+ data={"pixel_values": processed_images, "num_patches": num_patches}, tensor_type=return_tensors
+ )
+
+ def get_number_of_image_patches(self, height: int, width: int, images_kwargs=None):
+ """
+ A utility that returns number patches for a given image size.
+
+ Args:
+ height (`int`):
+ Height of the input image.
+ width (`int`):
+ Width of the input image.
+ images_kwargs (`dict`, *optional*)
+ Any kwargs to override defaults of the image processor.
+ Returns:
+ `int`: Number of patches per image.
+ """
+ min_patches = images_kwargs.get("min_patches", self.min_patches) if images_kwargs else self.min_patches
+ max_patches = images_kwargs.get("max_patches", self.max_patches) if images_kwargs else self.max_patches
+ patch_size = images_kwargs.get("patch_size", self.size) if images_kwargs else self.size
+ crop_to_patches = (
+ images_kwargs.get("crop_to_patches", self.crop_to_patches) if images_kwargs else self.crop_to_patches
+ )
+
+ num_patches = 1
+ if crop_to_patches and max_patches > 1:
+ if isinstance(patch_size, dict):
+ patch_height, patch_width = patch_size["height"], patch_size["width"]
+ else:
+ patch_height, patch_width = patch_size.height, patch_size.width
+ num_columns, num_rows = get_optimal_tiled_canvas(
+ (height, width), (patch_height, patch_width), min_patches, max_patches
+ )
+ if num_columns * num_rows > 1:
+ num_patches += num_columns * num_rows
+
+ return num_patches
+
+
+__all__ = ["GotOcr2ImageProcessor"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/got_ocr2/image_processing_pil_got_ocr2.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/got_ocr2/image_processing_pil_got_ocr2.py
new file mode 100644
index 0000000000000000000000000000000000000000..e016a390f5ec91503f32eec03a15e384741f5f66
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/got_ocr2/image_processing_pil_got_ocr2.py
@@ -0,0 +1,310 @@
+# Copyright 2025 HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Image processor class for Got-OCR-2."""
+
+from functools import lru_cache
+
+import numpy as np
+
+from ...image_processing_backends import PilBackend
+from ...image_processing_utils import BatchFeature
+from ...image_transforms import to_channel_dimension_format
+from ...image_utils import (
+ OPENAI_CLIP_MEAN,
+ OPENAI_CLIP_STD,
+ ChannelDimension,
+ PILImageResampling,
+ SizeDict,
+ get_image_size,
+ infer_channel_dimension_format,
+)
+from ...processing_utils import ImagesKwargs, Unpack
+from ...utils import (
+ TensorType,
+ auto_docstring,
+)
+
+
+# Adapted from transformers.models.got_ocr2.image_processing_got_ocr2.GotOcr2ImageProcessorKwargs
+class GotOcr2ImageProcessorKwargs(ImagesKwargs, total=False):
+ r"""
+ crop_to_patches (`bool`, *optional*, defaults to `self.crop_to_patches`):
+ Whether to crop the image to patches. Can be overridden by the `crop_to_patches` parameter in the
+ `preprocess` method.
+ min_patches (`int`, *optional*, defaults to `self.min_patches`):
+ The minimum number of patches to be extracted from the image. Only has an effect if `crop_to_patches` is
+ set to `True`. Can be overridden by the `min_patches` parameter in the `preprocess` method.
+ max_patches (`int`, *optional*, defaults to `self.max_patches`):
+ The maximum number of patches to be extracted from the image. Only has an effect if `crop_to_patches` is
+ set to `True`. Can be overridden by the `max_patches` parameter in the `preprocess` method.
+ """
+
+ crop_to_patches: bool
+ min_patches: int
+ max_patches: int
+
+
+# Adapted from transformers.models.got_ocr2.image_processing_got_ocr2.get_all_supported_aspect_ratios
+@lru_cache(maxsize=10)
+def get_all_supported_aspect_ratios(min_image_tiles: int, max_image_tiles: int) -> list[tuple[int, int]]:
+ """
+ Computes all allowed aspect ratios for a given minimum and maximum number of input tiles.
+
+ This function calculates all possible arrangements of tiles that can be formed
+ within the constraint of the minimum and maximum number of tiles. Each arrangement is
+ represented by its aspect ratio (width/height) and the corresponding tile configuration.
+
+ Args:
+ min_image_tiles (`int`):
+ The minimum number of tiles allowed.
+ max_image_tiles (`int`):
+ The maximum number of tiles allowed.
+
+ Returns:
+ `list[tuple[int, int]]`: A list of tuples, each tuple representing a valid (width, height)
+ configuration in terms of number of tiles.
+
+ Example:
+ >>> get_all_supported_aspect_ratios(1, 4)
+ [(1, 1), (1, 2), (2, 1), (1, 3), (3, 1), (1, 4), (2, 2), (4, 1)]
+
+ """
+ aspect_ratios = []
+ for width in range(1, max_image_tiles + 1):
+ for height in range(1, max_image_tiles + 1):
+ if width * height <= max_image_tiles and width * height >= min_image_tiles:
+ aspect_ratios.append((width, height))
+
+ aspect_ratios = sorted(aspect_ratios, key=lambda x: x[0] * x[1])
+
+ return aspect_ratios
+
+
+# Adapted from transformers.models.got_ocr2.image_processing_got_ocr2.get_optimal_tiled_canvas
+@lru_cache(maxsize=100)
+def get_optimal_tiled_canvas(
+ original_image_size: tuple[int, int],
+ target_tile_size: tuple[int, int],
+ min_image_tiles: int,
+ max_image_tiles: int,
+) -> tuple[int, int]:
+ """
+ Given a minimum and maximum number of tiles, find the canvas with the closest aspect ratio to the
+ original image aspect ratio.
+ In case of tie-breaking condition when two canvases have the same aspect ratio difference, we favor the canvas with
+ more tiles, until the area covered by the tiles is more than twice the target area, in order to avoid unnecessarily
+ excessive tiling.
+ """
+ possible_tile_arrangements = get_all_supported_aspect_ratios(min_image_tiles, max_image_tiles)
+
+ original_height, original_width = original_image_size
+ target_tile_height, target_tile_width = target_tile_size
+ aspect_ratio = original_width / original_height
+ area = original_width * original_height
+
+ # find the grid with the best aspect ratio
+ best_ratio_diff = float("inf")
+ best_grid = (1, 1)
+ for grid in possible_tile_arrangements:
+ grid_aspect_ratio = grid[0] / grid[1]
+ ratio_diff = abs(aspect_ratio - grid_aspect_ratio)
+ if ratio_diff < best_ratio_diff:
+ best_ratio_diff = ratio_diff
+ best_grid = grid
+ elif ratio_diff == best_ratio_diff:
+ # if the aspect ratio difference is the same, we favor the grid with more patches
+ # until the area covered by the patches is more than twice the original image area
+ if area > 0.5 * target_tile_height * target_tile_width * grid[0] * grid[1]:
+ best_grid = grid
+
+ return best_grid
+
+
+@auto_docstring
+class GotOcr2ImageProcessorPil(PilBackend):
+ valid_kwargs = GotOcr2ImageProcessorKwargs
+ resample = PILImageResampling.BICUBIC
+ image_mean = OPENAI_CLIP_MEAN
+ image_std = OPENAI_CLIP_STD
+ size = {"height": 384, "width": 384}
+ do_resize = True
+ do_rescale = True
+ do_normalize = True
+ do_convert_rgb = True
+ crop_to_patches = False
+ min_patches = 1
+ max_patches = 12
+
+ def __init__(self, **kwargs: Unpack[GotOcr2ImageProcessorKwargs]):
+ super().__init__(**kwargs)
+
+ def crop_image_to_patches(
+ self,
+ image: np.ndarray,
+ min_patches: int,
+ max_patches: int,
+ use_thumbnail: bool = True,
+ patch_size: SizeDict | None = None,
+ resample: "PILImageResampling | None" = None,
+ ):
+ """
+ Crop the image to patches and return a list of cropped images.
+ The number of patches and their grid arrangement are determined by the original image size,
+ the target patch size and the minimum and maximum number of patches.
+ The aspect ratio of the patches grid is chosen to be the closest to the original image aspect ratio.
+
+ Args:
+ image (`np.ndarray`):
+ The image to be cropped.
+ min_patches (`int`):
+ The minimum number of patches to be extracted from the image.
+ max_patches (`int`):
+ The maximum number of patches to be extracted from the image.
+ use_thumbnail (`bool`, *optional*, defaults to `True`):
+ Whether to add a thumbnail image to the list of cropped patches.
+ patch_size (`SizeDict`, *optional*):
+ The size of the output patches.
+ resample (`PILImageResampling | int | None`, *optional*):
+ Resampling filter to use when resizing.
+ """
+ # Ensure image is in CHW format for processing
+ input_data_format = infer_channel_dimension_format(image)
+ image = to_channel_dimension_format(image, ChannelDimension.FIRST, input_data_format)
+
+ patch_size_height, patch_size_width = patch_size.height, patch_size.width
+ original_height, original_width = get_image_size(image, channel_dim=ChannelDimension.FIRST)
+ # find the closest aspect ratio to the target
+ num_columns, num_rows = get_optimal_tiled_canvas(
+ (original_height, original_width), (patch_size_height, patch_size_width), min_patches, max_patches
+ )
+
+ # calculate the target width and height
+ target_width = patch_size_width * num_columns
+ target_height = patch_size_height * num_rows
+ num_blocks = num_columns * num_rows
+
+ # resize the image so that each patch is of patch_size
+ resized_image = self.resize(image, SizeDict(height=target_height, width=target_width), resample=resample)
+ # split the image into patches
+ processed_images = []
+ for i in range(num_blocks):
+ column = i % num_columns
+ row = i // num_columns
+ box = (
+ column * patch_size_width,
+ row * patch_size_height,
+ (column + 1) * patch_size_width,
+ (row + 1) * patch_size_height,
+ )
+ # split the image (images are CHW format)
+ patch_image = resized_image[..., box[1] : box[3], box[0] : box[2]]
+ # Convert back to original format
+ patch_image = to_channel_dimension_format(patch_image, input_data_format, ChannelDimension.FIRST)
+ processed_images.append(patch_image)
+
+ if use_thumbnail and len(processed_images) != 1:
+ thumbnail_img = self.resize(image, patch_size, resample=resample)
+ thumbnail_img = to_channel_dimension_format(thumbnail_img, input_data_format, ChannelDimension.FIRST)
+ processed_images.append(thumbnail_img)
+
+ return processed_images
+
+ def _preprocess(
+ self,
+ images: list[np.ndarray],
+ do_resize: bool,
+ size: SizeDict,
+ resample: "PILImageResampling | None",
+ do_rescale: bool,
+ rescale_factor: float,
+ do_normalize: bool,
+ image_mean: float | list[float] | None,
+ image_std: float | list[float] | None,
+ return_tensors: str | TensorType | None,
+ crop_to_patches: bool = False,
+ min_patches: int = 1,
+ max_patches: int = 12,
+ **kwargs,
+ ) -> BatchFeature:
+ num_patches = []
+ processed_images = []
+
+ for image in images:
+ if crop_to_patches and max_patches > 1:
+ patches = self.crop_image_to_patches(
+ image,
+ min_patches,
+ max_patches,
+ patch_size=size,
+ resample=resample,
+ )
+ num_patches.append(len(patches))
+ # Normalize and rescale patches
+ for patch in patches:
+ if do_rescale:
+ patch = self.rescale(patch, rescale_factor)
+ if do_normalize:
+ patch = self.normalize(patch, image_mean, image_std)
+ processed_images.append(patch)
+ else:
+ num_patches.append(1)
+ if do_resize:
+ image = self.resize(image, size, resample)
+ if do_rescale:
+ image = self.rescale(image, rescale_factor)
+ if do_normalize:
+ image = self.normalize(image, image_mean, image_std)
+ processed_images.append(image)
+
+ return BatchFeature(
+ data={"pixel_values": processed_images, "num_patches": num_patches}, tensor_type=return_tensors
+ )
+
+ def get_number_of_image_patches(self, height: int, width: int, images_kwargs=None):
+ """
+ A utility that returns number patches for a given image size.
+
+ Args:
+ height (`int`):
+ Height of the input image.
+ width (`int`):
+ Width of the input image.
+ images_kwargs (`dict`, *optional*)
+ Any kwargs to override defaults of the image processor.
+ Returns:
+ `int`: Number of patches per image.
+ """
+ min_patches = images_kwargs.get("min_patches", self.min_patches) if images_kwargs else self.min_patches
+ max_patches = images_kwargs.get("max_patches", self.max_patches) if images_kwargs else self.max_patches
+ patch_size = images_kwargs.get("patch_size", self.size) if images_kwargs else self.size
+ crop_to_patches = (
+ images_kwargs.get("crop_to_patches", self.crop_to_patches) if images_kwargs else self.crop_to_patches
+ )
+
+ num_patches = 1
+ if crop_to_patches and max_patches > 1:
+ if isinstance(patch_size, dict):
+ patch_height, patch_width = patch_size["height"], patch_size["width"]
+ else:
+ patch_height, patch_width = patch_size.height, patch_size.width
+ num_columns, num_rows = get_optimal_tiled_canvas(
+ (height, width), (patch_height, patch_width), min_patches, max_patches
+ )
+ if num_columns * num_rows > 1:
+ num_patches += num_columns * num_rows
+
+ return num_patches
+
+
+__all__ = ["GotOcr2ImageProcessorPil"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/got_ocr2/modeling_got_ocr2.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/got_ocr2/modeling_got_ocr2.py
new file mode 100644
index 0000000000000000000000000000000000000000..add27ed822a5a7e7d5025174fcd9703e36eb60f4
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/got_ocr2/modeling_got_ocr2.py
@@ -0,0 +1,771 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/got_ocr2/modular_got_ocr2.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_got_ocr2.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2024 HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+import collections
+from dataclasses import dataclass
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...cache_utils import Cache
+from ...generation import GenerationMixin
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import BaseModelOutputWithPast, BaseModelOutputWithPooling, ModelOutput
+from ...modeling_utils import PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, torch_compilable_check
+from ...utils.generic import merge_with_config_defaults
+from ...utils.output_capturing import capture_outputs
+from ..auto import AutoModel
+from .configuration_got_ocr2 import GotOcr2Config, GotOcr2VisionConfig
+
+
+class GotOcr2MLPBlock(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.lin1 = nn.Linear(config.hidden_size, config.mlp_dim)
+ self.lin2 = nn.Linear(config.mlp_dim, config.hidden_size)
+ self.act = ACT2FN[config.hidden_act]
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.lin1(hidden_states)
+ hidden_states = self.act(hidden_states)
+ hidden_states = self.lin2(hidden_states)
+ return hidden_states
+
+
+class GotOcr2VisionAttention(nn.Module):
+ """Multi-head Attention block with relative position embeddings."""
+
+ def __init__(self, config, window_size):
+ super().__init__()
+ input_size = (
+ (config.image_size // config.patch_size, config.image_size // config.patch_size)
+ if window_size == 0
+ else (window_size, window_size)
+ )
+
+ self.num_attention_heads = config.num_attention_heads
+ head_dim = config.hidden_size // config.num_attention_heads
+ self.scale = head_dim**-0.5
+ self.dropout = config.attention_dropout
+
+ self.qkv = nn.Linear(config.hidden_size, config.hidden_size * 3, bias=config.qkv_bias)
+ self.proj = nn.Linear(config.hidden_size, config.hidden_size)
+
+ self.use_rel_pos = config.use_rel_pos
+ if self.use_rel_pos:
+ if input_size is None:
+ raise ValueError("Input size must be provided if using relative positional encoding.")
+
+ # initialize relative positional embeddings
+ self.rel_pos_h = nn.Parameter(torch.zeros(2 * input_size[0] - 1, head_dim))
+ self.rel_pos_w = nn.Parameter(torch.zeros(2 * input_size[1] - 1, head_dim))
+
+ def get_rel_pos(self, q_size: int, k_size: int, rel_pos: torch.Tensor) -> torch.Tensor:
+ """
+ Get relative positional embeddings according to the relative positions of
+ query and key sizes.
+
+ Args:
+ q_size (int):
+ size of the query.
+ k_size (int):
+ size of key k.
+ rel_pos (`torch.Tensor`):
+ relative position embeddings (L, channel).
+
+ Returns:
+ Extracted positional embeddings according to relative positions.
+ """
+ max_rel_dist = int(2 * max(q_size, k_size) - 1)
+ # Interpolate rel pos.
+ rel_pos_resized = F.interpolate(
+ rel_pos.reshape(1, rel_pos.shape[0], -1).transpose(1, 2),
+ size=max_rel_dist,
+ mode="linear",
+ )
+ rel_pos_resized = rel_pos_resized.reshape(-1, max_rel_dist).permute(1, 0)
+
+ # Scale the coords with short length if shapes for q and k are different.
+ q_coords = torch.arange(q_size)[:, None] * max(k_size / q_size, 1.0)
+ k_coords = torch.arange(k_size)[None, :] * max(q_size / k_size, 1.0)
+ relative_coords = (q_coords - k_coords) + (k_size - 1) * max(q_size / k_size, 1.0)
+
+ return rel_pos_resized[relative_coords.long()]
+
+ def get_decomposed_rel_pos(
+ self,
+ query: torch.Tensor,
+ rel_pos_h: torch.Tensor,
+ rel_pos_w: torch.Tensor,
+ q_size: tuple[int, int],
+ k_size: tuple[int, int],
+ ) -> torch.Tensor:
+ """
+ Calculate decomposed Relative Positional Embeddings from :paper:`mvitv2`.
+ https://github.com/facebookresearch/mvit/blob/19786631e330df9f3622e5402b4a419a263a2c80/mvit/models/attention.py
+
+ Args:
+ query (`torch.Tensor`):
+ query q in the attention layer with shape (batch_size, query_height * query_width, channel).
+ rel_pos_h (`torch.Tensor`):
+ relative position embeddings (Lh, channel) for height axis.
+ rel_pos_w (`torch.Tensor`):
+ relative position embeddings (Lw, channel) for width axis.
+ q_size (tuple):
+ spatial sequence size of query q with (query_height, query_width).
+ k_size (tuple):
+ spatial sequence size of key k with (key_height, key_width).
+
+ Returns:
+ decomposed_rel_pos (`torch.Tensor`):
+ decomposed relative position embeddings.
+ """
+ query_height, query_width = q_size
+ key_height, key_width = k_size
+ relative_position_height = self.get_rel_pos(query_height, key_height, rel_pos_h)
+ relative_position_width = self.get_rel_pos(query_width, key_width, rel_pos_w)
+
+ batch_size, _, dim = query.shape
+ reshaped_query = query.reshape(batch_size, query_height, query_width, dim)
+ rel_h = torch.einsum("bhwc,hkc->bhwk", reshaped_query, relative_position_height)
+ rel_w = torch.einsum("bhwc,wkc->bhwk", reshaped_query, relative_position_width)
+
+ decomposed_rel_pos = rel_h[:, :, :, :, None] + rel_w[:, :, :, None, :]
+
+ return decomposed_rel_pos
+
+ def forward(self, hidden_states: torch.Tensor, output_attentions=None) -> tuple[torch.Tensor, torch.Tensor]:
+ batch_size, height, width, _ = hidden_states.shape
+ # qkv with shape (3, batch_size, nHead, height * width, channel)
+ qkv = (
+ self.qkv(hidden_states)
+ .reshape(batch_size, height * width, 3, self.num_attention_heads, -1)
+ .permute(2, 0, 3, 1, 4)
+ )
+ # q, k, v with shape (batch_size * nHead, height * width, channel)
+ query, key, value = qkv.reshape(3, batch_size * self.num_attention_heads, height * width, -1).unbind(0)
+
+ attn_weights = (query * self.scale) @ key.transpose(-2, -1)
+
+ if self.use_rel_pos:
+ decomposed_rel_pos = self.get_decomposed_rel_pos(
+ query, self.rel_pos_h, self.rel_pos_w, (height, width), (height, width)
+ )
+ decomposed_rel_pos = decomposed_rel_pos.reshape_as(attn_weights)
+ attn_weights = attn_weights + decomposed_rel_pos
+
+ attn_weights = torch.nn.functional.softmax(attn_weights, dtype=torch.float32, dim=-1).to(query.dtype)
+
+ attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
+
+ attn_output = (attn_probs @ value).reshape(batch_size, self.num_attention_heads, height, width, -1)
+ attn_output = attn_output.permute(0, 2, 3, 1, 4).reshape(batch_size, height, width, -1)
+
+ attn_output = self.proj(attn_output)
+ return attn_output, attn_weights
+
+
+class GotOcr2VisionLayer(GradientCheckpointingLayer):
+ def __init__(self, config, window_size):
+ super().__init__()
+ self.layer_norm1 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.attn = GotOcr2VisionAttention(config, window_size)
+ self.layer_norm2 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.mlp = GotOcr2MLPBlock(config)
+ self.window_size = window_size
+
+ def window_partition(self, hidden_states: torch.Tensor, window_size: int) -> tuple[torch.Tensor, tuple[int, int]]:
+ """
+ Args:
+ Partition into non-overlapping windows with padding if needed.
+ hidden_states (tensor): input tokens with [batch_size, height, width, channel]. window_size (int): window
+ size.
+
+ Returns:
+ windows: windows after partition with [batch_size * num_windows, window_size, window_size, channel].
+ (pad_height, pad_width): padded height and width before partition
+ """
+ batch_size, height, width, channel = hidden_states.shape
+
+ pad_h = (window_size - height % window_size) % window_size
+ pad_w = (window_size - width % window_size) % window_size
+ hidden_states = F.pad(hidden_states, (0, 0, 0, pad_w, 0, pad_h))
+ pad_height, pad_width = height + pad_h, width + pad_w
+
+ hidden_states = hidden_states.reshape(
+ batch_size, pad_height // window_size, window_size, pad_width // window_size, window_size, channel
+ )
+ windows = hidden_states.permute(0, 1, 3, 2, 4, 5).contiguous().reshape(-1, window_size, window_size, channel)
+ return windows, (pad_height, pad_width)
+
+ def window_unpartition(
+ self, windows: torch.Tensor, window_size: int, padding_shape: tuple[int, int], original_shape: tuple[int, int]
+ ) -> torch.Tensor:
+ """
+ Args:
+ Window unpartition into original sequences and removing padding.
+ hidden_states (tensor):
+ input tokens with [batch_size * num_windows, window_size, window_size, channel].
+ window_size (int):
+ window size.
+ padding_shape (Tuple):
+ padded height and width (pad_height, pad_width).
+ original_shape (Tuple): original height and width (height, width) before padding.
+
+ Returns:
+ hidden_states: unpartitioned sequences with [batch_size, height, width, channel].
+ """
+ pad_height, pad_width = padding_shape
+ height, width = original_shape
+ batch_size = windows.shape[0] // (pad_height * pad_width // window_size // window_size)
+ hidden_states = windows.reshape(
+ batch_size, pad_height // window_size, pad_width // window_size, window_size, window_size, -1
+ )
+ hidden_states = (
+ hidden_states.permute(0, 1, 3, 2, 4, 5).contiguous().reshape(batch_size, pad_height, pad_width, -1)
+ )
+
+ hidden_states = hidden_states[:, :height, :width, :].contiguous()
+ return hidden_states
+
+ def forward(self, hidden_states: torch.Tensor) -> tuple[torch.FloatTensor]:
+ residual = hidden_states
+ hidden_states = self.layer_norm1(hidden_states)
+ # Window partition
+ if self.window_size > 0:
+ height, width = hidden_states.shape[1], hidden_states.shape[2]
+ hidden_states, padding_shape = self.window_partition(hidden_states, self.window_size)
+
+ hidden_states, attn_weights = self.attn(
+ hidden_states=hidden_states,
+ )
+ # Reverse window partition
+ if self.window_size > 0:
+ hidden_states = self.window_unpartition(hidden_states, self.window_size, padding_shape, (height, width))
+
+ hidden_states = residual + hidden_states
+ layernorm_output = self.layer_norm2(hidden_states)
+ hidden_states = hidden_states + self.mlp(layernorm_output)
+ return hidden_states
+
+
+@auto_docstring
+class GotOcr2PreTrainedModel(PreTrainedModel):
+ config: GotOcr2Config
+ base_model_prefix = "model"
+ input_modalities = ("image", "text")
+ supports_gradient_checkpointing = True
+ _skip_keys_device_placement = ["past_key_values"]
+ _supports_flash_attn = False
+ _supports_sdpa = False
+
+ _can_compile_fullgraph = True
+ _supports_flex_attn = False
+ _supports_attention_backend = True
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ super()._init_weights(module)
+ if isinstance(module, GotOcr2VisionAttention):
+ if module.use_rel_pos:
+ init.zeros_(module.rel_pos_h)
+ init.zeros_(module.rel_pos_w)
+ elif isinstance(module, GotOcr2VisionEncoder):
+ if module.pos_embed is not None:
+ init.zeros_(module.pos_embed)
+
+
+@auto_docstring(
+ custom_intro="""
+ Base class for got_ocr2 vision model's outputs that also contains image embeddings obtained by applying the projection
+ layer to the pooler_output.
+ """
+)
+@dataclass
+class GotOcr2VisionEncoderOutput(ModelOutput):
+ r"""
+ image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
+ The image embeddings obtained by applying the projection layer to the pooler_output.
+ """
+
+ image_embeds: torch.FloatTensor | None = None
+ last_hidden_state: torch.FloatTensor | None = None
+ hidden_states: tuple[torch.FloatTensor, ...] | None = None
+ attentions: tuple[torch.FloatTensor, ...] | None = None
+
+
+class GotOcr2PatchEmbeddings(nn.Module):
+ """
+ This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
+ `hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
+ Transformer.
+ """
+
+ def __init__(self, config):
+ super().__init__()
+ image_size, patch_size = config.image_size, config.patch_size
+ num_channels, hidden_size = config.num_channels, config.hidden_size
+ image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
+ patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
+ num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
+ self.image_size = image_size
+ self.patch_size = patch_size
+ self.num_channels = num_channels
+ self.num_patches = num_patches
+
+ self.projection = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=patch_size)
+
+ def forward(self, pixel_values):
+ batch_size, num_channels, height, width = pixel_values.shape
+ if num_channels != self.num_channels:
+ raise ValueError(
+ "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
+ )
+ if height != self.image_size[0] or width != self.image_size[1]:
+ raise ValueError(
+ f"Input image size ({height}*{width}) doesn't match model ({self.image_size[0]}*{self.image_size[1]})."
+ )
+ embeddings = self.projection(pixel_values).permute(0, 2, 3, 1)
+ return embeddings
+
+
+class GotOcr2LayerNorm(nn.LayerNorm):
+ r"""LayerNorm that supports two data formats: channels_last (default) or channels_first.
+ The ordering of the dimensions in the inputs. channels_last corresponds to inputs with shape (batch_size, height,
+ width, channels) while channels_first corresponds to inputs with shape (batch_size, channels, height, width).
+ """
+
+ def __init__(self, normalized_shape, *, eps=1e-6, data_format="channels_last", **kwargs):
+ super().__init__(normalized_shape, eps=eps, **kwargs)
+ if data_format not in ["channels_last", "channels_first"]:
+ raise NotImplementedError(f"Unsupported data format: {data_format}")
+ self.data_format = data_format
+
+ def forward(self, features: torch.Tensor) -> torch.Tensor:
+ """
+ Args:
+ features: Tensor of shape (batch_size, channels, height, width) OR (batch_size, height, width, channels)
+ """
+ if self.data_format == "channels_first":
+ features = features.permute(0, 2, 3, 1)
+ features = super().forward(features)
+ features = features.permute(0, 3, 1, 2)
+ else:
+ features = super().forward(features)
+ return features
+
+
+class GotOcr2VisionNeck(nn.Module):
+ def __init__(self, config: GotOcr2VisionConfig):
+ super().__init__()
+ self.config = config
+
+ self.conv1 = nn.Conv2d(config.hidden_size, config.output_channels, kernel_size=1, bias=False)
+ self.layer_norm1 = GotOcr2LayerNorm(config.output_channels, data_format="channels_first")
+ self.conv2 = nn.Conv2d(config.output_channels, config.output_channels, kernel_size=3, padding=1, bias=False)
+ self.layer_norm2 = GotOcr2LayerNorm(config.output_channels, data_format="channels_first")
+
+ def forward(self, hidden_states):
+ hidden_states = hidden_states.permute(0, 3, 1, 2)
+ hidden_states = self.conv1(hidden_states)
+ hidden_states = self.layer_norm1(hidden_states)
+
+ hidden_states = self.conv2(hidden_states)
+ hidden_states = self.layer_norm2(hidden_states)
+ return hidden_states
+
+
+class GotOcr2VisionEncoder(GotOcr2PreTrainedModel):
+ _can_record_outputs = {"hidden_states": GotOcr2VisionLayer, "attentions": GotOcr2VisionAttention}
+ input_modalities = ("image",)
+
+ def __init__(self, config: GotOcr2VisionConfig):
+ super().__init__(config)
+ self.config = config
+ self.image_size = config.image_size
+ self.patch_embed = GotOcr2PatchEmbeddings(config)
+
+ self.pos_embed = None
+ if config.use_abs_pos:
+ # Initialize absolute positional embedding with pretrain image size.
+ self.pos_embed = nn.Parameter(
+ torch.zeros(
+ 1,
+ config.image_size // config.patch_size,
+ config.image_size // config.patch_size,
+ config.hidden_size,
+ )
+ )
+
+ self.layers = nn.ModuleList()
+ for i in range(config.num_hidden_layers):
+ layer = GotOcr2VisionLayer(
+ config,
+ window_size=config.window_size if i not in config.global_attn_indexes else 0,
+ )
+ self.layers.append(layer)
+
+ self.neck = GotOcr2VisionNeck(config)
+
+ self.gradient_checkpointing = False
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.patch_embed
+
+ @merge_with_config_defaults
+ @capture_outputs(tie_last_hidden_states=False)
+ def forward(
+ self, pixel_values: torch.FloatTensor | None = None, **kwargs: Unpack[TransformersKwargs]
+ ) -> tuple | GotOcr2VisionEncoderOutput:
+ if pixel_values is None:
+ raise ValueError("You have to specify pixel_values")
+
+ hidden_states = self.patch_embed(pixel_values)
+ if self.pos_embed is not None:
+ hidden_states = hidden_states + self.pos_embed
+ for layer_module in self.layers:
+ hidden_states = layer_module(hidden_states)
+ hidden_states = self.neck(hidden_states)
+ return GotOcr2VisionEncoderOutput(
+ last_hidden_state=hidden_states,
+ )
+
+
+class GotOcr2MultiModalProjector(nn.Module):
+ def __init__(self, config: GotOcr2Config):
+ super().__init__()
+ vision_output_channels = config.vision_config.output_channels
+ language_hidden_size = config.text_config.hidden_size
+ self.conv_upsampler1 = nn.Conv2d(
+ vision_output_channels, vision_output_channels * 2, kernel_size=3, stride=2, padding=1, bias=False
+ )
+ self.conv_upsampler2 = nn.Conv2d(
+ vision_output_channels * 2, language_hidden_size, kernel_size=3, stride=2, padding=1, bias=False
+ )
+ self.multimodal_projector = nn.Linear(language_hidden_size, language_hidden_size)
+
+ def forward(self, vision_embeddings: torch.Tensor) -> torch.Tensor:
+ hidden_state = self.conv_upsampler1(vision_embeddings)
+ hidden_state = self.conv_upsampler2(hidden_state)
+ hidden_state = hidden_state.flatten(2).permute(0, 2, 1)
+ hidden_state = self.multimodal_projector(hidden_state)
+ return hidden_state
+
+
+@auto_docstring(
+ custom_intro="""
+ Base class for GotOcr2 causal language model (or autoregressive) outputs.
+ """
+)
+@dataclass
+class GotOcr2CausalLMOutputWithPast(ModelOutput):
+ r"""
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
+ Language modeling loss (for next-token prediction).
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
+ past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
+ It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
+
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
+ `past_key_values` input) to speed up sequential decoding.
+ image_hidden_states (`torch.FloatTensor`, *optional*):
+ A `torch.FloatTensor` of size `(batch_size, num_images, sequence_length, hidden_size)`.
+ image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
+ """
+
+ loss: torch.FloatTensor | None = None
+ logits: torch.FloatTensor | None = None
+ past_key_values: Cache | None = None
+ hidden_states: tuple[torch.FloatTensor] | None = None
+ attentions: tuple[torch.FloatTensor] | None = None
+ image_hidden_states: torch.FloatTensor | None = None
+
+
+@auto_docstring(
+ custom_intro="""
+ Base class for GotOcr2 outputs, with hidden states and attentions.
+ """
+)
+@dataclass
+class GotOcr2ModelOutputWithPast(BaseModelOutputWithPast):
+ r"""
+ past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
+ It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
+
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
+ `past_key_values` input) to speed up sequential decoding.
+ image_hidden_states (`torch.FloatTensor`, *optional*):
+ A `torch.FloatTensor` of size `(batch_size, num_images, sequence_length, hidden_size)`.
+ image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
+ """
+
+ image_hidden_states: torch.FloatTensor | None = None
+
+
+@auto_docstring(
+ custom_intro="""
+ The GotOcr2 model which consists of a vision backbone and a language model, without a language modeling head.
+ """
+)
+class GotOcr2Model(GotOcr2PreTrainedModel):
+ def __init__(self, config: GotOcr2Config):
+ super().__init__(config)
+ self.vision_tower = GotOcr2VisionEncoder(config.vision_config)
+
+ self.multi_modal_projector = GotOcr2MultiModalProjector(config)
+ self.language_model = AutoModel.from_config(config.text_config)
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring(
+ custom_intro="Obtains image last hidden states from the vision tower and apply multimodal projection."
+ )
+ def get_image_features(
+ self,
+ pixel_values: torch.FloatTensor,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutputWithPooling:
+ image_outputs = self.vision_tower(pixel_values, return_dict=True, **kwargs)
+ last_hidden_state = image_outputs.last_hidden_state
+ image_outputs.pooler_output = self.multi_modal_projector(last_hidden_state)
+
+ return image_outputs
+
+ def get_placeholder_mask(
+ self, input_ids: torch.LongTensor, inputs_embeds: torch.FloatTensor, image_features: torch.FloatTensor
+ ):
+ """
+ Obtains multimodal placeholder mask from `input_ids` or `inputs_embeds`, and checks that the placeholder token count is
+ equal to the length of multimodal features. If the lengths are different, an error is raised.
+ """
+ if input_ids is None:
+ special_image_mask = inputs_embeds == self.get_input_embeddings()(
+ torch.tensor(self.config.image_token_id, dtype=torch.long, device=inputs_embeds.device)
+ )
+ special_image_mask = special_image_mask.all(-1)
+ else:
+ special_image_mask = input_ids == self.config.image_token_id
+
+ n_image_tokens = special_image_mask.sum()
+ n_image_features = image_features.shape[0] * image_features.shape[1]
+ special_image_mask = special_image_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
+ torch_compilable_check(
+ inputs_embeds[special_image_mask].numel() == image_features.numel(),
+ f"Image features and image tokens do not match, tokens: {n_image_tokens}, features: {n_image_features}",
+ )
+ return special_image_mask
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ pixel_values: torch.FloatTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ use_cache: bool | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | GotOcr2ModelOutputWithPast:
+ if (input_ids is None) ^ (inputs_embeds is not None):
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
+
+ if inputs_embeds is None:
+ inputs_embeds = self.get_input_embeddings()(input_ids)
+
+ if pixel_values is not None:
+ image_features = self.get_image_features(
+ pixel_values=pixel_values.to(inputs_embeds.dtype), return_dict=True
+ ).pooler_output
+ image_features = image_features.to(inputs_embeds.device, inputs_embeds.dtype)
+ special_image_mask = self.get_placeholder_mask(
+ input_ids, inputs_embeds=inputs_embeds, image_features=image_features
+ )
+ inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)
+
+ outputs = self.language_model(
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ return_dict=True,
+ **kwargs,
+ )
+
+ return GotOcr2ModelOutputWithPast(
+ last_hidden_state=outputs.last_hidden_state,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ image_hidden_states=image_features if pixel_values is not None else None,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ The GOT_OCR2 model which consists of a vision backbone and a language model.
+ """
+)
+class GotOcr2ForConditionalGeneration(GotOcr2PreTrainedModel, GenerationMixin):
+ _tied_weights_keys = {"lm_head.weight": "model.language_model.embed_tokens.weight"}
+
+ def __init__(self, config: GotOcr2Config):
+ super().__init__(config)
+ self.model = GotOcr2Model(config)
+ self.lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.vocab_size, bias=False)
+ self.post_init()
+
+ def get_output_embeddings(self) -> nn.Module:
+ return self.lm_head
+
+ @auto_docstring
+ def get_image_features(
+ self, pixel_values: torch.FloatTensor, **kwargs: Unpack[TransformersKwargs]
+ ) -> tuple | BaseModelOutputWithPooling:
+ return self.model.get_image_features(pixel_values=pixel_values, **kwargs)
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ pixel_values: torch.FloatTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ use_cache: bool | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | GotOcr2CausalLMOutputWithPast:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
+
+ Example:
+
+ ```python
+ >>> from PIL import Image
+ >>> import httpx
+ >>> from io import BytesIO
+ >>> from transformers import AutoProcessor, GotOcr2ForConditionalGeneration, TextStreamer
+
+ >>> model = GotOcr2ForConditionalGeneration.from_pretrained("stepfun-ai/GOT-OCR-2.0-hf").to("cuda")
+ >>> processor = AutoProcessor.from_pretrained("stepfun-ai/GOT-OCR-2.0-hf")
+
+ >>> url = "https://huggingface.co/datasets/hf-internal-testing/fixtures_got_ocr/resolve/main/multi_box.png"
+ >>> with httpx.stream("GET", url) as response:
+ ... image = Image.open(BytesIO(response.read()))
+
+ >>> inputs = processor(image, return_tensors="pt", color="green").to("cuda")
+
+ >>> # Generate
+ >>> streamer = TextStreamer(processor.tokenizer, skip_prompt=True, skip_special_tokens=True)
+ >>> generate_ids = model.generate(
+ ... **inputs,
+ ... do_sample=False,
+ ... tokenizer = processor.tokenizer,
+ ... stop_strings='<|im_end|>',
+ ... streamer=streamer,
+ ... max_new_tokens=4096,
+ ... )
+ "You should keep in mind what features from the module should be used, especially
+ when you're planning to sell a template."
+ ```"""
+ outputs = self.model(
+ input_ids=input_ids,
+ pixel_values=pixel_values,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ return_dict=True,
+ logits_to_keep=logits_to_keep,
+ **kwargs,
+ )
+
+ hidden_states = outputs[0]
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(
+ logits=logits, labels=labels, vocab_size=self.config.text_config.vocab_size, **kwargs
+ )
+
+ return GotOcr2CausalLMOutputWithPast(
+ loss=loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ image_hidden_states=outputs.image_hidden_states,
+ )
+
+ def prepare_inputs_for_generation(
+ self,
+ input_ids,
+ past_key_values=None,
+ inputs_embeds=None,
+ pixel_values=None,
+ attention_mask=None,
+ logits_to_keep=None,
+ is_first_iteration=False,
+ **kwargs,
+ ):
+ # Overwritten -- in specific circumstances we don't want to forward image inputs to the model
+
+ model_inputs = super().prepare_inputs_for_generation(
+ input_ids,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ logits_to_keep=logits_to_keep,
+ is_first_iteration=is_first_iteration,
+ **kwargs,
+ )
+
+ if is_first_iteration or not kwargs.get("use_cache", True):
+ # Pixel values are used only in the first iteration if available
+ # In subsequent iterations, they are already merged with text and cached
+ # NOTE: first iteration doesn't have to be prefill, it can be the first
+ # iteration with a question and cached system prompt (continue generate from cache)
+ model_inputs["pixel_values"] = pixel_values
+
+ return model_inputs
+
+
+__all__ = ["GotOcr2PreTrainedModel", "GotOcr2Model", "GotOcr2ForConditionalGeneration"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/got_ocr2/modular_got_ocr2.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/got_ocr2/modular_got_ocr2.py
new file mode 100644
index 0000000000000000000000000000000000000000..64f22f228f1c50ce6c11e6945f4231d7f0e99e8b
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/got_ocr2/modular_got_ocr2.py
@@ -0,0 +1,388 @@
+# Copyright 2024 HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+import torch
+import torch.nn as nn
+from huggingface_hub.dataclasses import strict
+
+from ... import initialization as init
+from ...cache_utils import Cache
+from ...configuration_utils import PreTrainedConfig
+from ...modeling_outputs import BaseModelOutputWithPooling
+from ...modeling_utils import PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, logging
+from ..auto import CONFIG_MAPPING, AutoConfig
+from ..llava.modeling_llava import (
+ LlavaCausalLMOutputWithPast,
+ LlavaForConditionalGeneration,
+ LlavaModel,
+ LlavaModelOutputWithPast,
+ LlavaPreTrainedModel,
+)
+from ..sam.modeling_sam import (
+ SamMLPBlock,
+ SamPreTrainedModel,
+ SamVisionAttention,
+ SamVisionEncoder,
+ SamVisionLayer,
+)
+
+
+logger = logging.get_logger(__name__)
+
+
+@auto_docstring(checkpoint="facebook/sam-vit-huge")
+@strict
+class GotOcr2VisionConfig(PreTrainedConfig):
+ r"""
+ output_channels (`int`, *optional*, defaults to 256):
+ Dimensionality of the output channels in the Patch Encoder.
+ use_abs_pos (`bool`, *optional*, defaults to `True`):
+ Whether to use absolute position embedding.
+ use_rel_pos (`bool`, *optional*, defaults to `True`):
+ Whether to use relative position embedding.
+ window_size (`int`, *optional*, defaults to 14):
+ Window size for relative position.
+ global_attn_indexes (`list[int]`, *optional*, defaults to `[2, 5, 8, 11]`):
+ The indexes of the global attention layers.
+ mlp_dim (`int`, *optional*, defaults to 3072):
+ The dimensionality of the MLP layer in the Transformer encoder.
+ """
+
+ base_config_key = "vision_config"
+ hidden_size: int = 768
+ output_channels: int = 256
+ num_hidden_layers: int = 12
+ num_attention_heads: int = 12
+ num_channels: int = 3
+ image_size: int | list[int] | tuple[int, int] = 1024
+ patch_size: int | list[int] | tuple[int, int] = 16
+ hidden_act: str = "gelu"
+ layer_norm_eps: float = 1e-06
+ attention_dropout: float | int = 0.0
+ initializer_range: float = 1e-10
+ qkv_bias: bool = True
+ use_abs_pos: bool = True
+ use_rel_pos: bool = True
+ window_size: int = 14
+ global_attn_indexes: list[int] | tuple[int, ...] = (2, 5, 8, 11)
+ mlp_dim: int = 3072
+
+
+@auto_docstring(checkpoint="facebook/sam-vit-huge")
+@strict
+class GotOcr2Config(PreTrainedConfig):
+ r"""
+ Example:
+
+ ```python
+ >>> from transformers import GotOcr2ForConditionalGeneration, GotOcr2Config
+
+ >>> # Initializing a GotOcr2 style configuration
+ >>> configuration = GotOcr2Config()
+
+ >>> # Initializing a model from the Qwen2-VL-7B style configuration
+ >>> model = GotOcr2ForConditionalGeneration(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "got_ocr2"
+ attribute_map = {
+ "image_token_id": "image_token_index",
+ }
+ sub_configs = {"text_config": AutoConfig, "vision_config": GotOcr2VisionConfig}
+
+ vision_config: dict | PreTrainedConfig | None = None
+ text_config: dict | PreTrainedConfig | None = None
+ image_token_index: int = 151859
+ image_seq_length: int = 576
+ tie_word_embeddings: bool = True
+
+ def __post_init__(self, **kwargs):
+ if self.vision_config is None:
+ self.vision_config = GotOcr2VisionConfig()
+ elif isinstance(self.vision_config, dict):
+ self.vision_config = GotOcr2VisionConfig(**self.vision_config)
+
+ if isinstance(self.text_config, dict):
+ self.text_config["model_type"] = self.text_config.get("model_type", "qwen2")
+ self.text_config = CONFIG_MAPPING[self.text_config["model_type"]](**self.text_config)
+ elif self.text_config is None:
+ self.text_config = CONFIG_MAPPING["qwen2"](
+ vocab_size=151860,
+ hidden_size=1024,
+ intermediate_size=2816,
+ num_hidden_layers=24,
+ num_attention_heads=16,
+ num_key_value_heads=16,
+ hidden_act="silu",
+ max_position_embeddings=32768,
+ initializer_range=0.02,
+ rms_norm_eps=1e-6,
+ use_cache=True,
+ tie_word_embeddings=self.tie_word_embeddings,
+ rope_theta=1000000.0,
+ rope_parameters=None,
+ use_sliding_window=False,
+ sliding_window=4096,
+ max_window_layers=21,
+ attention_dropout=0.0,
+ )
+
+ super().__post_init__(**kwargs)
+
+
+class GotOcr2MLPBlock(SamMLPBlock):
+ pass
+
+
+class GotOcr2VisionAttention(SamVisionAttention):
+ pass
+
+
+class GotOcr2VisionLayer(SamVisionLayer):
+ def __init__(self, config, window_size):
+ super().__init__(config, window_size)
+ self.layer_norm1 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.attn = GotOcr2VisionAttention(config, window_size)
+ self.layer_norm2 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.mlp = GotOcr2MLPBlock(config)
+ self.window_size = window_size
+
+
+class GotOcr2PreTrainedModel(SamPreTrainedModel):
+ input_modalities = ("image", "text")
+
+
+class GotOcr2VisionEncoder(SamVisionEncoder, GotOcr2PreTrainedModel):
+ input_modalities = ("image",)
+
+
+class GotOcr2MultiModalProjector(nn.Module):
+ def __init__(self, config: GotOcr2Config):
+ super().__init__()
+ vision_output_channels = config.vision_config.output_channels
+ language_hidden_size = config.text_config.hidden_size
+ self.conv_upsampler1 = nn.Conv2d(
+ vision_output_channels, vision_output_channels * 2, kernel_size=3, stride=2, padding=1, bias=False
+ )
+ self.conv_upsampler2 = nn.Conv2d(
+ vision_output_channels * 2, language_hidden_size, kernel_size=3, stride=2, padding=1, bias=False
+ )
+ self.multimodal_projector = nn.Linear(language_hidden_size, language_hidden_size)
+
+ def forward(self, vision_embeddings: torch.Tensor) -> torch.Tensor:
+ hidden_state = self.conv_upsampler1(vision_embeddings)
+ hidden_state = self.conv_upsampler2(hidden_state)
+ hidden_state = hidden_state.flatten(2).permute(0, 2, 1)
+ hidden_state = self.multimodal_projector(hidden_state)
+ return hidden_state
+
+
+class GotOcr2CausalLMOutputWithPast(LlavaCausalLMOutputWithPast):
+ pass
+
+
+class GotOcr2ModelOutputWithPast(LlavaModelOutputWithPast):
+ pass
+
+
+class GotOcr2PreTrainedModel(LlavaPreTrainedModel):
+ _supports_flash_attn = False
+ _supports_sdpa = False
+ _supports_flex_attn = False
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ PreTrainedModel._init_weights(self, module)
+ if isinstance(module, GotOcr2VisionAttention):
+ if module.use_rel_pos:
+ init.zeros_(module.rel_pos_h)
+ init.zeros_(module.rel_pos_w)
+ elif isinstance(module, GotOcr2VisionEncoder):
+ if module.pos_embed is not None:
+ init.zeros_(module.pos_embed)
+
+
+class GotOcr2Model(LlavaModel):
+ def __init__(self, config: GotOcr2Config):
+ super().__init__(config)
+ self.vision_tower = GotOcr2VisionEncoder(config.vision_config)
+
+ @can_return_tuple
+ @auto_docstring(
+ custom_intro="Obtains image last hidden states from the vision tower and apply multimodal projection."
+ )
+ def get_image_features(
+ self,
+ pixel_values: torch.FloatTensor,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutputWithPooling:
+ image_outputs = self.vision_tower(pixel_values, return_dict=True, **kwargs)
+ last_hidden_state = image_outputs.last_hidden_state
+ image_outputs.pooler_output = self.multi_modal_projector(last_hidden_state)
+
+ return image_outputs
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ pixel_values: torch.FloatTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ use_cache: bool | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | GotOcr2ModelOutputWithPast:
+ if (input_ids is None) ^ (inputs_embeds is not None):
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
+
+ if inputs_embeds is None:
+ inputs_embeds = self.get_input_embeddings()(input_ids)
+
+ if pixel_values is not None:
+ image_features = self.get_image_features(
+ pixel_values=pixel_values.to(inputs_embeds.dtype), return_dict=True
+ ).pooler_output
+ image_features = image_features.to(inputs_embeds.device, inputs_embeds.dtype)
+ special_image_mask = self.get_placeholder_mask(
+ input_ids, inputs_embeds=inputs_embeds, image_features=image_features
+ )
+ inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)
+
+ outputs = self.language_model(
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ return_dict=True,
+ **kwargs,
+ )
+
+ return GotOcr2ModelOutputWithPast(
+ last_hidden_state=outputs.last_hidden_state,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ image_hidden_states=image_features if pixel_values is not None else None,
+ )
+
+
+class GotOcr2ForConditionalGeneration(LlavaForConditionalGeneration):
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ pixel_values: torch.FloatTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ use_cache: bool | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | GotOcr2CausalLMOutputWithPast:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
+
+ Example:
+
+ ```python
+ >>> from PIL import Image
+ >>> import httpx
+ >>> from io import BytesIO
+ >>> from transformers import AutoProcessor, GotOcr2ForConditionalGeneration, TextStreamer
+
+ >>> model = GotOcr2ForConditionalGeneration.from_pretrained("stepfun-ai/GOT-OCR-2.0-hf").to("cuda")
+ >>> processor = AutoProcessor.from_pretrained("stepfun-ai/GOT-OCR-2.0-hf")
+
+ >>> url = "https://huggingface.co/datasets/hf-internal-testing/fixtures_got_ocr/resolve/main/multi_box.png"
+ >>> with httpx.stream("GET", url) as response:
+ ... image = Image.open(BytesIO(response.read()))
+
+ >>> inputs = processor(image, return_tensors="pt", color="green").to("cuda")
+
+ >>> # Generate
+ >>> streamer = TextStreamer(processor.tokenizer, skip_prompt=True, skip_special_tokens=True)
+ >>> generate_ids = model.generate(
+ ... **inputs,
+ ... do_sample=False,
+ ... tokenizer = processor.tokenizer,
+ ... stop_strings='<|im_end|>',
+ ... streamer=streamer,
+ ... max_new_tokens=4096,
+ ... )
+ "You should keep in mind what features from the module should be used, especially
+ when you're planning to sell a template."
+ ```"""
+ outputs = self.model(
+ input_ids=input_ids,
+ pixel_values=pixel_values,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ return_dict=True,
+ logits_to_keep=logits_to_keep,
+ **kwargs,
+ )
+
+ hidden_states = outputs[0]
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(
+ logits=logits, labels=labels, vocab_size=self.config.text_config.vocab_size, **kwargs
+ )
+
+ return GotOcr2CausalLMOutputWithPast(
+ loss=loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ image_hidden_states=outputs.image_hidden_states,
+ )
+
+ @auto_docstring
+ def get_image_features(
+ self, pixel_values: torch.FloatTensor, **kwargs: Unpack[TransformersKwargs]
+ ) -> tuple | BaseModelOutputWithPooling:
+ return self.model.get_image_features(pixel_values=pixel_values, **kwargs)
+
+
+__all__ = [
+ "GotOcr2VisionConfig",
+ "GotOcr2Config",
+ "GotOcr2PreTrainedModel",
+ "GotOcr2Model",
+ "GotOcr2ForConditionalGeneration",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/got_ocr2/processing_got_ocr2.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/got_ocr2/processing_got_ocr2.py
new file mode 100644
index 0000000000000000000000000000000000000000..87f7169532f02d7e8672da5086e8215231fe50c6
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/got_ocr2/processing_got_ocr2.py
@@ -0,0 +1,231 @@
+# Copyright 2024 HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+import numpy as np
+
+from ...image_processing_utils import BatchFeature
+from ...image_utils import ImageInput
+from ...processing_utils import ImagesKwargs, ProcessingKwargs, ProcessorMixin, TextKwargs, Unpack
+from ...tokenization_utils_base import PreTokenizedInput, TextInput
+from ...utils import auto_docstring, is_vision_available, logging
+
+
+if is_vision_available():
+ from ...image_utils import load_images
+
+logger = logging.get_logger(__name__)
+
+
+class GotOcr2TextKwargs(TextKwargs, total=False):
+ """
+ format (`bool`, *optional*, defaults to `False`):
+ Whether to request formatted output from the OCR model. When enabled, the model is instructed to return
+ structured and formatted text output rather than raw OCR results.
+ """
+
+ format: bool | None
+
+
+class GotOcr2ImagesKwargs(ImagesKwargs, total=False):
+ """
+ crop_to_patches (`bool`, *optional*, defaults to `False`):
+ Whether to crop images into patches before processing. When enabled, large images are divided into
+ smaller patches for more efficient OCR processing.
+ min_patches (`int`, *optional*, defaults to `1`):
+ Minimum number of patches to generate when cropping images. This ensures that even small images are
+ processed with at least this many patches.
+ max_patches (`int`, *optional*, defaults to `12`):
+ Maximum number of patches to generate when cropping images. Large images will be divided into at most
+ this many patches to control computational complexity.
+ box (`list`, `tuple[float, float]`, or `tuple[float, float, float, float]`, *optional*):
+ Bounding box coordinates for OCR region of interest. Can be specified as a single box `[x1, y1, x2, y2]`
+ or a list of boxes. Coordinates are normalized to the range [0, 1000] based on the image dimensions.
+ If not provided, OCR is performed on the entire image.
+ color (`str`, *optional*):
+ Color filter specification for OCR. When provided, the OCR query is prefixed with the color information
+ to focus on text of a specific color (e.g., "red", "blue").
+ num_image_tokens (`int`, *optional*, defaults to `256`):
+ Number of image tokens (patches) to use per image. This controls the resolution of the image representation
+ passed to the model. Higher values provide more detail but increase computational cost.
+ multi_page (`bool`, *optional*, defaults to `False`):
+ Whether the input consists of multi-page documents. When enabled, images can be provided as nested lists
+ where each inner list represents a page, and OCR is performed across all pages with appropriate handling
+ of page boundaries.
+ """
+
+ crop_to_patches: bool
+ min_patches: int
+ max_patches: int
+ box: list | tuple[float, float] | tuple[float, float, float, float] | None
+ color: str | None
+ num_image_tokens: int
+ multi_page: bool
+
+
+class GotOcr2ProcessorKwargs(ProcessingKwargs, total=False):
+ text_kwargs: GotOcr2TextKwargs
+ images_kwargs: GotOcr2ImagesKwargs
+ _defaults = {
+ "text_kwargs": {
+ "padding": False,
+ "format": False,
+ },
+ "images_kwargs": {
+ "num_image_tokens": 256,
+ "multi_page": False,
+ "crop_to_patches": False,
+ "min_patches": 1,
+ "max_patches": 12,
+ },
+ }
+
+
+def preprocess_box_annotation(box: list | tuple, image_size: tuple[int, int]) -> list:
+ """
+ Convert box annotation to the format [x1, y1, x2, y2] in the range [0, 1000].
+ """
+ width, height = image_size
+ if len(box) == 4:
+ box[0] = int(box[0] / width * 1000)
+ box[1] = int(box[1] / height * 1000)
+ box[2] = int(box[2] / width * 1000)
+ box[3] = int(box[3] / height * 1000)
+ else:
+ raise ValueError("Box must be a list or tuple of lists in the form [x1, y1, x2, y2].")
+
+ return list(box)
+
+
+@auto_docstring
+class GotOcr2Processor(ProcessorMixin):
+ def __init__(self, image_processor=None, tokenizer=None, chat_template=None, **kwargs):
+ super().__init__(image_processor, tokenizer, chat_template=chat_template)
+
+ self.message_start_token = "<|im_start|>"
+ self.message_end_token = "<|im_end|>"
+ self.img_start_token = "
"
+ self.img_end_token = ""
+ self.img_pad_token = ""
+ self.image_token = "" # keep the above for BC, but we need to call it `image_token`
+ self.image_token_id = tokenizer.convert_tokens_to_ids(self.image_token)
+ self.system_query = "system\nYou should follow the instructions carefully and explain your answers in detail."
+
+ def _make_list_of_inputs(self, images, text, box, color, multi_page):
+ if not isinstance(images, (list, tuple)):
+ images = [images]
+ if multi_page:
+ logger.warning("Multi-page inference is enabled but only one image is passed.")
+ images = [images]
+ elif isinstance(images[0], (list, tuple)) and not multi_page:
+ raise ValueError("Nested images are only supported with `multi_page` set to `True`.")
+ elif not isinstance(images[0], (list, tuple)) and multi_page:
+ images = [images]
+
+ if isinstance(text, str):
+ text = [text]
+
+ if not isinstance(box[0], (list, tuple)):
+ # Use the same box for all images
+ box = [box for _ in range(len(images))]
+ if not isinstance(color, (list, tuple)):
+ color = [color for _ in range(len(images))]
+
+ return images, text, box, color
+
+ @auto_docstring
+ def __call__(
+ self,
+ images: ImageInput | None = None,
+ text: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] | None = None,
+ **kwargs: Unpack[GotOcr2ProcessorKwargs],
+ ) -> BatchFeature:
+ r"""
+ Returns:
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
+
+ - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
+ `None`).
+ - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
+ """
+
+ output_kwargs = self._merge_kwargs(
+ GotOcr2ProcessorKwargs,
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
+ **kwargs,
+ )
+ format_output = output_kwargs["text_kwargs"].pop("format")
+ num_image_tokens = output_kwargs["images_kwargs"].pop("num_image_tokens")
+ box = output_kwargs["images_kwargs"].pop("box", [None])
+ color = output_kwargs["images_kwargs"].pop("color", None)
+ multi_page = output_kwargs["images_kwargs"].pop("multi_page")
+
+ crop_to_patches = output_kwargs["images_kwargs"].get("crop_to_patches")
+ images, text, box, color = self._make_list_of_inputs(images, text, box, color, multi_page)
+ if multi_page:
+ # save the number of pages per batch
+ num_pages_per_batch = [len(image_group) for image_group in images]
+ # flatten the list of images
+ images = [image for image_group in images for image in image_group]
+ else:
+ num_pages_per_batch = [1 for _ in range(len(images))]
+ # Load images as we need to know the image size
+ images = load_images(images)
+ image_sizes = [image.size for image in images]
+ image_inputs = self.image_processor(images=images, **output_kwargs["images_kwargs"])
+ num_patches_array = image_inputs.pop("num_patches")
+ if text is None:
+ text = []
+ patch_indices = np.cumsum(num_pages_per_batch)
+ for index, (num_pages, box_single, color_single) in enumerate(zip(num_pages_per_batch, box, color)):
+ current_patch_index = patch_indices[index - 1] if index > 0 else 0
+ num_patches = sum(num_patches_array[current_patch_index : current_patch_index + num_pages])
+ if box_single[0] is not None:
+ box_single = preprocess_box_annotation(box_single, image_sizes[index])
+ query = (
+ f"{f'[{color_single}] ' if color_single is not None else ''}"
+ f"{str(box_single) if box_single[0] is not None else ''} "
+ "OCR"
+ f"{' with format' if format_output else ''}"
+ f"{' across multi pages' if multi_page else ''}"
+ f"{' upon the patch reference' if crop_to_patches else ''}"
+ ": "
+ )
+ prompt = (
+ self.message_start_token
+ + self.system_query
+ + self.message_end_token
+ + self.message_start_token
+ + "user\n"
+ + self.img_start_token
+ + self.img_pad_token * num_image_tokens * num_patches
+ + self.img_end_token
+ + "\n"
+ + query
+ + self.message_end_token
+ + self.message_start_token
+ + "assistant\n"
+ )
+ text.append(prompt)
+
+ return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None)
+ text_inputs = self.tokenizer(text, **output_kwargs["text_kwargs"])
+ self._check_special_mm_tokens(text, text_inputs, modalities=["image"])
+
+ return BatchFeature(data={**text_inputs, **image_inputs}, tensor_type=return_tensors)
+
+
+__all__ = ["GotOcr2Processor"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gpt_sw3/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gpt_sw3/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e477eb1d2cc2ff0e34d214ed99ad3f80afe8ab0a
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gpt_sw3/__init__.py
@@ -0,0 +1,26 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .tokenization_gpt_sw3 import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gpt_sw3/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gpt_sw3/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d0d05b8016f51ac31cebc0d19b5484fddae9ffc8
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gpt_sw3/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gpt_sw3/__pycache__/tokenization_gpt_sw3.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gpt_sw3/__pycache__/tokenization_gpt_sw3.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2270716bbea6052b349a20a9c788c36d75813394
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gpt_sw3/__pycache__/tokenization_gpt_sw3.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gpt_sw3/tokenization_gpt_sw3.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gpt_sw3/tokenization_gpt_sw3.py
new file mode 100644
index 0000000000000000000000000000000000000000..95f6c2c255046baa2a110c4c8b73f2498753ce76
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gpt_sw3/tokenization_gpt_sw3.py
@@ -0,0 +1,239 @@
+"""The tokenizer used by the GPT-SW3 models."""
+
+import re
+import unicodedata
+from typing import Any, Union
+
+from ...tokenization_utils_sentencepiece import SentencePieceBackend
+from ...utils import is_torch_available, logging
+from ...utils.import_utils import requires
+
+
+if is_torch_available():
+ import torch
+
+
+logger = logging.get_logger(__name__)
+VOCAB_FILES_NAMES = {"vocab_file": "spiece.model"}
+
+
+@requires(backends=("sentencepiece",))
+class GPTSw3Tokenizer(SentencePieceBackend):
+ """
+ Construct an GPTSw3 tokenizer. Based on [SentencePiece](https://github.com/google/sentencepiece).
+
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
+ this superclass for more information regarding those methods.
+
+ Example usage:
+ ```python
+ >>> from transformers import GPTSw3Tokenizer
+
+ >>> tokenizer = GPTSw3Tokenizer.from_pretrained("AI-Sweden-Models/gpt-sw3-126m")
+ >>> tokenizer("Svenska är kul!")["input_ids"]
+ [1814, 377, 3617, 63504]
+ ```
+
+ Args:
+ vocab_file (`str`):
+ [SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
+ contains the vocabulary necessary to instantiate a tokenizer.
+ do_lower_case (`bool`, *optional*, defaults to `False`):
+ Whether or not to lowercase the input when tokenizing.
+ remove_space (`bool`, *optional*, defaults to `False`):
+ Whether or not to strip the text when tokenizing (removing excess spaces before and after the string).
+ keep_accents (`bool`, *optional*, defaults to `False`):
+ Whether or not to keep accents when tokenizing.
+ pad_token (`str`, *optional*):
+ The token used for padding, for example when batching sequences of different lengths. If not provided, will
+ default to '' or '' depending on model size.
+ unk_token (`str`, *optional*):
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
+ token instead. If not provided, will default to ''.
+ eos_token (`str`, *optional*):
+ The end of sequence token seen during pretraining. If not provided, will default to '<|endoftext|>'
+ bos_token (`str`, *optional*):
+ The beginning of sequence token that can be used for downstream task, was not seen during pretraining. If
+ not provided, will default to '' or '<|endoftext|>', depending on model size.
+ sp_model_kwargs (`dict`, *optional*):
+ Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
+ SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
+ to set:
+
+ - `enable_sampling`: Enable subword regularization.
+ - `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
+
+ - `nbest_size = {0,1}`: No sampling is performed.
+ - `nbest_size > 1`: samples from the nbest_size results.
+ - `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
+ using forward-filtering-and-backward-sampling algorithm.
+
+ - `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
+ BPE-dropout.
+
+ Attributes:
+ sp_model (`SentencePieceProcessor`):
+ The *SentencePiece* processor that is used for every conversion (string, tokens and IDs).
+ whitespaces (`set`):
+ The whitespaces that are replaced in the whitespace normalization in preprocessing.
+ non_printing_characters_re (`Pattern`):
+ The compiled regular expression to remove non-printing characters in preprocessing.
+ """
+
+ vocab_files_names = VOCAB_FILES_NAMES
+ model_input_names = ["input_ids", "attention_mask"]
+ is_fast = False
+
+ def __init__(
+ self,
+ vocab_file,
+ do_lower_case=False,
+ remove_space=False,
+ keep_accents=False,
+ pad_token=None,
+ unk_token=None,
+ eos_token=None,
+ bos_token=None,
+ sp_model_kwargs: dict[str, Any] | None = None,
+ **kwargs,
+ ) -> None:
+ name_or_path = kwargs.get("name_or_path")
+ if name_or_path is None:
+ logger.warning(
+ "name_or_path not provided, will work for all GPTSw3 models except gpt-sw3-7b,"
+ " you are testing the model, this can safely be ignored"
+ )
+ name_or_path = "None"
+
+ # Default definitions for our 2 tokenizer versions, with None-checks to enable proper testing
+ eos_token = "<|endoftext|>" if eos_token is None else eos_token
+ unk_token = "" if unk_token is None else unk_token
+ if "gpt-sw3-7b" in name_or_path:
+ pad_token = unk_token if pad_token is None else pad_token
+ bos_token = eos_token if bos_token is None else bos_token
+ else:
+ pad_token = "" if pad_token is None else pad_token
+ bos_token = "" if bos_token is None else bos_token
+
+ self.do_lower_case = do_lower_case
+ self.remove_space = remove_space
+ self.keep_accents = keep_accents
+
+ # Used for whitespace normalization in input texts
+ # fmt : off
+ self.whitespaces = {" ", " ", " ", " ", " ", " ", " ", " ", " ", " ", "", ""}
+ # fmt : on
+
+ # Regular expression to remove non-printing characters (e.g. some unicode control chars) in preprocessing
+ self.non_printing_characters_re = re.compile(
+ f"[{''.join(map(chr, list(range(0, 9)) + list(range(11, 32)) + list(range(127, 160)) + [160, 173, 8203]))}]"
+ )
+
+ # Ensure sp_model_kwargs is in kwargs for proper signature storage
+ # Always add it even if None, parent class will handle the conversion to {}
+ kwargs["sp_model_kwargs"] = sp_model_kwargs if sp_model_kwargs is not None else {}
+
+ # Call parent init (which will load sp_model)
+ super().__init__(
+ vocab_file=vocab_file,
+ do_lower_case=do_lower_case,
+ remove_space=remove_space,
+ keep_accents=keep_accents,
+ bos_token=bos_token,
+ eos_token=eos_token,
+ unk_token=unk_token,
+ pad_token=pad_token,
+ special_tokens_pattern="none",
+ **kwargs,
+ )
+
+ def preprocess_text(self, text: str) -> str:
+ """
+ Returns the preprocessed text. This procedure is identical to what was used when training the tokenizer.
+ """
+
+ # Remove non-printing characters
+ text = self.non_printing_characters_re.sub("", text)
+
+ # Normalize whitespaces
+ text = "".join([char if char not in self.whitespaces else " " for char in text])
+
+ # NFC Unicode normalization
+ text = unicodedata.normalize("NFC", text)
+ return text
+
+ def _tokenize(self, text: str, **kwargs) -> list[str]:
+ text = self.preprocess_text(text)
+ return self.sp_model.encode(text, out_type=str)
+
+ def convert_tokens_to_string(self, tokens: list[str]) -> str:
+ """Converts a sequence of tokens (strings) to a single string. Special tokens remain intact."""
+ current_sub_tokens = []
+ out_string = ""
+ prev_is_special = False
+ for token in tokens:
+ # make sure that special tokens are not decoded using sentencepiece model
+ if token in self.all_special_tokens:
+ # TODO: Check if this is needed, as it ensures that decode(encode(doc)) != doc by adding extra whitespace in the decoded document
+ if not prev_is_special:
+ out_string += " "
+
+ out_string += self.sp_model.decode(current_sub_tokens) + token
+ prev_is_special = True
+ current_sub_tokens = []
+ else:
+ current_sub_tokens.append(token)
+ prev_is_special = False
+ out_string += self.sp_model.decode(current_sub_tokens)
+
+ return out_string
+
+ def encode_fast(
+ self, text: str | list[str], return_tensors: str | bool = False
+ ) -> Union[list[int], list[list[int]], "torch.Tensor"]:
+ """
+ Encodes a text or batch of texts to token ids using preprocessing and the raw SP tokenizer. This has reduced
+ functionality but is often much faster.
+
+ Does NOT handle special tokens correctly, these can manually be added as ids afterwards.
+
+ Does NOT support padding, these can manually be added as ids afterwards.
+
+ Use default HuggingFace tokenization methods for full functionality.
+
+ Args:
+ text (`str` or `list[str]`): One or several text(s) to convert to token ids.
+ return_tensors (`str` or `bool`): Returns PyTorch tensors if set to True or "pt"
+
+ Returns:
+ `list[int]`, `list[list[int]]`, or `torch.Tensor`: The encoded text(s) as token ids.
+ """
+
+ if isinstance(text, str):
+ text = self.preprocess_text(text)
+ token_ids = self.sp_model.encode(text)
+ else:
+ text = [self.preprocess_text(t) for t in text]
+ token_ids = self.sp_model.encode(text)
+
+ if return_tensors is True or return_tensors == "pt":
+ token_ids = torch.tensor(token_ids)
+
+ return token_ids
+
+ def decode_fast(self, token_ids: int | list[int]) -> str:
+ """
+ Encodes a text or batch of texts to token ids using preprocessing and the raw SP tokenizer. This has reduced
+ functionality but is often much faster.
+
+ Args:
+ token_ids (`int` or `list[int]`): Encoded token or text as token id(s).
+
+ Returns:
+ `str`: Decoded text
+ """
+
+ return self.sp_model.decode(token_ids)
+
+
+__all__ = ["GPTSw3Tokenizer"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gptj/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gptj/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1782a5e25e0391cc56e3788fddffea61e6e9554b
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gptj/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gptj/__pycache__/configuration_gptj.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gptj/__pycache__/configuration_gptj.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dfc2ce3758540effd9e5eab34e23d333ab22b1e3
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gptj/__pycache__/configuration_gptj.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gptj/__pycache__/modeling_gptj.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gptj/__pycache__/modeling_gptj.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8353bf2ae84486017d84413c23f9ffe8007ebfd1
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/gptj/__pycache__/modeling_gptj.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/granitemoehybrid/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/granitemoehybrid/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..309c2c1a42bef15269c6aa719abcf6e89be65212
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/granitemoehybrid/__init__.py
@@ -0,0 +1,28 @@
+# Copyright 2025 IBM and the HuggingFace Inc. team. All rights reserved.
+#
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_granitemoehybrid import *
+ from .modeling_granitemoehybrid import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/granitemoehybrid/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/granitemoehybrid/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..82c8b6a267526689c2ef605b1c705f7603a9235d
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/granitemoehybrid/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/granitemoehybrid/__pycache__/configuration_granitemoehybrid.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/granitemoehybrid/__pycache__/configuration_granitemoehybrid.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..facb2faf6c41a64f0ada062327742a0bb63c162a
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/granitemoehybrid/__pycache__/configuration_granitemoehybrid.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/granitemoehybrid/__pycache__/modeling_granitemoehybrid.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/granitemoehybrid/__pycache__/modeling_granitemoehybrid.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..494b901cc7661d3f60cfb78d330c825dc2101c66
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/granitemoehybrid/__pycache__/modeling_granitemoehybrid.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/granitemoehybrid/__pycache__/modular_granitemoehybrid.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/granitemoehybrid/__pycache__/modular_granitemoehybrid.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fb5c7ebcdad238fb8b2a3b568deb5a01c479c69a
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/granitemoehybrid/__pycache__/modular_granitemoehybrid.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/granitemoehybrid/configuration_granitemoehybrid.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/granitemoehybrid/configuration_granitemoehybrid.py
new file mode 100644
index 0000000000000000000000000000000000000000..843630333f59aa9fe1844e5d3bb20871e26c3aeb
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/granitemoehybrid/configuration_granitemoehybrid.py
@@ -0,0 +1,124 @@
+# Copyright 2025 IBM and the HuggingFace Inc. team. All rights reserved.
+#
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""GraniteMoeHybrid model configuration"""
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...modeling_rope_utils import RopeParameters
+from ...utils import auto_docstring
+
+
+@auto_docstring(checkpoint="ibm-granite/granite-speech-3.2-8b")
+@strict
+class GraniteMoeHybridConfig(PreTrainedConfig):
+ r"""
+ embedding_multiplier (`float`, *optional*, defaults to 1.0):
+ embedding multiplier.
+ logits_scaling (`float`, *optional*, defaults to 1.0):
+ divisor for output logits.
+ residual_multiplier (`float`, *optional*, defaults to 1.0):
+ residual multiplier.
+ attention_multiplier (`float`, *optional*, defaults to 1.0):
+ attention multiplier.
+ shared_intermediate_size (`int`, *optional*, defaults to 1024):
+ intermediate size for shared experts.
+ position_embedding_type (`str`, *optional*):
+ Positional embedding type to be used; defaults to None. Allowed options: `[None, "rope"]`
+
+ Example:
+
+ ```python
+ >>> from transformers import GraniteMoeHybridModel, GraniteMoeHybridConfig
+
+ >>> # Initializing a GraniteMoeHybrid config
+ >>> configuration = GraniteMoeHybridConfig()
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "granitemoehybrid"
+ attribute_map = {"layers_block_type": "layer_types"}
+ keys_to_ignore_at_inference = ["past_key_values"]
+
+ vocab_size: int = 32000
+ hidden_size: int = 4096
+ intermediate_size: int = 11008
+ num_hidden_layers: int = 32
+ num_attention_heads: int = 32
+ num_key_value_heads: int | None = None
+ hidden_act: str = "silu"
+ max_position_embeddings: int = 2048
+ initializer_range: float = 0.02
+ rms_norm_eps: float = 1e-6
+ use_cache: bool = True
+ pad_token_id: int | None = None
+ bos_token_id: int | None = 1
+ eos_token_id: int | list[int] | None = 2
+ tie_word_embeddings: bool = False
+ rope_parameters: RopeParameters | dict | None = None
+ attention_bias: bool = False
+ attention_dropout: float | int | None = 0.0
+ embedding_multiplier: int | float | None = 1.0
+ logits_scaling: int | float | None = 1.0
+ residual_multiplier: int | float | None = 1.0
+ attention_multiplier: int | float | None = 1.0
+ num_local_experts: int | None = 8
+ num_experts_per_tok: int | None = 2
+ output_router_logits: bool | None = False
+ router_aux_loss_coef: float | None = 0.001
+ shared_intermediate_size: int = 1024
+ position_embedding_type: str | None = None
+ layer_types: list[str] | None = None
+ mamba_n_heads: int | None = 128
+ mamba_n_groups: int | None = 1
+ mamba_d_state: int | None = 256
+ mamba_d_head: int | str | None = "auto"
+ mamba_d_conv: int | None = 4
+ mamba_expand: int | None = 2
+ mamba_chunk_size: int | None = 256
+ mamba_conv_bias: bool | None = True
+ mamba_proj_bias: bool | None = False
+ time_step_min: float | None = 0.001
+ time_step_max: float | None = 0.1
+ time_step_limit: list[float, float] | tuple[float, float] | None = (0.0, float("inf"))
+
+ def __post_init__(self, **kwargs):
+ if self.num_key_value_heads is None:
+ self.num_key_value_heads = self.num_attention_heads
+
+ mamba_intermediate = self.mamba_expand * self.hidden_size
+ if self.mamba_d_head == "auto":
+ self.mamba_d_head = mamba_intermediate // self.mamba_n_heads
+
+ self.time_step_limit = tuple(self.time_step_limit) if self.time_step_limit is not None else None
+ if self.layer_types is None:
+ self.layer_types = ["mamba"] * self.num_hidden_layers
+
+ super().__post_init__(**kwargs)
+
+ def validate_architecture(self):
+ """Part of `@strict`-powered validation. Validates the architecture of the config."""
+
+ mamba_intermediate = self.mamba_expand * self.hidden_size
+ if mamba_intermediate % self.mamba_n_heads != 0:
+ raise ValueError("mamba_n_heads must divide mamba_expand * hidden_size")
+
+ if self.mamba_d_head * self.mamba_n_heads != mamba_intermediate:
+ raise ValueError("The dimensions for the Mamba head state do not match the model intermediate_size")
+
+
+__all__ = ["GraniteMoeHybridConfig"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/granitemoehybrid/modeling_granitemoehybrid.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/granitemoehybrid/modeling_granitemoehybrid.py
new file mode 100644
index 0000000000000000000000000000000000000000..2e0926f3e5d4e6102c1e70199178140767806580
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/granitemoehybrid/modeling_granitemoehybrid.py
@@ -0,0 +1,1412 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/granitemoehybrid/modular_granitemoehybrid.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_granitemoehybrid.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2025 IBM and the HuggingFace Inc. team. All rights reserved.
+#
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from collections.abc import Callable
+from typing import Optional, TypedDict
+
+import torch
+from torch import nn
+from torch.nn import functional as F
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...cache_utils import Cache, DynamicCache
+from ...generation import GenerationMixin
+from ...integrations import use_kernel_forward_from_hub, use_kernel_func_from_hub, use_kernelized_func
+from ...integrations.hub_kernels import lazy_load_kernel
+from ...masking_utils import create_causal_mask
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import BaseModelOutputWithPast, MoeCausalLMOutputWithPast, MoeModelOutputWithPast
+from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, is_torchdynamo_compiling, logging
+from ...utils.generic import maybe_autocast, merge_with_config_defaults
+from ...utils.import_utils import resolve_internal_import
+from ...utils.output_capturing import capture_outputs
+from .configuration_granitemoehybrid import GraniteMoeHybridConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+def rotate_half(x):
+ """Rotates half the hidden dims of the input."""
+ x1 = x[..., : x.shape[-1] // 2]
+ x2 = x[..., x.shape[-1] // 2 :]
+ return torch.cat((-x2, x1), dim=-1)
+
+
+@use_kernel_func_from_hub("rotary_pos_emb")
+def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
+ """Applies Rotary Position Embedding to the query and key tensors.
+
+ Args:
+ q (`torch.Tensor`): The query tensor.
+ k (`torch.Tensor`): The key tensor.
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
+ Returns:
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
+ """
+ cos = cos.unsqueeze(unsqueeze_dim)
+ sin = sin.unsqueeze(unsqueeze_dim)
+ q_embed = (q * cos) + (rotate_half(q) * sin)
+ k_embed = (k * cos) + (rotate_half(k) * sin)
+ return q_embed, k_embed
+
+
+def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
+ """
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
+ """
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
+ if n_rep == 1:
+ return hidden_states
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
+
+
+def eager_attention_forward(
+ module: nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: torch.Tensor | None,
+ scaling: float,
+ dropout: float = 0.0,
+ **kwargs: Unpack[TransformersKwargs],
+):
+ key_states = repeat_kv(key, module.num_key_value_groups)
+ value_states = repeat_kv(value, module.num_key_value_groups)
+
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
+ if attention_mask is not None:
+ attn_weights = attn_weights + attention_mask
+
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
+ attn_output = torch.matmul(attn_weights, value_states)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+
+ return attn_output, attn_weights
+
+
+@use_kernelized_func(apply_rotary_pos_emb)
+class GraniteMoeHybridAttention(nn.Module):
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
+
+ def __init__(self, config: GraniteMoeHybridConfig, layer_idx: int):
+ super().__init__()
+ self.config = config
+ self.layer_idx = layer_idx
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
+ self.scaling = config.attention_multiplier # Only diff with llama
+ self.attention_dropout = config.attention_dropout
+ self.is_causal = True
+
+ self.q_proj = nn.Linear(
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
+ )
+ self.k_proj = nn.Linear(
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
+ )
+ self.v_proj = nn.Linear(
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
+ )
+ self.o_proj = nn.Linear(
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
+ )
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor | None,
+ past_key_values: Cache | None = None,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None, # None or rope embeddings
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor, torch.Tensor]:
+ input_shape = hidden_states.shape[:-1]
+ hidden_shape = (*input_shape, -1, self.head_dim)
+
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+
+ if position_embeddings is not None:
+ cos, sin = position_embeddings
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
+
+ if past_key_values is not None:
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_states,
+ key_states,
+ value_states,
+ attention_mask,
+ dropout=0.0 if not self.training else self.attention_dropout,
+ scaling=self.scaling,
+ **kwargs,
+ )
+
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ attn_output = self.o_proj(attn_output)
+ return attn_output, attn_weights
+
+
+# Helper methods for segment sum computation
+
+
+def pad_tensor_by_size(input_tensor: torch.Tensor, pad_size: int):
+ """
+ Padding x tensor with `pad_size` on the seq_len dim (dim=1)
+
+ Assumes that we only have tensors of either size 4 or 3
+ """
+ pad_shape = (0, 0, 0, 0, 0, pad_size, 0, 0) if len(input_tensor.shape) == 4 else (0, 0, 0, pad_size, 0, 0)
+
+ return torch.nn.functional.pad(input_tensor, pad_shape, mode="constant", value=0)
+
+
+def reshape_into_chunks(input_tensor, pad_size, chunk_size):
+ """
+ Padding input_tensor with `pad_size` on the seq_len dim (dim=1) and
+ simultaneously splitting it into chunk sequences.
+
+ Assumes that we only have tensors of either size 4 or 3
+ """
+ # [bsz, seq_len, ...] -> [bsz, seq_len multiple of chunk_size, ...]
+ input_tensor = pad_tensor_by_size(input_tensor, pad_size)
+
+ if len(input_tensor.shape) == 3:
+ # [bsz, seq_len multiple of chunk_size, num_heads] -> [bsz, -1, chunk_size, num_heads]
+ return input_tensor.reshape(input_tensor.shape[0], -1, chunk_size, input_tensor.shape[2])
+ else:
+ # [bsz, seq_len multiple of chunk_size, num_heads, head_dim or state_size] -> [bsz, -1, chunk_size, num_heads, head_dim or state_size]
+ return input_tensor.reshape(
+ input_tensor.shape[0], -1, chunk_size, input_tensor.shape[2], input_tensor.shape[3]
+ )
+
+
+def segment_sum(input_tensor):
+ """
+ More stable segment sum calculation. Uses cumulative sums and masking instead of direct subtractions.
+ """
+ chunk_size = input_tensor.size(-1)
+ # 1. expand input tensor to have an additional dimension and repeat along that dimension
+ # [..., chunk_size] -> [..., chunk_size, chunk_size]
+ input_tensor = input_tensor[..., None].expand(*input_tensor.size(), chunk_size)
+ # 2. create a lower triangular mask with the diagonal set to 0 to 0 out elements above diag
+ mask = torch.tril(torch.ones(chunk_size, chunk_size, device=input_tensor.device, dtype=torch.bool), diagonal=-1)
+ input_tensor = input_tensor.masked_fill(~mask, 0)
+ # 3. compute actual cumsum
+ tensor_segsum = torch.cumsum(input_tensor, dim=-2)
+
+ # 4. apply mask to keep only the lower triangular part of the cumulative sum result (incl diagonal this time)
+ mask = torch.tril(torch.ones(chunk_size, chunk_size, device=input_tensor.device, dtype=torch.bool), diagonal=0)
+ tensor_segsum = tensor_segsum.masked_fill(~mask, -torch.inf)
+ return tensor_segsum
+
+
+def apply_mask_to_padding_states(hidden_states, attention_mask):
+ """
+ Tunes out the hidden states for padding tokens, see https://github.com/state-spaces/mamba/issues/66
+ """
+ # NOTE: attention mask is a 2D boolean tensor
+ if attention_mask is not None and attention_mask.shape[1] > 1 and attention_mask.shape[0] > 1:
+ dtype = hidden_states.dtype
+ hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype)
+
+ return hidden_states
+
+
+# Adapted from transformers.models.mamba2.modeling_mamba2.Mamba2Mixer
+class GraniteMoeHybridMambaLayer(nn.Module):
+ """
+ Compute ∆, A, B, C, and D the state space parameters and compute the `contextualized_states`.
+ A, D are input independent (see Mamba paper [1] Section 3.5.2 "Interpretation of A" for why A isn't selective)
+ ∆, B, C are input-dependent (this is a key difference between Mamba and the linear time invariant S4,
+ and is why Mamba is called **selective** state spaces)
+
+ The are a few differences between this and Mamba2Mixer:
+ - The variable use_precomputed_states is slightly different due to the hybrid cache structure
+ - There's a few non-obvious bugs fixed with batching in the slow path that exist in main
+ - Some extra variables that our layer doesn't need have been removed
+ - We ported most of the refactors in https://github.com/huggingface/transformers/pull/35154, which is (as of Dec 18, 2024) unmerged
+ """
+
+ def __init__(self, config: GraniteMoeHybridConfig, layer_idx: int):
+ super().__init__()
+ self.num_heads = config.mamba_n_heads
+ self.hidden_size = config.hidden_size
+ self.ssm_state_size = config.mamba_d_state
+ self.conv_kernel_size = config.mamba_d_conv
+ self.intermediate_size = int(config.mamba_expand * self.hidden_size)
+ self.layer_idx = layer_idx
+ self.use_conv_bias = config.mamba_conv_bias
+ self.activation = config.hidden_act
+ self.act = ACT2FN[config.hidden_act]
+ self.use_bias = config.mamba_proj_bias
+
+ self.layer_norm_epsilon = config.rms_norm_eps
+
+ self.n_groups = config.mamba_n_groups
+ self.head_dim = config.mamba_d_head
+ self.chunk_size = config.mamba_chunk_size
+
+ self.time_step_limit = config.time_step_limit
+ self.time_step_min = config.time_step_min
+ self.time_step_max = config.time_step_max
+
+ self.conv_dim = self.intermediate_size + 2 * self.n_groups * self.ssm_state_size
+ self.conv1d = nn.Conv1d(
+ in_channels=self.conv_dim,
+ out_channels=self.conv_dim,
+ bias=config.mamba_conv_bias,
+ kernel_size=self.conv_kernel_size,
+ groups=self.conv_dim,
+ padding=self.conv_kernel_size - 1,
+ )
+
+ # projection of the input hidden states
+ projection_size = self.intermediate_size + self.conv_dim + self.num_heads
+ self.in_proj = nn.Linear(
+ self.hidden_size,
+ projection_size,
+ bias=self.use_bias,
+ )
+ # selective projection used to make dt, B and C input dependent
+
+ # time step projection (discretization)
+ # instantiate once and copy inv_dt in init_weights of PretrainedModel
+ self.dt_bias = nn.Parameter(torch.ones(self.num_heads))
+
+ # S4D real initialization. These are not discretized!
+ # The core is to load them, compute the discrete states, then write the updated state. Keeps the memory bounded
+ A = torch.arange(1, self.num_heads + 1)
+ self.A_log = nn.Parameter(torch.log(A))
+ self.norm = GraniteMoeHybridRMSNormGated(self.intermediate_size, eps=self.layer_norm_epsilon)
+ self.D = nn.Parameter(torch.ones(self.num_heads))
+
+ self.out_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=self.use_bias)
+
+ global causal_conv1d_update, causal_conv1d_fn
+ causal_conv1d = lazy_load_kernel("causal-conv1d")
+ causal_conv1d_update = getattr(causal_conv1d, "causal_conv1d_update", None)
+ causal_conv1d_fn = getattr(causal_conv1d, "causal_conv1d_fn", None)
+
+ global selective_state_update, mamba_chunk_scan_combined, mamba_split_conv1d_scan_combined
+ mamba_ssm = lazy_load_kernel("mamba-ssm")
+ selective_state_update = resolve_internal_import(
+ mamba_ssm, chained_path="ops.triton.selective_state_update.selective_state_update"
+ )
+ mamba_chunk_scan_combined = resolve_internal_import(
+ mamba_ssm, chained_path="ops.triton.ssd_combined.mamba_chunk_scan_combined"
+ )
+ mamba_split_conv1d_scan_combined = resolve_internal_import(
+ mamba_ssm, chained_path="ops.triton.ssd_combined.mamba_split_conv1d_scan_combined"
+ )
+
+ global is_fast_path_available
+ is_fast_path_available = all(
+ (
+ selective_state_update,
+ mamba_chunk_scan_combined,
+ mamba_split_conv1d_scan_combined,
+ causal_conv1d_fn,
+ causal_conv1d_update,
+ )
+ )
+
+ if not is_fast_path_available:
+ logger.warning_once(
+ "The fast path is not available because one of `(selective_state_update, causal_conv1d_fn, causal_conv1d_update)`"
+ " is None. Falling back to the naive implementation. To install follow https://github.com/state-spaces/mamba/#installation and"
+ " https://github.com/Dao-AILab/causal-conv1d"
+ )
+ else:
+ logger.warning_once("The fast path for GraniteMoeHybrid will be used when running the model on a GPU")
+
+ def cuda_kernels_forward(
+ self,
+ hidden_states: torch.Tensor,
+ cache_params: Cache | None = None,
+ attention_mask: torch.Tensor | None = None,
+ seq_idx: torch.IntTensor | None = None,
+ ):
+ # 1. Gated MLP's linear projection
+ hidden_states = apply_mask_to_padding_states(hidden_states, attention_mask)
+ projected_states = self.in_proj(hidden_states)
+
+ # Set up dimensions for reshapes later
+ batch_size, seq_len, _ = hidden_states.shape
+ groups_time_state_size = self.n_groups * self.ssm_state_size
+
+ use_precomputed_states = (
+ cache_params is not None and cache_params.has_previous_state(self.layer_idx) and seq_len == 1
+ )
+
+ # getting projected states from cache if it exists
+ if use_precomputed_states:
+ gate, hidden_states_B_C, dt = projected_states.squeeze(1).split(
+ [self.intermediate_size, self.conv_dim, self.num_heads], dim=-1
+ )
+
+ # 2. Convolution sequence transformation
+ hidden_states_B_C = causal_conv1d_update(
+ hidden_states_B_C,
+ cache_params.layers[self.layer_idx].conv_states,
+ self.conv1d.weight.squeeze(1),
+ self.conv1d.bias,
+ self.activation,
+ )
+
+ hidden_states, B, C = torch.split(
+ hidden_states_B_C,
+ [self.intermediate_size, groups_time_state_size, groups_time_state_size],
+ dim=-1,
+ )
+
+ # 3. SSM transformation
+ A = -torch.exp(self.A_log.float()) # (nheads,)
+ A = A[:, None, ...][:, :, None].expand(-1, self.head_dim, self.ssm_state_size).to(dtype=torch.float32)
+ dt = dt[:, :, None].expand(-1, -1, self.head_dim)
+ dt_bias = self.dt_bias[:, None, ...].expand(-1, self.head_dim)
+ D = self.D[:, None, ...].expand(-1, self.head_dim)
+ B = B.view(batch_size, self.n_groups, B.shape[1] // self.n_groups)
+ C = C.view(batch_size, self.n_groups, C.shape[1] // self.n_groups)
+ hidden_states_reshaped = hidden_states.view(batch_size, self.num_heads, self.head_dim)
+ hidden_states = selective_state_update(
+ cache_params.layers[self.layer_idx].recurrent_states,
+ hidden_states_reshaped,
+ dt,
+ A,
+ B,
+ C,
+ D,
+ z=None,
+ dt_bias=dt_bias,
+ dt_softplus=True,
+ )
+ hidden_states = hidden_states.view(batch_size, self.num_heads * self.head_dim)
+ hidden_states = self.norm(hidden_states, gate)
+
+ # 4. Final linear projection
+ out = self.out_proj(hidden_states)[:, None, ...]
+ # Fused calculations or step by step if no initialized cache is found
+ else:
+ A = -torch.exp(self.A_log.float()) # (num_heads) or (intermediate_size, state_size)
+ dt_limit_kwargs = {} if self.time_step_limit == (0.0, float("inf")) else {"dt_limit": self.time_step_limit}
+
+ # 2-4. Fused kernel for conv1d, SSM, and the final projection
+ if self.training and cache_params is None:
+ out = mamba_split_conv1d_scan_combined(
+ projected_states,
+ self.conv1d.weight.squeeze(1),
+ self.conv1d.bias,
+ self.dt_bias,
+ A,
+ D=self.D,
+ chunk_size=self.chunk_size,
+ seq_idx=seq_idx,
+ activation=self.activation,
+ rmsnorm_weight=self.norm.weight,
+ rmsnorm_eps=self.norm.variance_epsilon,
+ outproj_weight=self.out_proj.weight,
+ outproj_bias=self.out_proj.bias,
+ headdim=self.head_dim,
+ ngroups=self.n_groups,
+ norm_before_gate=False,
+ return_final_states=False,
+ **dt_limit_kwargs,
+ )
+
+ else:
+ gate, hidden_states_B_C, dt = projected_states.split(
+ [self.intermediate_size, self.conv_dim, self.num_heads], dim=-1
+ )
+
+ # 2. Convolution sequence transformation
+ # Init cache
+ if cache_params is not None:
+ # storing the states
+ # If we just take xBC[:, :, -self.d_conv :], it will error if seqlen < self.d_conv
+ # Instead F.pad will pad with zeros if seqlen < self.d_conv, and truncate otherwise.
+ hidden_states_B_C_transposed = hidden_states_B_C.transpose(1, 2)
+ conv_states = nn.functional.pad(
+ hidden_states_B_C_transposed,
+ (self.conv_kernel_size - hidden_states_B_C_transposed.shape[-1], 0),
+ )
+ conv_states = cache_params.update_conv_state(conv_states, self.layer_idx)
+
+ if self.activation not in ["silu", "swish"]:
+ hidden_states_B_C = self.act(
+ self.conv1d(hidden_states_B_C.transpose(1, 2))[..., :seq_len].transpose(1, 2)
+ )
+ else:
+ hidden_states_B_C = causal_conv1d_fn(
+ x=hidden_states_B_C.transpose(1, 2),
+ weight=self.conv1d.weight.squeeze(1),
+ bias=self.conv1d.bias,
+ activation=self.activation,
+ seq_idx=seq_idx,
+ ).transpose(1, 2)
+
+ hidden_states_B_C = apply_mask_to_padding_states(hidden_states_B_C, attention_mask)
+ hidden_states, B, C = torch.split(
+ hidden_states_B_C,
+ [self.intermediate_size, groups_time_state_size, groups_time_state_size],
+ dim=-1,
+ )
+
+ # 3. SSM transformation
+ scan_output, ssm_state = mamba_chunk_scan_combined(
+ hidden_states.view(batch_size, seq_len, -1, self.head_dim),
+ dt,
+ A,
+ B.view(batch_size, seq_len, self.n_groups, -1),
+ C.view(batch_size, seq_len, self.n_groups, -1),
+ chunk_size=self.chunk_size,
+ D=self.D,
+ z=None,
+ seq_idx=seq_idx,
+ return_final_states=True,
+ dt_bias=self.dt_bias,
+ dt_softplus=True,
+ **dt_limit_kwargs,
+ )
+
+ # Init cache
+ if ssm_state is not None and cache_params is not None:
+ ssm_state = cache_params.update_recurrent_state(ssm_state, self.layer_idx)
+
+ scan_output = scan_output.view(batch_size, seq_len, -1)
+ # Multiply "gate" branch and apply extra normalization layer
+ scan_output = self.norm(scan_output, gate)
+
+ # 4. Final linear projection
+ out = self.out_proj(scan_output)
+ return out
+
+ # fmt: off
+ def torch_forward(
+ self,
+ input_states,
+ cache_params: Cache | None = None,
+ attention_mask: torch.Tensor | None = None,
+ ):
+ batch_size, seq_len, _ = input_states.shape
+ dtype = input_states.dtype
+
+ # 1. Gated MLP's linear projection
+ input_states = apply_mask_to_padding_states(input_states, attention_mask)
+ projected_states = self.in_proj(input_states)
+ gate, hidden_states_B_C, dt = projected_states.split(
+ [self.intermediate_size, self.conv_dim, self.num_heads], dim=-1
+ )
+ hidden_states_B_C = hidden_states_B_C.transpose(1,2)
+
+ use_precomputed_states = cache_params is not None and cache_params.has_previous_state(self.layer_idx) and seq_len == 1
+
+ # 2. Convolution sequence transformation
+ if use_precomputed_states:
+ conv_states = cache_params.update_conv_state(hidden_states_B_C, self.layer_idx)
+
+ hidden_states_B_C = torch.sum(
+ conv_states * self.conv1d.weight.squeeze(1), dim=-1
+ )
+ if self.use_conv_bias:
+ hidden_states_B_C = hidden_states_B_C + self.conv1d.bias
+ hidden_states_B_C = self.act(hidden_states_B_C)
+ else:
+ # Init cache
+ if cache_params is not None:
+ conv_states = nn.functional.pad(
+ hidden_states_B_C, (self.conv_kernel_size - hidden_states_B_C.shape[-1], 0)
+ )
+ conv_states = cache_params.update_conv_state(conv_states, self.layer_idx)
+
+ hidden_states_B_C = self.act(self.conv1d(hidden_states_B_C)[..., :seq_len].transpose(1, 2))
+
+ hidden_states_B_C = apply_mask_to_padding_states(hidden_states_B_C, attention_mask)
+ hidden_states, B, C = torch.split(
+ hidden_states_B_C,
+ [self.intermediate_size, self.n_groups * self.ssm_state_size, self.n_groups * self.ssm_state_size],
+ dim=-1
+ )
+
+ # 3. SSM transformation
+ A = -torch.exp(self.A_log.float()) # [num_heads]
+ if use_precomputed_states:
+ # We need to guarantee that anything regarding the cache is on the same device
+ cache_device = cache_params.layers[self.layer_idx].recurrent_states.device
+
+ # Note: there is no need to pad parameter matrices here, as there is just one new token
+ # for batched generation
+ dt = dt[:, 0, :][:, None, ...]
+ dt = dt.transpose(1, 2).expand(batch_size, dt.shape[-1], self.head_dim)
+ # [num_heads] -> [num_heads, head_dim]
+ dt_bias = self.dt_bias[..., None].expand(self.dt_bias.shape[0], self.head_dim)
+
+ dt = torch.nn.functional.softplus(dt + dt_bias.to(dt.dtype))
+ dt = torch.clamp(dt, self.time_step_limit[0], self.time_step_limit[1])
+ A = A[..., None, None].expand(self.num_heads, self.head_dim, self.ssm_state_size).to(dtype=torch.float32)
+ # [bsz, num_heads, head_dim, state_size]
+ dA = (torch.exp(dt[..., None] * A)).to(device=cache_device)
+
+ # Discretize B
+ # [bsz, n_groups * state_size] -> [bsz, n_groups, 1, state_size] ->
+ # -> [bsz, n_groups, group to head repetition factor, state_size] -> [bsz, num_heads, state_size]
+ B = B.reshape(batch_size, self.n_groups, -1)[..., None, :]
+ B = B.expand(batch_size, self.n_groups, self.num_heads // self.n_groups, B.shape[-1]).contiguous()
+ B = B.reshape(batch_size, -1, B.shape[-1])
+ # [bsz, num_heads, head_dim, state_size]
+ dB = dt[..., None] * B[..., None, :]
+
+ # Discretize x into dB
+ # [bsz, intermediate_size] -> [bsz, num_heads, head_dim]
+ hidden_states = hidden_states.reshape(batch_size, -1, self.head_dim)
+ dBx = (dB * hidden_states[..., None]).to(device=cache_device)
+
+ # State calculation
+ ssm_states = cache_params.layers[self.layer_idx].recurrent_states * dA + dBx
+ ssm_states = cache_params.update_recurrent_state(ssm_states, self.layer_idx)
+
+ # Subsequent output
+ # [bsz, n_groups * state_size] -> [bsz, num_heads, state_size]
+ C = C.reshape(batch_size, self.n_groups, -1)[..., None, :]
+ C = C.expand(batch_size, self.n_groups, self.num_heads // self.n_groups, C.shape[-1]).contiguous()
+ C = C.reshape(batch_size, -1, C.shape[-1])
+ # [bsz, num_heads, head_dim]
+
+ ssm_states = ssm_states.to(device=C.device, dtype=C.dtype) # Shape: [b, h, d, n]
+ # Reshape ssm_states to merge the first two dimensions
+ ssm_states_reshaped = ssm_states.view(batch_size * self.num_heads, self.head_dim, self.ssm_state_size) # Shape: [b*h, d, n]
+ C_reshaped = C.view(batch_size * self.num_heads, self.ssm_state_size, 1) # Shape: [b*h, n, 1]
+ y = torch.bmm(ssm_states_reshaped, C_reshaped)
+ y = y.view(batch_size, self.num_heads, self.head_dim)
+
+ # D skip connection
+ # [num_heads] -> [num_heads, head_dim]
+ D = self.D[..., None].expand(self.D.shape[0], self.head_dim)
+ y = (y + hidden_states * D).to(y.dtype)
+
+ # [bsz, num_heads, head_dim] -> [bsz, 1, intermediate_size]
+ y = y.reshape(batch_size, -1)[:, None, ...]
+ else:
+ # begin ssd naive implementation without einsums
+ dt = nn.functional.softplus(dt + self.dt_bias)
+ dt = torch.clamp(dt, self.time_step_limit[0], self.time_step_limit[1])
+ hidden_states = hidden_states.reshape(batch_size, seq_len, -1, self.head_dim).float()
+ B = B.reshape(batch_size, seq_len, -1, self.ssm_state_size).float()
+ C = C.reshape(batch_size, seq_len, -1, self.ssm_state_size).float()
+ B = B.repeat_interleave(self.num_heads // self.n_groups, dim=2, output_size=self.num_heads)
+ C = C.repeat_interleave(self.num_heads // self.n_groups, dim=2, output_size=self.num_heads)
+ pad_size = (self.chunk_size - seq_len % self.chunk_size) % self.chunk_size
+
+ D_residual = self.D[..., None] * pad_tensor_by_size(hidden_states, pad_size)
+
+ # Discretize x and A
+ hidden_states = hidden_states * dt[..., None]
+ A = A.to(hidden_states.dtype) * dt
+
+ # Rearrange into blocks/chunks
+ hidden_states, A, B, C = [reshape_into_chunks(t, pad_size, self.chunk_size) for t in (hidden_states, A, B, C)]
+
+ # [bsz, -1, chunk_size, num_heads] -> [bsz, num_heads, -1, chunk_size]
+ A = A.permute(0, 3, 1, 2)
+ A_cumsum = torch.cumsum(A, dim=-1)
+
+ # 1. Compute the output for each intra-chunk (diagonal blocks)
+ # This is the analog of a causal mask
+ L = torch.exp(segment_sum(A))
+
+ # Contraction of C and B to get G (attention-weights like)
+ G_intermediate = C[:, :, :, None, :, :] * B[:, :, None, :, :, :] # shape: (b, c, l, s, h, n)
+ G = G_intermediate.sum(dim=-1) # shape: (b, c, l, s, h)
+
+ # Compute M, equivalent to applying attention mask to weights
+ M_intermediate = G[..., None] * L.permute(0, 2, 3, 4, 1)[..., None]
+ M = M_intermediate.sum(dim=-1)
+
+ # Compute Y_diag (apply to values)
+ Y_diag = (M[..., None] * hidden_states[:, :, None]).sum(dim=3)
+
+ # 2. Compute the state for each intra-chunk
+ # (right term of low-rank factorization of off-diagonal blocks; B terms)
+ decay_states = torch.exp(A_cumsum[:, :, :, -1:] - A_cumsum)
+ B_decay = B * decay_states.permute(0, -2, -1, 1)[..., None]
+ states = (B_decay[..., None, :] * hidden_states[..., None]).sum(dim=2)
+
+ # 3. Compute the inter-chunk SSM recurrence; produces correct SSM states at chunk boundaries
+ # (middle term of factorization of off-diag blocks; A terms)
+ previous_states = torch.zeros_like(states[:, :1])
+ states = torch.cat([previous_states, states], dim=1)
+ decay_chunk = torch.exp(segment_sum(nn.functional.pad(A_cumsum[:, :, :, -1], (1, 0))))
+ decay_chunk = decay_chunk.transpose(1, 3)
+ new_states = (decay_chunk[..., None, None] * states[:, :, None, ...]).sum(dim=1)
+ states, ssm_state = new_states[:, :-1], new_states[:, -1]
+
+ # 4. Compute state -> output conversion per chunk
+ # (left term of low-rank factorization of off-diagonal blocks; C terms)
+ state_decay_out = torch.exp(A_cumsum)
+ C_times_states = (C[..., None, :] * states[:, :, None, ...])
+ state_decay_out_permuted = state_decay_out.permute(0, 2, 3, 1)
+ Y_off = (C_times_states.sum(-1) * state_decay_out_permuted[..., None])
+
+ # Add output of intra-chunk and inter-chunk terms (diagonal and off-diagonal blocks)
+ y = Y_diag + Y_off
+ # [bsz, -1, self.chunk_size, num_heads, head_dim] -> [bsz, (padded) seq_len, num_heads, head_dim]
+ y = y.reshape(batch_size, -1, self.num_heads, self.head_dim)
+
+ y = y + D_residual
+ # Cutting off padded chunks
+ if pad_size > 0:
+ y = y[:, :seq_len, :, :]
+ y = y.reshape(batch_size, seq_len, -1)
+
+ # Init cache
+ if ssm_state is not None and cache_params is not None:
+ ssm_state = cache_params.update_recurrent_state(ssm_state, self.layer_idx)
+
+ scan_output = self.norm(y, gate)
+
+ # end ssd naive
+
+ # 4. Final linear projection
+ contextualized_states = self.out_proj(scan_output.to(dtype)) # [batch, seq_len, hidden_size]
+ return contextualized_states
+ # fmt: on
+
+ def forward(
+ self,
+ hidden_states,
+ cache_params: Cache | None = None,
+ attention_mask: torch.Tensor | None = None,
+ seq_idx: torch.IntTensor | None = None,
+ **kwargs,
+ ):
+ if is_fast_path_available and "cuda" in self.in_proj.weight.device.type and not is_torchdynamo_compiling():
+ return self.cuda_kernels_forward(hidden_states, cache_params, attention_mask, seq_idx)
+ if seq_idx is not None:
+ raise NotImplementedError(
+ "`seq_idx` support requires fast path support. Please install `mamba_ssm` and `causal_conv1d`"
+ )
+ dtype = hidden_states.dtype
+ if attention_mask is not None and attention_mask.shape[1] > 1 and attention_mask.shape[0] > 1:
+ # tune out hidden states for pad tokens, see https://github.com/state-spaces/mamba/issues/66
+ hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype)
+
+ return self.torch_forward(hidden_states, cache_params, attention_mask)
+
+
+class GraniteMoeHybridRMSNormGated(torch.nn.Module):
+ def __init__(self, hidden_size, eps=1e-6):
+ super().__init__()
+ self.weight = nn.Parameter(torch.ones(hidden_size))
+ self.variance_epsilon = eps
+
+ def forward(self, hidden_states, gate=None):
+ input_dtype = hidden_states.dtype
+ hidden_states = hidden_states.to(torch.float32)
+
+ if gate is not None:
+ hidden_states = hidden_states * nn.functional.silu(gate.to(torch.float32))
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
+
+ return self.weight * hidden_states.to(input_dtype)
+
+
+class GraniteMoeHybridMLP(nn.Module):
+ """
+ MLP layer for shared experts
+
+ Args:
+ config:
+ Configuration object with model hyperparameters.
+ """
+
+ def __init__(self, config: GraniteMoeHybridConfig):
+ super().__init__()
+
+ self.input_size = config.hidden_size
+ self.hidden_size = config.shared_intermediate_size
+ self.activation = ACT2FN[config.hidden_act]
+ self.input_linear = nn.Linear(self.input_size, self.hidden_size * 2, bias=False)
+ self.output_linear = nn.Linear(self.hidden_size, self.input_size, bias=False)
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.input_linear(hidden_states)
+ chunked_hidden_states = hidden_states.chunk(2, dim=-1)
+ hidden_states = self.activation(chunked_hidden_states[0]) * chunked_hidden_states[1]
+ hidden_states = self.output_linear(hidden_states)
+ return hidden_states
+
+
+class GraniteMoeHybridRotaryEmbedding(nn.Module):
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
+
+ def __init__(self, config: GraniteMoeHybridConfig, device=None):
+ super().__init__()
+ self.max_seq_len_cached = config.max_position_embeddings
+ self.original_max_seq_len = config.max_position_embeddings
+
+ self.config = config
+
+ self.rope_type = self.config.rope_parameters["rope_type"]
+ rope_init_fn: Callable = self.compute_default_rope_parameters
+ if self.rope_type != "default":
+ rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
+ inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
+
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
+ self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
+
+ @staticmethod
+ def compute_default_rope_parameters(
+ config: GraniteMoeHybridConfig | None = None,
+ device: Optional["torch.device"] = None,
+ seq_len: int | None = None,
+ ) -> tuple["torch.Tensor", float]:
+ """
+ Computes the inverse frequencies according to the original RoPE implementation
+ Args:
+ config ([`~transformers.PreTrainedConfig`]):
+ The model configuration.
+ device (`torch.device`):
+ The device to use for initialization of the inverse frequencies.
+ seq_len (`int`, *optional*):
+ The current sequence length. Unused for this type of RoPE.
+ Returns:
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
+ """
+ base = config.rope_parameters["rope_theta"]
+ dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
+
+ attention_factor = 1.0 # Unused in this type of RoPE
+
+ # Compute the inverse frequencies
+ inv_freq = 1.0 / (
+ base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
+ )
+ return inv_freq, attention_factor
+
+ @torch.no_grad()
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
+ def forward(self, x, position_ids):
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
+ position_ids_expanded = position_ids[:, None, :].float()
+
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
+ with maybe_autocast(device_type=device_type, enabled=False): # Force float32
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
+ emb = torch.cat((freqs, freqs), dim=-1)
+ cos = emb.cos() * self.attention_scaling
+ sin = emb.sin() * self.attention_scaling
+
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
+
+
+class GraniteMoeHybridParallelExperts(nn.Module):
+ def __init__(self, num_experts: int, input_size: int, output_size: int) -> None:
+ """
+ Initialize the GraniteMoeHybridParallelExperts module.
+ The experts weights are stored in [num_experts, output_size, input_size] format. Such that it's compatible with
+ many MoE libraries, such as [Megablock](https://github.com/databricks/megablocks) and
+ [ScatterMoE](https://github.com/shawntan/scattermoe), as well as the
+ [MoE kernel](https://github.com/vllm-project/vllm/blob/main/vllm/model_executor/layers/fused_moe/fused_moe.py)
+ used in vllm.
+
+ Args:
+ num_experts (int):
+ Number of experts.
+ input_size (int):
+ Size of the input.
+ output_size (int):
+ Size of the output.
+ """
+ super().__init__()
+ self.weight = nn.Parameter(torch.empty(num_experts, output_size, input_size))
+ self.num_experts = num_experts
+ self.input_size = input_size
+ self.output_size = output_size
+
+ def forward(self, inputs, expert_size):
+ """
+ Forward pass of the GraniteMoeHybridParallelExperts module.
+
+ Args:
+ inputs (Tensor):
+ Input tensor.
+ expert_size:
+ Expert size information.
+
+ Returns:
+ Tensor: Output tensor.
+ """
+ input_list = inputs.split(expert_size, dim=0)
+ output_list = []
+ for i in range(self.num_experts):
+ output_list.append(F.linear(input_list[i], self.weight[i]))
+ results = torch.cat(output_list, dim=0)
+ return results
+
+
+class GraniteMoeHybridTopKGating(nn.Module):
+ def __init__(self, input_size: int, num_experts: int, top_k: int):
+ """
+ Initialize the top-k gating mechanism.
+
+ Args:
+ input_size (`int`):
+ Size of the input.
+ num_experts (`int`):
+ Number of experts.
+ top_k (`int`):
+ Number of top experts to select.
+ """
+ super().__init__()
+
+ self.num_experts = num_experts
+ self.input_size = input_size
+ self.top_k = top_k
+
+ self.layer = nn.Linear(input_size, num_experts, bias=False)
+
+ def forward(self, hidden_states):
+ # compute the top_k routing decision
+ logits = self.layer(hidden_states).float() # [batch_size x seq_len, num_experts]
+ top_k_logits, top_k_indices = logits.topk(self.top_k, dim=1) # [num_tokens, top_k]
+ top_k_gates = torch.softmax(top_k_logits, dim=1).type_as(hidden_states) # [num_tokens, top_k]
+
+ # compute number of input given to each expert
+ zeros = torch.zeros(
+ [top_k_gates.size(0), self.num_experts], dtype=top_k_gates.dtype, device=top_k_gates.device
+ ) # [num_tokens, num_experts]
+ gates = zeros.scatter(1, top_k_indices, 1) # [num_tokens, num_experts]
+ expert_size = gates.long().sum(0) # [num_experts,]
+ # (This cause torch.compile to fail with `torch._dynamo.exc.Unsupported: Backend compiler failed with a fake tensor exception at`)
+ # (and `DataDependentOutputException`)
+ expert_size = expert_size.tolist()
+
+ # sort and group input tokens according to expert assignment
+ top_k_experts = top_k_indices.flatten() # [num_tokens * top_k]
+ _, index_sorted_experts = top_k_experts.sort(0) # [num_tokens * top_k]
+ batch_index = index_sorted_experts.div(self.top_k, rounding_mode="trunc") # [num_tokens * top_k]
+
+ # gather the gate values for grouped input tokens
+ top_k_gates = top_k_gates.flatten() # [num_tokens * top_k]
+ batch_gates = top_k_gates[index_sorted_experts] # [num_tokens * top_k]
+
+ return index_sorted_experts, batch_index, batch_gates, expert_size, logits
+
+
+class GraniteMoeHybridMoE(nn.Module):
+ """
+ A Sparsely gated mixture of experts layer with 1-layer Feed-Forward networks as experts.
+
+ Args:
+ config:
+ Configuration object with model hyperparameters.
+ """
+
+ def __init__(self, config: GraniteMoeHybridConfig):
+ super().__init__()
+
+ self.input_size = config.hidden_size
+ self.hidden_size = config.intermediate_size
+ self.activation = ACT2FN[config.hidden_act]
+ self.input_linear = GraniteMoeHybridParallelExperts(
+ config.num_local_experts, self.input_size, self.hidden_size * 2
+ )
+ self.output_linear = GraniteMoeHybridParallelExperts(
+ config.num_local_experts, self.hidden_size, self.input_size
+ )
+
+ self.router = GraniteMoeHybridTopKGating(
+ input_size=self.input_size,
+ num_experts=config.num_local_experts,
+ top_k=config.num_experts_per_tok,
+ )
+
+ def forward(self, layer_input):
+ bsz, length, emb_size = layer_input.size()
+ layer_input = layer_input.reshape(-1, emb_size)
+ _, batch_index, batch_gates, expert_size, _ = self.router(layer_input)
+
+ expert_inputs = layer_input[batch_index]
+ hidden_states = self.input_linear(expert_inputs, expert_size)
+ chunked_hidden_states = hidden_states.chunk(2, dim=-1)
+ hidden_states = self.activation(chunked_hidden_states[0]) * chunked_hidden_states[1]
+ expert_outputs = self.output_linear(hidden_states, expert_size)
+
+ expert_outputs = expert_outputs * batch_gates[:, None]
+
+ zeros = torch.zeros((bsz * length, self.input_size), dtype=expert_outputs.dtype, device=expert_outputs.device)
+ layer_output = zeros.index_add(0, batch_index, expert_outputs)
+ layer_output = layer_output.view(bsz, length, self.input_size)
+ return layer_output
+
+
+class GraniteFlashAttentionKwargs(TypedDict, total=False):
+ """
+ Keyword arguments for advanced Flash Attention, causal-conv1d, and mamba_ssm kernel usage.
+ Use cases include padding-free training and fewer `torch.compile` graph breaks.
+
+ cu_seq_lens_q (`torch.LongTensor`):
+ Gets cumulative sequence length for query state.
+ cu_seq_lens_k (`torch.LongTensor`):
+ Gets cumulative sequence length for key state.
+ max_length_q (`int`):
+ Maximum sequence length for query state.
+ max_length_k (`int`):
+ Maximum sequence length for key state.
+ seq_idx (`torch.IntTensor):
+ Index of each packed sequence.
+ """
+
+ cu_seq_lens_q: torch.LongTensor
+ cu_seq_lens_k: torch.LongTensor
+ max_length_q: int
+ max_length_k: int
+ seq_idx: torch.IntTensor
+
+
+@use_kernel_forward_from_hub("RMSNorm")
+class GraniteMoeHybridRMSNorm(nn.Module):
+ def __init__(self, hidden_size, eps: float = 1e-6) -> None:
+ """
+ GraniteMoeHybridRMSNorm is equivalent to T5LayerNorm
+ """
+ super().__init__()
+ self.weight = nn.Parameter(torch.ones(hidden_size))
+ self.variance_epsilon = eps
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ input_dtype = hidden_states.dtype
+ hidden_states = hidden_states.to(torch.float32)
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
+ return self.weight * hidden_states.to(input_dtype)
+
+ def extra_repr(self):
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
+
+
+class GraniteMoeHybridDecoderLayer(GradientCheckpointingLayer):
+ def __init__(self, config: GraniteMoeHybridConfig, layer_idx: int):
+ super().__init__()
+ self.hidden_size = config.hidden_size
+ # Either attention or mamba will be initialized, depending on the layer type.
+ self.self_attn = None
+ self.input_layernorm = GraniteMoeHybridRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.post_attention_layernorm = GraniteMoeHybridRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+
+ # Allow non-MoE (dense)
+ self.block_sparse_moe = GraniteMoeHybridMoE(config) if config.num_local_experts > 0 else None
+ self.residual_multiplier = config.residual_multiplier # Only diff with mixtral!
+ self.shared_mlp = GraniteMoeHybridMLP(config)
+ self.mamba = None
+
+ if config.layers_block_type[layer_idx] == "mamba":
+ self.mamba = GraniteMoeHybridMambaLayer(config, layer_idx)
+ else:
+ self.self_attn = GraniteMoeHybridAttention(config, layer_idx)
+ self.layer_type = config.layers_block_type[layer_idx]
+
+ # Accept 0 experts: skip MoE if num_local_experts == 0
+ self.has_experts = getattr(config, "num_local_experts", 0) > 0
+
+ @auto_docstring
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor | None = None,
+ past_key_values: Cache | None = None,
+ use_cache: bool | None = False,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
+ **kwargs: Unpack[GraniteFlashAttentionKwargs],
+ ) -> tuple[torch.FloatTensor, tuple[torch.FloatTensor, torch.FloatTensor] | None]:
+ residual = hidden_states
+ hidden_states = self.input_layernorm(hidden_states)
+
+ if self.mamba is not None:
+ hidden_states = self.mamba(
+ hidden_states=hidden_states,
+ cache_params=past_key_values,
+ attention_mask=attention_mask,
+ **kwargs,
+ )
+ else:
+ hidden_states, _ = self.self_attn(
+ hidden_states=hidden_states,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ position_embeddings=position_embeddings,
+ **kwargs,
+ )
+
+ hidden_states = residual + hidden_states * self.residual_multiplier
+ residual = hidden_states
+ hidden_states = self.post_attention_layernorm(hidden_states)
+
+ if self.has_experts:
+ moe_hidden_states = self.block_sparse_moe(hidden_states)
+ hidden_states = moe_hidden_states + self.shared_mlp(hidden_states)
+ else:
+ hidden_states = self.shared_mlp(hidden_states)
+
+ hidden_states = residual + hidden_states * self.residual_multiplier
+ return hidden_states
+
+
+@auto_docstring
+class GraniteMoeHybridPreTrainedModel(PreTrainedModel):
+ config: GraniteMoeHybridConfig
+ base_model_prefix = "model"
+ supports_gradient_checkpointing = True
+ _no_split_modules = ["GraniteMoeHybridDecoderLayer"]
+ _skip_keys_device_placement = ["past_key_values"]
+ _supports_flash_attn = True
+ _supports_sdpa = True
+ _supports_flex_attn = True
+ _can_compile_fullgraph = False # TopK gating fails fullgraph compilation at "expert_size = expert_size.tolist()"
+ _supports_attention_backend = True
+ _can_record_outputs = {
+ "hidden_states": GraniteMoeHybridDecoderLayer,
+ "attentions": GraniteMoeHybridAttention,
+ }
+ _is_stateful = True
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ super()._init_weights(module)
+ if isinstance(module, GraniteMoeHybridParallelExperts):
+ init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
+ if isinstance(module, GraniteMoeHybridMambaLayer):
+ init.ones_(module.dt_bias)
+ init.copy_(module.A_log, torch.log(torch.arange(1, module.num_heads + 1)))
+ init.ones_(module.D)
+ elif isinstance(module, GraniteMoeHybridRMSNormGated):
+ init.ones_(module.weight)
+
+
+@auto_docstring
+class GraniteMoeHybridModel(GraniteMoeHybridPreTrainedModel):
+ def __init__(self, config: GraniteMoeHybridConfig):
+ super().__init__(config)
+ self.padding_idx = config.pad_token_id
+ self.vocab_size = config.vocab_size
+
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
+ self.layers = nn.ModuleList(
+ [GraniteMoeHybridDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
+ )
+ self.norm = GraniteMoeHybridRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.rotary_emb = GraniteMoeHybridRotaryEmbedding(config) if config.position_embedding_type == "rope" else None
+ self.gradient_checkpointing = False
+ self.embedding_multiplier = config.embedding_multiplier
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ @merge_with_config_defaults
+ @capture_outputs
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ use_cache: bool | None = None,
+ **kwargs: Unpack[GraniteFlashAttentionKwargs],
+ ) -> tuple | BaseModelOutputWithPast:
+ if (input_ids is None) ^ (inputs_embeds is not None):
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
+
+ if inputs_embeds is None:
+ inputs_embeds = self.embed_tokens(input_ids)
+
+ inputs_embeds = inputs_embeds * self.embedding_multiplier
+
+ if use_cache and past_key_values is None:
+ past_key_values = DynamicCache(config=self.config)
+
+ if position_ids is None:
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
+ position_ids = position_ids.unsqueeze(0)
+
+ causal_mask_mapping = {}
+ for layer_type in set(self.config.layers_block_type):
+ if "mamba" in layer_type:
+ causal_mask_mapping[layer_type] = self._update_mamba_mask(attention_mask, past_key_values)
+ else:
+ causal_mask_mapping[layer_type] = create_causal_mask(
+ config=self.config,
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ )
+
+ # embed positions
+ hidden_states = inputs_embeds
+ position_embeddings = None
+ if self.rotary_emb is not None:
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
+
+ for i, decoder_layer in enumerate(self.layers):
+ hidden_states = decoder_layer(
+ hidden_states,
+ attention_mask=causal_mask_mapping[self.config.layers_block_type[i]],
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ position_embeddings=position_embeddings,
+ **kwargs,
+ )
+ hidden_states = self.norm(hidden_states)
+
+ return MoeModelOutputWithPast(
+ last_hidden_state=hidden_states,
+ past_key_values=past_key_values,
+ )
+
+ def _update_mamba_mask(self, attention_mask, past_key_values):
+ """
+ No need for zeroing states when
+ 1. Cached forward
+ 2. Attending to all inputs
+ """
+ mamba_mask = attention_mask
+ if (past_key_values is not None and past_key_values.has_previous_state()) or (
+ attention_mask is not None and torch.all(attention_mask == 1)
+ ):
+ mamba_mask = None
+ return mamba_mask
+
+
+def load_balancing_loss_func(
+ gate_logits: torch.Tensor | tuple[torch.Tensor] | None,
+ num_experts: int | None = None,
+ top_k=2,
+ attention_mask: torch.Tensor | None = None,
+) -> torch.Tensor | int:
+ r"""
+ Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
+
+ See Switch Transformer (https://huggingface.co/papers/2101.03961) for more details. This function implements the loss
+ function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
+ experts is too unbalanced.
+
+ Args:
+ gate_logits:
+ Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of
+ shape [batch_size X sequence_length, num_experts].
+ num_experts:
+ Number of experts
+ top_k:
+ The number of experts to route per-token, can be also interpreted as the `top-k` routing
+ parameter.
+ attention_mask (`torch.Tensor`, *optional*):
+ The attention_mask used in forward function
+ shape [batch_size X sequence_length] if not None.
+
+ Returns:
+ The auxiliary loss.
+ """
+ if gate_logits is None or not isinstance(gate_logits, tuple):
+ return 0
+
+ if isinstance(gate_logits, tuple):
+ compute_device = gate_logits[0].device
+ concatenated_gate_logits = torch.cat([layer_gate.to(compute_device) for layer_gate in gate_logits], dim=0)
+
+ routing_weights = torch.nn.functional.softmax(concatenated_gate_logits, dim=-1)
+
+ _, selected_experts = torch.topk(routing_weights, top_k, dim=-1)
+
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_experts)
+
+ if attention_mask is None:
+ # Compute the percentage of tokens routed to each experts
+ tokens_per_expert = torch.mean(expert_mask.float(), dim=0)
+
+ # Compute the average probability of routing to these experts
+ router_prob_per_expert = torch.mean(routing_weights, dim=0)
+ else:
+ batch_size, sequence_length = attention_mask.shape
+ num_hidden_layers = concatenated_gate_logits.shape[0] // (batch_size * sequence_length)
+
+ # Compute the mask that masks all padding tokens as 0 with the same shape of expert_mask
+ expert_attention_mask = (
+ attention_mask[None, :, :, None, None]
+ .expand((num_hidden_layers, batch_size, sequence_length, top_k, num_experts))
+ .reshape(-1, top_k, num_experts)
+ .to(compute_device)
+ )
+
+ # Compute the percentage of tokens routed to each experts
+ tokens_per_expert = torch.sum(expert_mask.float() * expert_attention_mask, dim=0) / torch.sum(
+ expert_attention_mask, dim=0
+ )
+
+ # Compute the mask that masks all padding tokens as 0 with the same shape of tokens_per_expert
+ router_per_expert_attention_mask = (
+ attention_mask[None, :, :, None]
+ .expand((num_hidden_layers, batch_size, sequence_length, num_experts))
+ .reshape(-1, num_experts)
+ .to(compute_device)
+ )
+
+ # Compute the average probability of routing to these experts
+ router_prob_per_expert = torch.sum(routing_weights * router_per_expert_attention_mask, dim=0) / torch.sum(
+ router_per_expert_attention_mask, dim=0
+ )
+
+ overall_loss = torch.sum(tokens_per_expert * router_prob_per_expert.unsqueeze(0))
+ return overall_loss * num_experts
+
+
+@auto_docstring
+class GraniteMoeHybridForCausalLM(GraniteMoeHybridPreTrainedModel, GenerationMixin):
+ _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
+ _tp_plan = {"lm_head": "colwise_gather_output"}
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
+
+ def __init__(self, config: GraniteMoeHybridConfig):
+ super().__init__(config)
+ self.model = GraniteMoeHybridModel(config)
+ self.vocab_size = config.vocab_size
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
+ self.router_aux_loss_coef = config.router_aux_loss_coef
+ self.num_experts = config.num_local_experts
+ self.num_experts_per_tok = config.num_experts_per_tok
+ self.logits_scaling = config.logits_scaling
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ @can_return_tuple
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ output_router_logits: bool | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ **kwargs,
+ ) -> tuple | MoeCausalLMOutputWithPast:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
+
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, GraniteMoeHybridForCausalLM
+
+ >>> model = GraniteMoeHybridForCausalLM.from_pretrained("ibm-granite/granite-4.0-h-tiny")
+ >>> tokenizer = AutoTokenizer.from_pretrained("ibm-granite/granite-4.0-h-tiny")
+
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
+
+ >>> # Generate
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
+ ```"""
+ output_router_logits = (
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
+ )
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
+ outputs = self.model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ **kwargs,
+ )
+
+ # Only compute necessary logits
+ hidden_states = outputs.last_hidden_state
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
+ logits = logits / self.config.logits_scaling
+
+ loss = None
+ if labels is not None:
+ # Flatten the tokens
+ loss = self.loss_function(
+ logits,
+ labels,
+ vocab_size=self.config.vocab_size,
+ **kwargs,
+ )
+
+ aux_loss = None
+ if output_router_logits:
+ aux_loss = load_balancing_loss_func(
+ outputs.router_logits,
+ self.num_experts,
+ self.num_experts_per_tok,
+ attention_mask,
+ )
+ if labels is not None:
+ loss += self.router_aux_loss_coef * aux_loss.to(loss.device) # make sure to reside in the same device
+ return MoeCausalLMOutputWithPast(
+ loss=loss,
+ aux_loss=aux_loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ router_logits=outputs.router_logits,
+ )
+
+
+__all__ = ["GraniteMoeHybridForCausalLM", "GraniteMoeHybridModel", "GraniteMoeHybridPreTrainedModel"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/granitemoehybrid/modular_granitemoehybrid.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/granitemoehybrid/modular_granitemoehybrid.py
new file mode 100644
index 0000000000000000000000000000000000000000..741c58e005f837fb3a805d733c74c3ea9045952b
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/granitemoehybrid/modular_granitemoehybrid.py
@@ -0,0 +1,320 @@
+# Copyright 2025 IBM and the HuggingFace Inc. team. All rights reserved.
+#
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from collections.abc import Callable
+
+import torch
+from torch import nn
+
+from ... import initialization as init
+from ...cache_utils import Cache, DynamicCache
+from ...masking_utils import create_causal_mask
+from ...modeling_outputs import BaseModelOutputWithPast, MoeModelOutputWithPast
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS
+from ...processing_utils import Unpack
+from ...utils import TransformersKwargs, auto_docstring, logging
+from ...utils.generic import merge_with_config_defaults
+from ...utils.output_capturing import capture_outputs
+from ..bamba.configuration_bamba import BambaConfig
+from ..bamba.modeling_bamba import BambaMixer, BambaRMSNormGated
+from ..gemma2.modeling_gemma2 import Gemma2RotaryEmbedding
+from ..granitemoeshared.modeling_granitemoeshared import (
+ GraniteFlashAttentionKwargs,
+ GraniteMoeSharedAttention,
+ GraniteMoeSharedDecoderLayer,
+ GraniteMoeSharedForCausalLM,
+ GraniteMoeSharedMLP,
+ GraniteMoeSharedModel,
+ GraniteMoeSharedMoE,
+ GraniteMoeSharedPreTrainedModel,
+ apply_rotary_pos_emb,
+ eager_attention_forward,
+)
+from .configuration_granitemoehybrid import GraniteMoeHybridConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+class GraniteMoeHybridAttention(GraniteMoeSharedAttention):
+ def __init__(self, config: GraniteMoeHybridConfig, layer_idx: int):
+ super().__init__(config, layer_idx)
+
+ def forward( # FIME: @ARTHUR this forward is also classic: attention nope
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor | None,
+ past_key_values: Cache | None = None,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None, # None or rope embeddings
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor, torch.Tensor]:
+ input_shape = hidden_states.shape[:-1]
+ hidden_shape = (*input_shape, -1, self.head_dim)
+
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+
+ if position_embeddings is not None:
+ cos, sin = position_embeddings
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
+
+ if past_key_values is not None:
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_states,
+ key_states,
+ value_states,
+ attention_mask,
+ dropout=0.0 if not self.training else self.attention_dropout,
+ scaling=self.scaling,
+ **kwargs,
+ )
+
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ attn_output = self.o_proj(attn_output)
+ return attn_output, attn_weights
+
+
+class GraniteMoeHybridMambaLayer(BambaMixer):
+ def __init__(self, config: GraniteMoeHybridConfig, layer_idx: int):
+ super().__init__(BambaConfig(config), layer_idx)
+
+
+class GraniteMoeHybridRMSNormGated(BambaRMSNormGated):
+ def __init__(self, hidden_size, eps=1e-6):
+ super().__init__(hidden_size, eps)
+
+
+class GraniteMoeHybridMLP(GraniteMoeSharedMLP):
+ def __init__(self, config: GraniteMoeHybridConfig):
+ super().__init__(config)
+
+
+class GraniteMoeHybridRotaryEmbedding(Gemma2RotaryEmbedding):
+ pass
+
+
+class GraniteMoeHybridMoE(GraniteMoeSharedMoE):
+ pass
+
+
+class GraniteMoeHybridDecoderLayer(GraniteMoeSharedDecoderLayer):
+ def __init__(self, config: GraniteMoeHybridConfig, layer_idx: int):
+ super().__init__(config, layer_idx)
+ self.shared_mlp = GraniteMoeHybridMLP(config)
+ # Either attention or mamba will be initialized, depending on the layer type.
+ self.self_attn = None
+ self.mamba = None
+
+ if config.layers_block_type[layer_idx] == "mamba":
+ self.mamba = GraniteMoeHybridMambaLayer(config, layer_idx)
+ else:
+ self.self_attn = GraniteMoeHybridAttention(config, layer_idx)
+ self.layer_type = config.layers_block_type[layer_idx]
+
+ # Allow non-MoE (dense)
+ self.block_sparse_moe = GraniteMoeHybridMoE(config) if config.num_local_experts > 0 else None
+
+ # Accept 0 experts: skip MoE if num_local_experts == 0
+ self.has_experts = getattr(config, "num_local_experts", 0) > 0
+
+ @auto_docstring
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor | None = None,
+ past_key_values: Cache | None = None,
+ use_cache: bool | None = False,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
+ **kwargs: Unpack[GraniteFlashAttentionKwargs],
+ ) -> tuple[torch.FloatTensor, tuple[torch.FloatTensor, torch.FloatTensor] | None]:
+ residual = hidden_states
+ hidden_states = self.input_layernorm(hidden_states)
+
+ if self.mamba is not None:
+ hidden_states = self.mamba(
+ hidden_states=hidden_states,
+ cache_params=past_key_values,
+ attention_mask=attention_mask,
+ **kwargs,
+ )
+ else:
+ hidden_states, _ = self.self_attn(
+ hidden_states=hidden_states,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ position_embeddings=position_embeddings,
+ **kwargs,
+ )
+
+ hidden_states = residual + hidden_states * self.residual_multiplier
+ residual = hidden_states
+ hidden_states = self.post_attention_layernorm(hidden_states)
+
+ if self.has_experts:
+ moe_hidden_states = self.block_sparse_moe(hidden_states)
+ hidden_states = moe_hidden_states + self.shared_mlp(hidden_states)
+ else:
+ hidden_states = self.shared_mlp(hidden_states)
+
+ hidden_states = residual + hidden_states * self.residual_multiplier
+ return hidden_states
+
+
+class GraniteMoeHybridPreTrainedModel(GraniteMoeSharedPreTrainedModel):
+ config: GraniteMoeHybridConfig
+ _no_split_modules = ["GraniteMoeHybridDecoderLayer"]
+ _is_stateful = True
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ super()._init_weights(module)
+ if isinstance(module, GraniteMoeHybridMambaLayer):
+ init.ones_(module.dt_bias)
+ init.copy_(module.A_log, torch.log(torch.arange(1, module.num_heads + 1)))
+ init.ones_(module.D)
+ elif isinstance(module, GraniteMoeHybridRMSNormGated):
+ init.ones_(module.weight)
+
+
+class GraniteMoeHybridModel(GraniteMoeSharedModel):
+ def __init__(self, config: GraniteMoeHybridConfig):
+ super().__init__(config)
+ self.layers = nn.ModuleList(
+ [GraniteMoeHybridDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
+ )
+ self.embedding_multiplier = config.embedding_multiplier
+ self.rotary_emb = GraniteMoeHybridRotaryEmbedding(config) if config.position_embedding_type == "rope" else None
+
+ @auto_docstring
+ @merge_with_config_defaults
+ @capture_outputs
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ use_cache: bool | None = None,
+ **kwargs: Unpack[GraniteFlashAttentionKwargs],
+ ) -> tuple | BaseModelOutputWithPast:
+ if (input_ids is None) ^ (inputs_embeds is not None):
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
+
+ if inputs_embeds is None:
+ inputs_embeds = self.embed_tokens(input_ids)
+
+ inputs_embeds = inputs_embeds * self.embedding_multiplier
+
+ if use_cache and past_key_values is None:
+ past_key_values = DynamicCache(config=self.config)
+
+ if position_ids is None:
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
+ position_ids = position_ids.unsqueeze(0)
+
+ causal_mask_mapping = {}
+ for layer_type in set(self.config.layers_block_type):
+ if "mamba" in layer_type:
+ causal_mask_mapping[layer_type] = self._update_mamba_mask(attention_mask, past_key_values)
+ else:
+ causal_mask_mapping[layer_type] = create_causal_mask(
+ config=self.config,
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ )
+
+ # embed positions
+ hidden_states = inputs_embeds
+ position_embeddings = None
+ if self.rotary_emb is not None:
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
+
+ for i, decoder_layer in enumerate(self.layers):
+ hidden_states = decoder_layer(
+ hidden_states,
+ attention_mask=causal_mask_mapping[self.config.layers_block_type[i]],
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ position_embeddings=position_embeddings,
+ **kwargs,
+ )
+ hidden_states = self.norm(hidden_states)
+
+ return MoeModelOutputWithPast(
+ last_hidden_state=hidden_states,
+ past_key_values=past_key_values,
+ )
+
+ def _update_mamba_mask(self, attention_mask, past_key_values):
+ """
+ No need for zeroing states when
+ 1. Cached forward
+ 2. Attending to all inputs
+ """
+ mamba_mask = attention_mask
+ if (past_key_values is not None and past_key_values.has_previous_state()) or (
+ attention_mask is not None and torch.all(attention_mask == 1)
+ ):
+ mamba_mask = None
+ return mamba_mask
+
+
+class GraniteMoeHybridForCausalLM(GraniteMoeSharedForCausalLM):
+ _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
+
+ def __init__(self, config: GraniteMoeHybridConfig):
+ super().__init__(config)
+ self.model = GraniteMoeHybridModel(config)
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def forward(self, **super_kwargs):
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
+
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, GraniteMoeHybridForCausalLM
+
+ >>> model = GraniteMoeHybridForCausalLM.from_pretrained("ibm-granite/granite-4.0-h-tiny")
+ >>> tokenizer = AutoTokenizer.from_pretrained("ibm-granite/granite-4.0-h-tiny")
+
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
+
+ >>> # Generate
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
+ ```"""
+ return super().forward(**super_kwargs)
+
+
+__all__ = ["GraniteMoeHybridForCausalLM", "GraniteMoeHybridModel", "GraniteMoeHybridPreTrainedModel"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/helium/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/helium/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..73d0966e5c1c489944c4b539c0cc06384c985c87
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/helium/__init__.py
@@ -0,0 +1,27 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_helium import *
+ from .modeling_helium import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/helium/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/helium/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2d1ee373ea9f516743ce841fecf4c164c9e8aa2d
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/helium/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/helium/__pycache__/configuration_helium.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/helium/__pycache__/configuration_helium.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..90b9a91cb954d0e82e826d99628033a1a0961928
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/helium/__pycache__/configuration_helium.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/helium/__pycache__/modeling_helium.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/helium/__pycache__/modeling_helium.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ebe4b43f9f917f53f6dea64ae208e32f9026fd5f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/helium/__pycache__/modeling_helium.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/helium/__pycache__/modular_helium.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/helium/__pycache__/modular_helium.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0b2962b769b9c681c443ee1e9e066bb5600fb2c9
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/helium/__pycache__/modular_helium.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/helium/configuration_helium.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/helium/configuration_helium.py
new file mode 100644
index 0000000000000000000000000000000000000000..caa966b58a9dd4686762dddd9eeca9798bff4462
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/helium/configuration_helium.py
@@ -0,0 +1,80 @@
+# Copyright 2024 The Kyutai and HuggingFace Inc. teams. All rights reserved.
+#
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...modeling_rope_utils import RopeParameters
+from ...utils import auto_docstring
+
+
+@auto_docstring(checkpoint="kyutai/helium-1-preview")
+@strict
+class HeliumConfig(PreTrainedConfig):
+ r"""
+ Example:
+
+ ```python
+ >>> from transformers import HeliumModel, HeliumConfig
+ >>> # Initializing a Helium 2b style configuration
+ >>> configuration = HeliumConfig()
+ >>> # Initializing a model from the Helium 2b style configuration
+ >>> model = HeliumModel(configuration)
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "helium"
+ keys_to_ignore_at_inference = ["past_key_values"]
+ default_theta = 100000.0
+ base_model_tp_plan = {
+ "layers.*.self_attn.q_proj": "colwise",
+ "layers.*.self_attn.k_proj": "colwise",
+ "layers.*.self_attn.v_proj": "colwise",
+ "layers.*.self_attn.o_proj": "rowwise",
+ "layers.*.mlp.gate_proj": "colwise",
+ "layers.*.mlp.up_proj": "colwise",
+ "layers.*.mlp.down_proj": "rowwise",
+ }
+ base_model_pp_plan = {
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
+ "norm": (["hidden_states"], ["hidden_states"]),
+ }
+
+ vocab_size: int = 48000
+ hidden_size: int = 2560
+ intermediate_size: int = 7040
+ num_hidden_layers: int = 24
+ num_attention_heads: int = 20
+ num_key_value_heads: int = 20
+ head_dim: int = 128
+ hidden_act: str = "silu"
+ attention_dropout: float | int = 0.0
+ max_position_embeddings: int = 4096
+ initializer_range: float = 0.02
+ rms_norm_eps: float = 1e-8
+ use_cache: bool = True
+ tie_word_embeddings: bool = False
+ rope_parameters: RopeParameters | dict | None = None
+ pad_token_id: int | None = 3
+ eos_token_id: int | list[int] | None = 2
+ bos_token_id: int | None = 1
+ attention_bias: bool = False
+ mlp_bias: bool = False
+
+
+__all__ = ["HeliumConfig"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/helium/modeling_helium.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/helium/modeling_helium.py
new file mode 100644
index 0000000000000000000000000000000000000000..8283fcb19e28c5bbc2a9d90d26fa4bb3a8f42f2c
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/helium/modeling_helium.py
@@ -0,0 +1,511 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/helium/modular_helium.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_helium.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2024 The Kyutai and HuggingFace Inc. teams. All rights reserved.
+#
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import math
+from collections.abc import Callable
+from typing import Optional
+
+import torch
+import torch.nn as nn
+
+from ...activations import ACT2FN
+from ...cache_utils import Cache, DynamicCache
+from ...generation import GenerationMixin
+from ...integrations import use_kernelized_func
+from ...masking_utils import create_causal_mask
+from ...modeling_layers import (
+ GenericForSequenceClassification,
+ GenericForTokenClassification,
+ GradientCheckpointingLayer,
+)
+from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
+from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import TransformersKwargs, auto_docstring, can_return_tuple
+from ...utils.generic import maybe_autocast, merge_with_config_defaults
+from ...utils.output_capturing import capture_outputs
+from .configuration_helium import HeliumConfig
+
+
+class HeliumRMSNorm(nn.Module):
+ def __init__(self, hidden_size, eps=1e-6):
+ super().__init__()
+ self.weight = nn.Parameter(torch.ones(hidden_size))
+ self.variance_epsilon = eps
+
+ def forward(self, hidden_states):
+ input_dtype = hidden_states.dtype
+ hidden_states = hidden_states.to(torch.float32)
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
+ return (self.weight.to(torch.float32) * hidden_states).to(input_dtype)
+
+ def extra_repr(self):
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
+
+
+class HeliumRotaryEmbedding(nn.Module):
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
+
+ def __init__(self, config: HeliumConfig, device=None):
+ super().__init__()
+ self.max_seq_len_cached = config.max_position_embeddings
+ self.original_max_seq_len = config.max_position_embeddings
+
+ self.config = config
+
+ self.rope_type = self.config.rope_parameters["rope_type"]
+ rope_init_fn: Callable = self.compute_default_rope_parameters
+ if self.rope_type != "default":
+ rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
+ inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
+
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
+ self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
+
+ @staticmethod
+ def compute_default_rope_parameters(
+ config: HeliumConfig | None = None,
+ device: Optional["torch.device"] = None,
+ seq_len: int | None = None,
+ ) -> tuple["torch.Tensor", float]:
+ """
+ Computes the inverse frequencies according to the original RoPE implementation
+ Args:
+ config ([`~transformers.PreTrainedConfig`]):
+ The model configuration.
+ device (`torch.device`):
+ The device to use for initialization of the inverse frequencies.
+ seq_len (`int`, *optional*):
+ The current sequence length. Unused for this type of RoPE.
+ Returns:
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
+ """
+ base = config.rope_parameters["rope_theta"]
+ dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
+
+ attention_factor = 1.0 # Unused in this type of RoPE
+
+ # Compute the inverse frequencies
+ inv_freq = 1.0 / (
+ base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
+ )
+ return inv_freq, attention_factor
+
+ @torch.no_grad()
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
+ def forward(self, x, position_ids):
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
+ position_ids_expanded = position_ids[:, None, :].float()
+
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
+ with maybe_autocast(device_type=device_type, enabled=False): # Force float32
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
+ emb = torch.cat((freqs, freqs), dim=-1)
+ cos = emb.cos() * self.attention_scaling
+ sin = emb.sin() * self.attention_scaling
+
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
+
+
+class HeliumMLP(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.hidden_size = config.hidden_size
+ self.intermediate_size = config.intermediate_size
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
+ self.act_fn = ACT2FN[config.hidden_act]
+
+ def forward(self, x):
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
+ return down_proj
+
+
+def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
+ """
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
+ """
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
+ if n_rep == 1:
+ return hidden_states
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
+
+
+def eager_attention_forward(
+ module: nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: torch.Tensor | None,
+ scaling: float,
+ dropout: float = 0.0,
+ **kwargs: Unpack[TransformersKwargs],
+):
+ key_states = repeat_kv(key, module.num_key_value_groups)
+ value_states = repeat_kv(value, module.num_key_value_groups)
+
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
+ if attention_mask is not None:
+ attn_weights = attn_weights + attention_mask
+
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
+ attn_output = torch.matmul(attn_weights, value_states)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+
+ return attn_output, attn_weights
+
+
+def rotate_half(x):
+ """Rotates half the hidden dims of the input."""
+ x1 = x[..., 0::2]
+ x2 = x[..., 1::2]
+ return torch.stack((-x2, x1), dim=-1).flatten(-2)
+
+
+def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
+ """Applies Rotary Position Embedding to the query and key tensors.
+
+ Args:
+ q (`torch.Tensor`): The query tensor.
+ k (`torch.Tensor`): The key tensor.
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
+ Returns:
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
+ """
+ cos = cos.unsqueeze(unsqueeze_dim)
+ sin = sin.unsqueeze(unsqueeze_dim)
+
+ # Interleave them instead of usual shape
+ cos = cos[..., : cos.shape[-1] // 2].repeat_interleave(2, dim=-1)
+ sin = sin[..., : sin.shape[-1] // 2].repeat_interleave(2, dim=-1)
+
+ q_embed = (q * cos) + (rotate_half(q) * sin)
+ k_embed = (k * cos) + (rotate_half(k) * sin)
+
+ return q_embed, k_embed
+
+
+@use_kernelized_func(apply_rotary_pos_emb)
+class HeliumAttention(nn.Module):
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
+
+ def __init__(self, config: HeliumConfig, layer_idx: int | None = None):
+ super().__init__()
+ self.config = config
+ self.layer_idx = layer_idx
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
+ self.scaling = 1 / math.sqrt(self.head_dim)
+ self.attention_dropout = config.attention_dropout
+ self.is_causal = True
+
+ self.q_proj = nn.Linear(
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
+ )
+ self.k_proj = nn.Linear(
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
+ )
+ self.v_proj = nn.Linear(
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
+ )
+ self.o_proj = nn.Linear(config.hidden_size, config.hidden_size, bias=False)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
+ attention_mask: torch.Tensor | None = None,
+ past_key_values: Cache | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor, torch.Tensor]:
+ input_shape = hidden_states.shape[:-1]
+ hidden_shape = (*input_shape, -1, self.head_dim)
+
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+
+ cos, sin = position_embeddings
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
+
+ if past_key_values is not None:
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_states,
+ key_states,
+ value_states,
+ attention_mask,
+ dropout=0.0 if not self.training else self.attention_dropout,
+ scaling=self.scaling,
+ **kwargs,
+ )
+
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ attn_output = self.o_proj(attn_output)
+ return attn_output, attn_weights
+
+
+class HeliumDecoderLayer(GradientCheckpointingLayer):
+ def __init__(self, config: HeliumConfig, layer_idx: int | None = None):
+ super().__init__()
+ self.hidden_size = config.hidden_size
+
+ self.self_attn = HeliumAttention(config=config, layer_idx=layer_idx)
+
+ self.mlp = HeliumMLP(config)
+ self.input_layernorm = HeliumRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.post_attention_layernorm = HeliumRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ use_cache: bool | None = False,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.Tensor:
+ residual = hidden_states
+ hidden_states = self.input_layernorm(hidden_states)
+ # Self Attention
+ hidden_states, _ = self.self_attn(
+ hidden_states=hidden_states,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ position_embeddings=position_embeddings,
+ **kwargs,
+ )
+ hidden_states = residual + hidden_states
+
+ # Fully Connected
+ residual = hidden_states
+ hidden_states = self.post_attention_layernorm(hidden_states)
+ hidden_states = self.mlp(hidden_states)
+ hidden_states = residual + hidden_states
+ return hidden_states
+
+
+@auto_docstring
+class HeliumPreTrainedModel(PreTrainedModel):
+ config: HeliumConfig
+ base_model_prefix = "model"
+ supports_gradient_checkpointing = True
+ _no_split_modules = ["HeliumDecoderLayer"]
+ _skip_keys_device_placement = ["past_key_values"]
+ _supports_flash_attn = True
+ _supports_sdpa = True
+ _supports_flex_attn = True
+
+ _can_compile_fullgraph = True
+ _supports_attention_backend = True
+ _can_record_outputs = {
+ "hidden_states": HeliumDecoderLayer,
+ "attentions": HeliumAttention,
+ }
+
+
+@auto_docstring
+class HeliumModel(HeliumPreTrainedModel):
+ def __init__(self, config: HeliumConfig):
+ super().__init__(config)
+ self.padding_idx = config.pad_token_id
+ self.vocab_size = config.vocab_size
+
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
+ self.layers = nn.ModuleList(
+ [HeliumDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
+ )
+ self.norm = HeliumRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.rotary_emb = HeliumRotaryEmbedding(config=config)
+ self.gradient_checkpointing = False
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @merge_with_config_defaults
+ @capture_outputs
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ use_cache: bool | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> BaseModelOutputWithPast:
+ if (input_ids is None) ^ (inputs_embeds is not None):
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
+
+ if inputs_embeds is None:
+ inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)
+
+ if use_cache and past_key_values is None:
+ past_key_values = DynamicCache(config=self.config)
+
+ if position_ids is None:
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
+ position_ids = position_ids.unsqueeze(0)
+
+ causal_mask = create_causal_mask(
+ config=self.config,
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ position_ids=position_ids,
+ )
+
+ hidden_states = inputs_embeds
+ position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
+
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
+ hidden_states = decoder_layer(
+ hidden_states,
+ attention_mask=causal_mask,
+ position_embeddings=position_embeddings,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ **kwargs,
+ )
+
+ hidden_states = self.norm(hidden_states)
+ return BaseModelOutputWithPast(
+ last_hidden_state=hidden_states,
+ past_key_values=past_key_values,
+ )
+
+
+@auto_docstring
+class HeliumForCausalLM(HeliumPreTrainedModel, GenerationMixin):
+ _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
+ _tp_plan = {"lm_head": "colwise_gather_output"}
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
+
+ def __init__(self, config):
+ super().__init__(config)
+ self.model = HeliumModel(config)
+ self.vocab_size = config.vocab_size
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ use_cache: bool | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> CausalLMOutputWithPast:
+ r"""
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, HeliumForCausalLM
+
+ >>> model = HeliumForCausalLM.from_pretrained("google/helium-7b")
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/helium-7b")
+
+ >>> prompt = "What is your favorite condiment?"
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
+
+ >>> # Generate
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
+ "What is your favorite condiment?"
+ ```"""
+ outputs: BaseModelOutputWithPast = self.model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ **kwargs,
+ )
+
+ hidden_states = outputs.last_hidden_state
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
+
+ return CausalLMOutputWithPast(
+ loss=loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+class HeliumForSequenceClassification(GenericForSequenceClassification, HeliumPreTrainedModel):
+ pass
+
+
+class HeliumForTokenClassification(GenericForTokenClassification, HeliumPreTrainedModel):
+ pass
+
+
+__all__ = [
+ "HeliumPreTrainedModel",
+ "HeliumModel",
+ "HeliumForCausalLM",
+ "HeliumForSequenceClassification",
+ "HeliumForTokenClassification",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/helium/modular_helium.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/helium/modular_helium.py
new file mode 100644
index 0000000000000000000000000000000000000000..566cce5886dee58d756aeaa6078e17403b5352cd
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/helium/modular_helium.py
@@ -0,0 +1,144 @@
+# Copyright 2024 The Kyutai and HuggingFace Inc. teams. All rights reserved.
+#
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import math
+
+import torch
+import torch.nn as nn
+
+from ...utils import logging
+from ..gemma.modeling_gemma import GemmaForCausalLM, GemmaForSequenceClassification, GemmaForTokenClassification
+from ..granite.modeling_granite import GraniteAttention
+from ..llama.modeling_llama import LlamaDecoderLayer, LlamaMLP, LlamaModel, LlamaPreTrainedModel, LlamaRotaryEmbedding
+from .configuration_helium import HeliumConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+class HeliumRMSNorm(nn.Module):
+ def __init__(self, hidden_size, eps=1e-6):
+ super().__init__()
+ self.weight = nn.Parameter(torch.ones(hidden_size))
+ self.variance_epsilon = eps
+
+ def forward(self, hidden_states):
+ input_dtype = hidden_states.dtype
+ hidden_states = hidden_states.to(torch.float32)
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
+ return (self.weight.to(torch.float32) * hidden_states).to(input_dtype)
+
+ def extra_repr(self):
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
+
+
+class HeliumRotaryEmbedding(LlamaRotaryEmbedding):
+ pass
+
+
+class HeliumMLP(LlamaMLP):
+ pass
+
+
+def rotate_half(x):
+ """Rotates half the hidden dims of the input."""
+ x1 = x[..., 0::2]
+ x2 = x[..., 1::2]
+ return torch.stack((-x2, x1), dim=-1).flatten(-2)
+
+
+def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
+ """Applies Rotary Position Embedding to the query and key tensors.
+
+ Args:
+ q (`torch.Tensor`): The query tensor.
+ k (`torch.Tensor`): The key tensor.
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
+ Returns:
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
+ """
+ cos = cos.unsqueeze(unsqueeze_dim)
+ sin = sin.unsqueeze(unsqueeze_dim)
+
+ # Interleave them instead of usual shape
+ cos = cos[..., : cos.shape[-1] // 2].repeat_interleave(2, dim=-1)
+ sin = sin[..., : sin.shape[-1] // 2].repeat_interleave(2, dim=-1)
+
+ q_embed = (q * cos) + (rotate_half(q) * sin)
+ k_embed = (k * cos) + (rotate_half(k) * sin)
+
+ return q_embed, k_embed
+
+
+class HeliumAttention(GraniteAttention):
+ def __init__(self, config: HeliumConfig, layer_idx: int | None = None):
+ super().__init__(config, layer_idx)
+ self.o_proj = nn.Linear(config.hidden_size, config.hidden_size, bias=False)
+ self.scaling = 1 / math.sqrt(self.head_dim)
+
+
+class HeliumDecoderLayer(LlamaDecoderLayer):
+ def __init__(self, config: HeliumConfig, layer_idx: int | None = None):
+ super().__init__(config, layer_idx)
+
+ self.mlp = HeliumMLP(config)
+ self.input_layernorm = HeliumRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.post_attention_layernorm = HeliumRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+
+
+class HeliumPreTrainedModel(LlamaPreTrainedModel):
+ pass
+
+
+class HeliumModel(HeliumPreTrainedModel, LlamaModel):
+ def __init__(self, config: HeliumConfig):
+ super().__init__(config)
+ self.layers = nn.ModuleList(
+ [HeliumDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
+ )
+ self.norm = HeliumRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.gradient_checkpointing = False
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+
+class HeliumForCausalLM(GemmaForCausalLM):
+ pass
+
+
+class HeliumForSequenceClassification(GemmaForSequenceClassification):
+ pass
+
+
+class HeliumForTokenClassification(GemmaForTokenClassification):
+ pass
+
+
+__all__ = [
+ "HeliumPreTrainedModel",
+ "HeliumModel",
+ "HeliumForCausalLM",
+ "HeliumForSequenceClassification",
+ "HeliumForTokenClassification",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/hy_v3/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/hy_v3/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..16e08a09fb323e2a8697fc8056d90a3fc305a9b9
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/hy_v3/__init__.py
@@ -0,0 +1,27 @@
+# Copyright 2026 The HunYuan Team and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_hy_v3 import *
+ from .modeling_hy_v3 import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/hy_v3/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/hy_v3/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1227a7c5561ee667e07b9c0b44c1875197f049dd
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/hy_v3/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/hy_v3/__pycache__/configuration_hy_v3.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/hy_v3/__pycache__/configuration_hy_v3.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e1174247f1cc95adbc4b28cd9b21eafd02e876f6
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/hy_v3/__pycache__/configuration_hy_v3.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/hy_v3/__pycache__/modeling_hy_v3.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/hy_v3/__pycache__/modeling_hy_v3.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3f83c5f1db7772435b206909489d1c164c3fd081
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/hy_v3/__pycache__/modeling_hy_v3.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/hy_v3/__pycache__/modular_hy_v3.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/hy_v3/__pycache__/modular_hy_v3.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9b6ce500ac344ca8352ae37ce65a8c595e477d51
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/hy_v3/__pycache__/modular_hy_v3.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/hy_v3/configuration_hy_v3.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/hy_v3/configuration_hy_v3.py
new file mode 100644
index 0000000000000000000000000000000000000000..e2eee94b118af9e2ed7de2519da9ae0de50dcdf3
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/hy_v3/configuration_hy_v3.py
@@ -0,0 +1,114 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/hy_v3/modular_hy_v3.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_hy_v3.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2026 Tencent HunYuan Team and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...modeling_rope_utils import RopeParameters
+from ...utils import auto_docstring
+
+
+@auto_docstring(checkpoint="tencent/Hy3-preview")
+@strict
+class HYV3Config(PreTrainedConfig):
+ r"""
+ router_scaling_factor (*float*):
+ Scaling factor on the top-k weighs of the MoE expert selection.
+ enable_moe_fp32_combine (*bool*):
+ Whether to add the shared experts to the final MoE result in fp32 or the base existing dtype of the model.
+ mlp_layer_types (`list`, *optional*):
+ MLP (Moe vs Dense) pattern for each layer.
+
+ Example:
+ ```python
+ >>> from transformers import HYV3Config, HYV3Model
+
+ >>> config = HYV3Config()
+ >>> model = HYV3Model(config)
+ ```
+ """
+
+ model_type = "hy_v3"
+ default_theta = 11_158_840.0
+ keys_to_ignore_at_inference = ["past_key_values"]
+ attribute_map = {
+ "num_local_experts": "num_experts",
+ }
+ base_model_tp_plan = {
+ "layers.*.self_attn.q_proj": "colwise",
+ "layers.*.self_attn.k_proj": "colwise",
+ "layers.*.self_attn.v_proj": "colwise",
+ "layers.*.self_attn.q_norm": "replicated_with_grad_allreduce",
+ "layers.*.self_attn.k_norm": "replicated_with_grad_allreduce",
+ "layers.*.self_attn.o_proj": "rowwise",
+ "layers.*.mlp.experts.gate_up_proj": "packed_colwise",
+ "layers.*.mlp.experts.down_proj": "rowwise",
+ "layers.*.mlp.experts": "moe_tp_experts",
+ "layers.*.mlp.shared_experts.gate_proj": "colwise",
+ "layers.*.mlp.shared_experts.up_proj": "colwise",
+ "layers.*.mlp.shared_experts.down_proj": "rowwise",
+ "layers.*.mlp.gate_proj": "colwise",
+ "layers.*.mlp.up_proj": "colwise",
+ "layers.*.mlp.down_proj": "rowwise",
+ }
+ base_model_pp_plan = {
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
+ "norm": (["hidden_states"], ["hidden_states"]),
+ }
+
+ vocab_size: int = 120832
+ hidden_size: int = 4096
+ intermediate_size: int = 13312
+ num_hidden_layers: int = 80
+ num_attention_heads: int = 64
+ num_key_value_heads: int = 8
+ head_dim: int = 128
+ hidden_act: str = "silu"
+ max_position_embeddings: int = 131072
+ initializer_range: float = 0.006
+ rms_norm_eps: float = 1e-5
+ use_cache: bool = True
+ pad_token_id: int | None = None
+ bos_token_id: int | None = None
+ eos_token_id: int | list[int] | None = None
+ tie_word_embeddings: bool = False
+ attention_bias: bool = False
+ attention_dropout: float = 0.0
+ mlp_bias: bool = False
+ num_experts: int | None = 192
+ num_experts_per_tok: int | None = 8
+ num_shared_experts: int | None = 1
+ moe_intermediate_size: int = 1536
+ router_scaling_factor: float = 2.826
+ enable_moe_fp32_combine: bool = True
+ mlp_layer_types: list[str] | None = None
+ output_router_logits: bool = False
+ rope_parameters: RopeParameters | dict | None = None
+
+ def __post_init__(self, **kwargs):
+ if self.mlp_layer_types is None:
+ self.mlp_layer_types = ["dense"] * (1 if self.num_hidden_layers > 0 else 0) + ["sparse"] * max(
+ self.num_hidden_layers - 1, 0
+ )
+
+ super().__post_init__(**kwargs)
+
+
+__all__ = ["HYV3Config"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/hy_v3/modeling_hy_v3.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/hy_v3/modeling_hy_v3.py
new file mode 100644
index 0000000000000000000000000000000000000000..f2d64736b4f0a1c6ccb61939dd9e9b4cd8170aa7
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/hy_v3/modeling_hy_v3.py
@@ -0,0 +1,608 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/hy_v3/modular_hy_v3.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_hy_v3.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2026 Tencent HunYuan Team and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from collections.abc import Callable
+from typing import Optional
+
+import torch
+import torch.nn.functional as F
+from torch import nn
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...cache_utils import Cache, DynamicCache
+from ...generation import GenerationMixin
+from ...integrations import (
+ use_experts_implementation,
+ use_kernel_forward_from_hub,
+ use_kernel_func_from_hub,
+ use_kernelized_func,
+)
+from ...masking_utils import create_causal_mask
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import MoeCausalLMOutputWithPast, MoeModelOutputWithPast
+from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import TransformersKwargs, auto_docstring, can_return_tuple
+from ...utils.generic import maybe_autocast, merge_with_config_defaults
+from ...utils.output_capturing import OutputRecorder, capture_outputs
+from .configuration_hy_v3 import HYV3Config
+
+
+@use_kernel_forward_from_hub("RMSNorm")
+class HYV3RMSNorm(nn.Module):
+ def __init__(self, hidden_size, eps: float = 1e-6) -> None:
+ """
+ HYV3RMSNorm is equivalent to T5LayerNorm
+ """
+ super().__init__()
+ self.weight = nn.Parameter(torch.ones(hidden_size))
+ self.variance_epsilon = eps
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ input_dtype = hidden_states.dtype
+ hidden_states = hidden_states.to(torch.float32)
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
+ return self.weight * hidden_states.to(input_dtype)
+
+ def extra_repr(self):
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
+
+
+class HYV3RotaryEmbedding(nn.Module):
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
+
+ def __init__(self, config: HYV3Config, device=None):
+ super().__init__()
+ self.max_seq_len_cached = config.max_position_embeddings
+ self.original_max_seq_len = config.max_position_embeddings
+
+ self.config = config
+
+ self.rope_type = self.config.rope_parameters["rope_type"]
+ rope_init_fn: Callable = self.compute_default_rope_parameters
+ if self.rope_type != "default":
+ rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
+ inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
+
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
+ self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
+
+ @staticmethod
+ def compute_default_rope_parameters(
+ config: HYV3Config | None = None,
+ device: Optional["torch.device"] = None,
+ seq_len: int | None = None,
+ ) -> tuple["torch.Tensor", float]:
+ """
+ Computes the inverse frequencies according to the original RoPE implementation
+ Args:
+ config ([`~transformers.PreTrainedConfig`]):
+ The model configuration.
+ device (`torch.device`):
+ The device to use for initialization of the inverse frequencies.
+ seq_len (`int`, *optional*):
+ The current sequence length. Unused for this type of RoPE.
+ Returns:
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
+ """
+ base = config.rope_parameters["rope_theta"]
+ dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
+
+ attention_factor = 1.0 # Unused in this type of RoPE
+
+ # Compute the inverse frequencies
+ inv_freq = 1.0 / (
+ base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
+ )
+ return inv_freq, attention_factor
+
+ @torch.no_grad()
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
+ def forward(self, x, position_ids):
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
+ position_ids_expanded = position_ids[:, None, :].float()
+
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
+ with maybe_autocast(device_type=device_type, enabled=False): # Force float32
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
+ emb = torch.cat((freqs, freqs), dim=-1)
+ cos = emb.cos() * self.attention_scaling
+ sin = emb.sin() * self.attention_scaling
+
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
+
+
+class HYV3MLP(nn.Module):
+ def __init__(self, config: HYV3Config, intermediate_size: int | None = None):
+ super().__init__()
+ self.config = config
+ self.hidden_size = config.hidden_size
+ self.intermediate_size = intermediate_size or config.intermediate_size
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
+ self.act_fn = ACT2FN[config.hidden_act]
+
+ def forward(self, x):
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
+ return down_proj
+
+
+def rotate_half(x):
+ """Rotates half the hidden dims of the input."""
+ x1 = x[..., : x.shape[-1] // 2]
+ x2 = x[..., x.shape[-1] // 2 :]
+ return torch.cat((-x2, x1), dim=-1)
+
+
+@use_kernel_func_from_hub("rotary_pos_emb")
+def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
+ """Applies Rotary Position Embedding to the query and key tensors.
+
+ Args:
+ q (`torch.Tensor`): The query tensor.
+ k (`torch.Tensor`): The key tensor.
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
+ Returns:
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
+ """
+ cos = cos.unsqueeze(unsqueeze_dim)
+ sin = sin.unsqueeze(unsqueeze_dim)
+ q_embed = (q * cos) + (rotate_half(q) * sin)
+ k_embed = (k * cos) + (rotate_half(k) * sin)
+ return q_embed, k_embed
+
+
+def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
+ """
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
+ """
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
+ if n_rep == 1:
+ return hidden_states
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
+
+
+def eager_attention_forward(
+ module: nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: torch.Tensor | None,
+ scaling: float,
+ dropout: float = 0.0,
+ **kwargs: Unpack[TransformersKwargs],
+):
+ key_states = repeat_kv(key, module.num_key_value_groups)
+ value_states = repeat_kv(value, module.num_key_value_groups)
+
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
+ if attention_mask is not None:
+ attn_weights = attn_weights + attention_mask
+
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
+ attn_output = torch.matmul(attn_weights, value_states)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+
+ return attn_output, attn_weights
+
+
+@use_kernelized_func(apply_rotary_pos_emb)
+class HYV3Attention(nn.Module):
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
+
+ def __init__(self, config: HYV3Config, layer_idx: int | None = None):
+ super().__init__()
+ self.config = config
+ self.layer_idx = layer_idx
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
+ self.scaling = self.head_dim**-0.5
+ self.attention_dropout = config.attention_dropout
+ self.is_causal = True
+
+ self.q_proj = nn.Linear(
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
+ )
+ self.k_proj = nn.Linear(
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
+ )
+ self.v_proj = nn.Linear(
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
+ )
+ self.o_proj = nn.Linear(
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
+ )
+ self.q_norm = HYV3RMSNorm(self.head_dim, config.rms_norm_eps)
+ self.k_norm = HYV3RMSNorm(self.head_dim, config.rms_norm_eps)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
+ attention_mask: torch.Tensor | None,
+ past_key_values: Cache | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor, torch.Tensor]:
+ input_shape = hidden_states.shape[:-1]
+ hidden_shape = (*input_shape, -1, self.head_dim)
+
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+ query_states = self.q_norm(query_states)
+ key_states = self.k_norm(key_states)
+
+ cos, sin = position_embeddings
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
+
+ if past_key_values is not None:
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_states,
+ key_states,
+ value_states,
+ attention_mask,
+ dropout=0.0 if not self.training else self.attention_dropout,
+ scaling=self.scaling,
+ **kwargs,
+ )
+
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ attn_output = self.o_proj(attn_output)
+ return attn_output, attn_weights
+
+
+class HYV3TopKRouter(nn.Module):
+ def __init__(self, config: HYV3Config):
+ super().__init__()
+ self.top_k = config.num_experts_per_tok
+ self.num_experts = config.num_local_experts
+ self.hidden_dim = config.hidden_size
+ self.weight = nn.Parameter(torch.empty(self.num_experts, self.hidden_dim))
+ self.router_scaling_factor = config.router_scaling_factor
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ e_score_correction_bias: torch.Tensor,
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ hidden_states = hidden_states.reshape(-1, self.hidden_dim)
+ router_logits = F.linear(hidden_states.float(), self.weight.float())
+ routing_weights = torch.sigmoid(router_logits)
+
+ scores_for_choice = routing_weights + e_score_correction_bias
+ _, top_k_index = torch.topk(scores_for_choice, self.top_k, dim=-1, sorted=False)
+ top_k_weights = routing_weights.gather(1, top_k_index)
+
+ top_k_weights = top_k_weights / (top_k_weights.sum(dim=-1, keepdim=True) + 1e-20)
+ # Key difference: extra scaling factor
+ top_k_weights = top_k_weights * self.router_scaling_factor
+
+ return router_logits, top_k_weights, top_k_index
+
+
+@use_experts_implementation
+class HYV3Experts(nn.Module):
+ """Collection of expert weights stored as 3D tensors."""
+
+ def __init__(self, config):
+ super().__init__()
+ self.num_experts = config.num_experts
+ self.hidden_dim = config.hidden_size
+ self.intermediate_dim = config.moe_intermediate_size
+ self.gate_up_proj = nn.Parameter(torch.empty(self.num_experts, 2 * self.intermediate_dim, self.hidden_dim))
+ self.down_proj = nn.Parameter(torch.empty(self.num_experts, self.hidden_dim, self.intermediate_dim))
+ self.act_fn = ACT2FN[config.hidden_act]
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ top_k_index: torch.Tensor,
+ top_k_weights: torch.Tensor,
+ ) -> torch.Tensor:
+ final_hidden_states = torch.zeros_like(hidden_states)
+ with torch.no_grad():
+ expert_mask = torch.nn.functional.one_hot(top_k_index, num_classes=self.num_experts)
+ expert_mask = expert_mask.permute(2, 1, 0)
+ expert_hit = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero()
+
+ for expert_idx in expert_hit:
+ expert_idx = expert_idx[0]
+ if expert_idx == self.num_experts:
+ continue
+ top_k_pos, token_idx = torch.where(expert_mask[expert_idx])
+ current_state = hidden_states[token_idx]
+ gate, up = nn.functional.linear(current_state, self.gate_up_proj[expert_idx]).chunk(2, dim=-1)
+ current_hidden_states = self.act_fn(gate) * up
+ current_hidden_states = nn.functional.linear(current_hidden_states, self.down_proj[expert_idx])
+ current_hidden_states = current_hidden_states * top_k_weights[token_idx, top_k_pos, None]
+ final_hidden_states.index_add_(0, token_idx, current_hidden_states.to(final_hidden_states.dtype))
+
+ return final_hidden_states
+
+
+class HYV3MoE(nn.Module):
+ def __init__(self, config: HYV3Config):
+ super().__init__()
+ self.top_k = config.num_experts_per_tok
+ self.gate = HYV3TopKRouter(config)
+ self.experts = HYV3Experts(config)
+ self.register_buffer("e_score_correction_bias", torch.zeros(config.num_local_experts))
+ self.enable_moe_fp32_combine = config.enable_moe_fp32_combine
+ shared_intermediate = config.moe_intermediate_size * config.num_shared_experts
+ self.shared_experts = HYV3MLP(config, intermediate_size=shared_intermediate)
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ batch_size, seq_len, hidden_dim = hidden_states.shape
+ hidden_states = hidden_states.view(-1, hidden_dim)
+
+ _, top_k_weights, top_k_index = self.gate(hidden_states, self.e_score_correction_bias)
+ routed_output = self.experts(hidden_states, top_k_index, top_k_weights)
+
+ # Key difference: optional float casting on combing shared experts
+ if self.enable_moe_fp32_combine:
+ hidden_states = (routed_output.float() + self.shared_experts(hidden_states).float()).to(
+ hidden_states.dtype
+ )
+ else:
+ hidden_states = routed_output + self.shared_experts(hidden_states)
+
+ return hidden_states.reshape(batch_size, seq_len, hidden_dim)
+
+
+class HYV3DecoderLayer(GradientCheckpointingLayer):
+ def __init__(self, config: HYV3Config, layer_idx: int):
+ super().__init__()
+ self.hidden_size = config.hidden_size
+ self.self_attn = HYV3Attention(config=config, layer_idx=layer_idx)
+ self.mlp = HYV3MoE(config) if config.mlp_layer_types[layer_idx] == "sparse" else HYV3MLP(config)
+ self.input_layernorm = HYV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.post_attention_layernorm = HYV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ use_cache: bool | None = False,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.Tensor:
+ residual = hidden_states
+ hidden_states = self.input_layernorm(hidden_states)
+ # Self Attention
+ hidden_states, _ = self.self_attn(
+ hidden_states=hidden_states,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ position_embeddings=position_embeddings,
+ **kwargs,
+ )
+ hidden_states = residual + hidden_states
+
+ # Fully Connected
+ residual = hidden_states
+ hidden_states = self.post_attention_layernorm(hidden_states)
+ hidden_states = self.mlp(hidden_states)
+ hidden_states = residual + hidden_states
+ return hidden_states
+
+
+@auto_docstring
+class HYV3PreTrainedModel(PreTrainedModel):
+ config: HYV3Config
+ base_model_prefix = "model"
+ supports_gradient_checkpointing = True
+ _no_split_modules = ["HYV3DecoderLayer"]
+ _skip_keys_device_placement = ["past_key_values"]
+ _supports_flash_attn = True
+ _supports_sdpa = True
+ _supports_flex_attn = True
+
+ _can_compile_fullgraph = True
+ _supports_attention_backend = True
+ _can_record_outputs = {
+ "router_logits": OutputRecorder(HYV3TopKRouter, index=0),
+ "hidden_states": HYV3DecoderLayer,
+ "attentions": HYV3Attention,
+ }
+ # Not supporting multi-token prediction (MTP) atm
+ _keys_to_ignore_on_load_unexpected = [r"model\.layers\.80.*"]
+ _keep_in_fp32_modules_strict = ["e_score_correction_bias"]
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ super()._init_weights(module)
+ std = self.config.initializer_range
+ if isinstance(module, HYV3TopKRouter):
+ init.normal_(module.weight, mean=0.0, std=std)
+ elif isinstance(module, HYV3Experts):
+ init.normal_(module.gate_up_proj, mean=0.0, std=std)
+ init.normal_(module.down_proj, mean=0.0, std=std)
+ elif isinstance(module, HYV3MoE):
+ init.zeros_(module.e_score_correction_bias)
+
+
+@auto_docstring
+class HYV3Model(HYV3PreTrainedModel):
+ def __init__(self, config: HYV3Config):
+ super().__init__(config)
+ self.padding_idx = config.pad_token_id
+ self.vocab_size = config.vocab_size
+
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
+ self.layers = nn.ModuleList(
+ [HYV3DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
+ )
+ self.norm = HYV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.rotary_emb = HYV3RotaryEmbedding(config=config)
+ self.gradient_checkpointing = False
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @merge_with_config_defaults
+ @capture_outputs
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ use_cache: bool | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> MoeModelOutputWithPast:
+ if (input_ids is None) ^ (inputs_embeds is not None):
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
+
+ if use_cache and past_key_values is None:
+ past_key_values = DynamicCache(config=self.config)
+
+ if inputs_embeds is None:
+ inputs_embeds = self.embed_tokens(input_ids)
+
+ if position_ids is None:
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
+ position_ids = position_ids.unsqueeze(0)
+
+ # No sliding window opposed to mixtral
+ causal_mask = create_causal_mask(
+ config=self.config,
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ position_ids=position_ids,
+ )
+
+ hidden_states = inputs_embeds
+ position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
+
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
+ hidden_states = decoder_layer(
+ hidden_states,
+ attention_mask=causal_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ position_embeddings=position_embeddings,
+ **kwargs,
+ )
+
+ hidden_states = self.norm(hidden_states)
+
+ return MoeModelOutputWithPast( # only diff with Mistral is the output type, we need MoE
+ last_hidden_state=hidden_states,
+ past_key_values=past_key_values,
+ )
+
+
+@auto_docstring
+class HYV3ForCausalLM(HYV3PreTrainedModel, GenerationMixin):
+ _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
+ _tp_plan = {"lm_head": "colwise_gather_output"}
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
+
+ def __init__(self, config: HYV3Config):
+ super().__init__(config)
+ self.model = HYV3Model(config)
+ self.vocab_size = config.vocab_size
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ use_cache: bool | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> MoeCausalLMOutputWithPast:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
+ """
+ outputs: MoeModelOutputWithPast = self.model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ **kwargs,
+ )
+
+ hidden_states = outputs.last_hidden_state
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
+
+ return MoeCausalLMOutputWithPast(
+ loss=loss,
+ aux_loss=None, # Not used in this model
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ router_logits=outputs.router_logits,
+ )
+
+
+__all__ = ["HYV3ForCausalLM", "HYV3Model", "HYV3PreTrainedModel"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/hy_v3/modular_hy_v3.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/hy_v3/modular_hy_v3.py
new file mode 100644
index 0000000000000000000000000000000000000000..fa0931435197d40abe481061f85684733199b428
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/hy_v3/modular_hy_v3.py
@@ -0,0 +1,316 @@
+# Copyright 2026 Tencent HunYuan Team and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch HYV3 model."""
+
+import torch
+import torch.nn.functional as F
+from huggingface_hub.dataclasses import strict
+from torch import nn
+
+from ... import initialization as init
+from ...cache_utils import Cache
+from ...configuration_utils import PreTrainedConfig
+from ...modeling_outputs import MoeCausalLMOutputWithPast, MoeModelOutputWithPast
+from ...modeling_rope_utils import RopeParameters
+from ...modeling_utils import PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import (
+ TransformersKwargs,
+ auto_docstring,
+ can_return_tuple,
+ logging,
+)
+from ...utils.output_capturing import OutputRecorder
+from ..apertus.modeling_apertus import ApertusAttention
+from ..deepseek_v3.modeling_deepseek_v3 import DeepseekV3DecoderLayer
+from ..llama.modeling_llama import (
+ LlamaForCausalLM,
+ LlamaMLP,
+ LlamaPreTrainedModel,
+ LlamaRMSNorm,
+ LlamaRotaryEmbedding,
+)
+from ..minimax_m2.modeling_minimax_m2 import MiniMaxM2Model, MiniMaxM2SparseMoeBlock
+from ..mixtral.modeling_mixtral import MixtralTopKRouter
+from ..qwen3_moe.modeling_qwen3_moe import Qwen3MoeExperts
+
+
+logger = logging.get_logger(__name__)
+
+
+@auto_docstring(checkpoint="tencent/Hy3-preview")
+@strict
+class HYV3Config(PreTrainedConfig):
+ r"""
+ router_scaling_factor (*float*):
+ Scaling factor on the top-k weighs of the MoE expert selection.
+ enable_moe_fp32_combine (*bool*):
+ Whether to add the shared experts to the final MoE result in fp32 or the base existing dtype of the model.
+ mlp_layer_types (`list`, *optional*):
+ MLP (Moe vs Dense) pattern for each layer.
+
+ Example:
+ ```python
+ >>> from transformers import HYV3Config, HYV3Model
+
+ >>> config = HYV3Config()
+ >>> model = HYV3Model(config)
+ ```
+ """
+
+ model_type = "hy_v3"
+ default_theta = 11_158_840.0
+ keys_to_ignore_at_inference = ["past_key_values"]
+ attribute_map = {
+ "num_local_experts": "num_experts",
+ }
+ base_model_tp_plan = {
+ "layers.*.self_attn.q_proj": "colwise",
+ "layers.*.self_attn.k_proj": "colwise",
+ "layers.*.self_attn.v_proj": "colwise",
+ "layers.*.self_attn.q_norm": "replicated_with_grad_allreduce",
+ "layers.*.self_attn.k_norm": "replicated_with_grad_allreduce",
+ "layers.*.self_attn.o_proj": "rowwise",
+ "layers.*.mlp.experts.gate_up_proj": "packed_colwise",
+ "layers.*.mlp.experts.down_proj": "rowwise",
+ "layers.*.mlp.experts": "moe_tp_experts",
+ "layers.*.mlp.shared_experts.gate_proj": "colwise",
+ "layers.*.mlp.shared_experts.up_proj": "colwise",
+ "layers.*.mlp.shared_experts.down_proj": "rowwise",
+ "layers.*.mlp.gate_proj": "colwise",
+ "layers.*.mlp.up_proj": "colwise",
+ "layers.*.mlp.down_proj": "rowwise",
+ }
+ base_model_pp_plan = {
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
+ "norm": (["hidden_states"], ["hidden_states"]),
+ }
+
+ vocab_size: int = 120832
+ hidden_size: int = 4096
+ intermediate_size: int = 13312
+ num_hidden_layers: int = 80
+ num_attention_heads: int = 64
+ num_key_value_heads: int = 8
+ head_dim: int = 128
+ hidden_act: str = "silu"
+ max_position_embeddings: int = 131072
+ initializer_range: float = 0.006
+ rms_norm_eps: float = 1e-5
+ use_cache: bool = True
+ pad_token_id: int | None = None
+ bos_token_id: int | None = None
+ eos_token_id: int | list[int] | None = None
+ tie_word_embeddings: bool = False
+ attention_bias: bool = False
+ attention_dropout: float = 0.0
+ mlp_bias: bool = False
+ num_experts: int | None = 192
+ num_experts_per_tok: int | None = 8
+ num_shared_experts: int | None = 1
+ moe_intermediate_size: int = 1536
+ router_scaling_factor: float = 2.826
+ enable_moe_fp32_combine: bool = True
+ mlp_layer_types: list[str] | None = None
+ output_router_logits: bool = False
+ rope_parameters: RopeParameters | dict | None = None
+
+ def __post_init__(self, **kwargs):
+ if self.mlp_layer_types is None:
+ self.mlp_layer_types = ["dense"] * (1 if self.num_hidden_layers > 0 else 0) + ["sparse"] * max(
+ self.num_hidden_layers - 1, 0
+ )
+
+ super().__post_init__(**kwargs)
+
+
+class HYV3RMSNorm(LlamaRMSNorm):
+ pass
+
+
+class HYV3RotaryEmbedding(LlamaRotaryEmbedding):
+ pass
+
+
+class HYV3MLP(LlamaMLP):
+ def __init__(self, config: HYV3Config, intermediate_size: int | None = None):
+ super().__init__(config)
+ self.intermediate_size = intermediate_size or config.intermediate_size
+
+
+class HYV3Attention(ApertusAttention):
+ pass
+
+
+class HYV3TopKRouter(MixtralTopKRouter):
+ def __init__(self, config: HYV3Config):
+ super().__init__(config)
+ self.router_scaling_factor = config.router_scaling_factor
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ e_score_correction_bias: torch.Tensor,
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ hidden_states = hidden_states.reshape(-1, self.hidden_dim)
+ router_logits = F.linear(hidden_states.float(), self.weight.float())
+ routing_weights = torch.sigmoid(router_logits)
+
+ scores_for_choice = routing_weights + e_score_correction_bias
+ _, top_k_index = torch.topk(scores_for_choice, self.top_k, dim=-1, sorted=False)
+ top_k_weights = routing_weights.gather(1, top_k_index)
+
+ top_k_weights = top_k_weights / (top_k_weights.sum(dim=-1, keepdim=True) + 1e-20)
+ # Key difference: extra scaling factor
+ top_k_weights = top_k_weights * self.router_scaling_factor
+
+ return router_logits, top_k_weights, top_k_index
+
+
+class HYV3Experts(Qwen3MoeExperts):
+ pass
+
+
+class HYV3MoE(MiniMaxM2SparseMoeBlock):
+ def __init__(self, config: HYV3Config):
+ super().__init__(config)
+ del self.jitter_noise
+ self.enable_moe_fp32_combine = config.enable_moe_fp32_combine
+ self.gate = HYV3TopKRouter(config)
+ self.experts = HYV3Experts(config)
+ shared_intermediate = config.moe_intermediate_size * config.num_shared_experts
+ self.shared_experts = HYV3MLP(config, intermediate_size=shared_intermediate)
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ batch_size, seq_len, hidden_dim = hidden_states.shape
+ hidden_states = hidden_states.view(-1, hidden_dim)
+
+ _, top_k_weights, top_k_index = self.gate(hidden_states, self.e_score_correction_bias)
+ routed_output = self.experts(hidden_states, top_k_index, top_k_weights)
+
+ # Key difference: optional float casting on combing shared experts
+ if self.enable_moe_fp32_combine:
+ hidden_states = (routed_output.float() + self.shared_experts(hidden_states).float()).to(
+ hidden_states.dtype
+ )
+ else:
+ hidden_states = routed_output + self.shared_experts(hidden_states)
+
+ return hidden_states.reshape(batch_size, seq_len, hidden_dim)
+
+
+class HYV3DecoderLayer(DeepseekV3DecoderLayer):
+ def __init__(self, config: HYV3Config, layer_idx: int):
+ nn.Module.__init__(self)
+ self.hidden_size = config.hidden_size
+ self.self_attn = HYV3Attention(config=config, layer_idx=layer_idx)
+ self.mlp = HYV3MoE(config) if config.mlp_layer_types[layer_idx] == "sparse" else HYV3MLP(config)
+ self.input_layernorm = HYV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.post_attention_layernorm = HYV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+
+
+class HYV3PreTrainedModel(LlamaPreTrainedModel):
+ # Not supporting multi-token prediction (MTP) atm
+ _keys_to_ignore_on_load_unexpected = [r"model\.layers\.80.*"]
+ _keep_in_fp32_modules_strict = ["e_score_correction_bias"]
+ _can_record_outputs = {
+ "router_logits": OutputRecorder(HYV3TopKRouter, index=0),
+ "hidden_states": HYV3DecoderLayer,
+ "attentions": HYV3Attention,
+ }
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ PreTrainedModel._init_weights(self, module)
+ std = self.config.initializer_range
+ if isinstance(module, HYV3TopKRouter):
+ init.normal_(module.weight, mean=0.0, std=std)
+ elif isinstance(module, HYV3Experts):
+ init.normal_(module.gate_up_proj, mean=0.0, std=std)
+ init.normal_(module.down_proj, mean=0.0, std=std)
+ elif isinstance(module, HYV3MoE):
+ init.zeros_(module.e_score_correction_bias)
+
+
+class HYV3Model(MiniMaxM2Model):
+ def __init__(self, config: HYV3Config):
+ super().__init__(config)
+ self.layers = nn.ModuleList(
+ [HYV3DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
+ )
+ self.norm = HYV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.rotary_emb = HYV3RotaryEmbedding(config=config)
+
+
+class HYV3ForCausalLM(LlamaForCausalLM):
+ def __init__(self, config: HYV3Config):
+ super().__init__(config)
+ self.model = HYV3Model(config)
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ use_cache: bool | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> MoeCausalLMOutputWithPast:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
+ """
+ outputs: MoeModelOutputWithPast = self.model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ **kwargs,
+ )
+
+ hidden_states = outputs.last_hidden_state
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
+
+ return MoeCausalLMOutputWithPast(
+ loss=loss,
+ aux_loss=None, # Not used in this model
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ router_logits=outputs.router_logits,
+ )
+
+
+__all__ = [
+ "HYV3Config",
+ "HYV3ForCausalLM",
+ "HYV3Model",
+ "HYV3PreTrainedModel",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/informer/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/informer/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c6307cd4e5254a7ad5b75efd17ae6d344034671a
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/informer/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/informer/__pycache__/configuration_informer.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/informer/__pycache__/configuration_informer.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..94933c1cdf598948e77cc4b8afe92ce105f3ab5d
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/informer/__pycache__/configuration_informer.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/informer/__pycache__/modeling_informer.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/informer/__pycache__/modeling_informer.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..530f84c24e6b4ccf0812b1a718eca14ad41daf2f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/informer/__pycache__/modeling_informer.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/informer/__pycache__/modular_informer.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/informer/__pycache__/modular_informer.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bddf93397b13dff81871dd1540aa9d4114780854
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/informer/__pycache__/modular_informer.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/instructblip/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/instructblip/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..ed2bd053d2c8b9fdaec4211b2b74e964bb88a5e3
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/instructblip/__init__.py
@@ -0,0 +1,28 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_instructblip import *
+ from .modeling_instructblip import *
+ from .processing_instructblip import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/instructblip/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/instructblip/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..035be403959eb4213d934fd8b9115ea588841ab1
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/instructblip/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/instructblip/__pycache__/configuration_instructblip.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/instructblip/__pycache__/configuration_instructblip.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fc199e5c68d5ba94d44530eebebc8ba678e2cd8b
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/instructblip/__pycache__/configuration_instructblip.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/instructblip/__pycache__/modeling_instructblip.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/instructblip/__pycache__/modeling_instructblip.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3b0f14ae7b308541956cb3ebb0a6a01842df81d1
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/instructblip/__pycache__/modeling_instructblip.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/instructblip/__pycache__/processing_instructblip.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/instructblip/__pycache__/processing_instructblip.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ec9ab65cc97575ba01457e63368ab717ee6ac1db
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/instructblip/__pycache__/processing_instructblip.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/instructblip/configuration_instructblip.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/instructblip/configuration_instructblip.py
new file mode 100644
index 0000000000000000000000000000000000000000..07fe02fb613b9f439bf95933af4166dfad7d95c4
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/instructblip/configuration_instructblip.py
@@ -0,0 +1,186 @@
+# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""InstructBLIP model configuration"""
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
+from ...utils import auto_docstring, logging
+from ..auto import CONFIG_MAPPING, AutoConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+@auto_docstring(checkpoint="Salesforce/instructblip-flan-t5-xl")
+@strict
+class InstructBlipVisionConfig(PreTrainedConfig):
+ r"""
+ Example:
+
+ ```python
+ >>> from transformers import InstructBlipVisionConfig, InstructBlipVisionModel
+
+ >>> # Initializing a InstructBlipVisionConfig with Salesforce/instructblip-flan-t5-xl style configuration
+ >>> configuration = InstructBlipVisionConfig()
+
+ >>> # Initializing a InstructBlipVisionModel (with random weights) from the Salesforce/instructblip-flan-t5-xl style configuration
+ >>> model = InstructBlipVisionModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "instructblip_vision_model"
+ base_config_key = "vision_config"
+
+ hidden_size: int = 1408
+ intermediate_size: int = 6144
+ num_hidden_layers: int = 39
+ num_attention_heads: int = 16
+ image_size: int | list[int] | tuple[int, int] = 224
+ patch_size: int | list[int] | tuple[int, int] = 14
+ hidden_act: str = "gelu"
+ layer_norm_eps: float = 1e-6
+ attention_dropout: float | int = 0.0
+ initializer_range: float = 1e-10
+ qkv_bias: bool = True
+
+
+@auto_docstring(checkpoint="Salesforce/instructblip-flan-t5-xl")
+@strict
+class InstructBlipQFormerConfig(PreTrainedConfig):
+ r"""
+ cross_attention_frequency (`int`, *optional*, defaults to 2):
+ The frequency of adding cross-attention to the Transformer layers.
+ encoder_hidden_size (`int`, *optional*, defaults to 1408):
+ The hidden size of the hidden states for cross-attention.
+
+ Examples:
+
+ ```python
+ >>> from transformers import InstructBlipQFormerConfig, InstructBlipQFormerModel
+
+ >>> # Initializing a InstructBLIP Salesforce/instructblip-flan-t5-xl style configuration
+ >>> configuration = InstructBlipQFormerConfig()
+
+ >>> # Initializing a model (with random weights) from the Salesforce/instructblip-flan-t5-xl style configuration
+ >>> model = InstructBlipQFormerModel(configuration)
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "instructblip_qformer"
+ base_config_key = "qformer_config"
+
+ vocab_size: int = 30522
+ hidden_size: int = 768
+ num_hidden_layers: int = 12
+ num_attention_heads: int = 12
+ intermediate_size: int = 3072
+ hidden_act: str = "gelu"
+ hidden_dropout_prob: float | int = 0.1
+ attention_probs_dropout_prob: float | int = 0.1
+ max_position_embeddings: int = 512
+ initializer_range: float = 0.02
+ layer_norm_eps: float = 1e-12
+ pad_token_id: int | None = 0
+ cross_attention_frequency: int = 2
+ encoder_hidden_size: int = 1408
+
+
+@auto_docstring(checkpoint="Salesforce/instructblip-flan-t5-xl")
+@strict
+class InstructBlipConfig(PreTrainedConfig):
+ r"""
+ qformer_config (`dict`, *optional*):
+ Dictionary of configuration options used to initialize [`InstructBlipQFormerConfig`].
+ num_query_tokens (`int`, *optional*, defaults to 32):
+ The number of query tokens passed through the Transformer.
+
+ Example:
+
+ ```python
+ >>> from transformers import (
+ ... InstructBlipVisionConfig,
+ ... InstructBlipQFormerConfig,
+ ... OPTConfig,
+ ... InstructBlipConfig,
+ ... InstructBlipForConditionalGeneration,
+ ... )
+
+ >>> # Initializing a InstructBlipConfig with Salesforce/instructblip-flan-t5-xl style configuration
+ >>> configuration = InstructBlipConfig()
+
+ >>> # Initializing a InstructBlipForConditionalGeneration (with random weights) from the Salesforce/instructblip-flan-t5-xl style configuration
+ >>> model = InstructBlipForConditionalGeneration(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+
+ >>> # We can also initialize a InstructBlipConfig from a InstructBlipVisionConfig, InstructBlipQFormerConfig and any PreTrainedConfig
+
+ >>> # Initializing InstructBLIP vision, InstructBLIP Q-Former and language model configurations
+ >>> vision_config = InstructBlipVisionConfig()
+ >>> qformer_config = InstructBlipQFormerConfig()
+ >>> text_config = OPTConfig()
+
+ >>> config = InstructBlipConfig(vision_config=vision_config, qformer_config=qformer_config, text_config=text_config)
+ ```"""
+
+ model_type = "instructblip"
+ attribute_map = {
+ "image_token_id": "image_token_index",
+ }
+ sub_configs = {
+ "text_config": AutoConfig,
+ "qformer_config": InstructBlipQFormerConfig,
+ "vision_config": InstructBlipVisionConfig,
+ }
+
+ vision_config: dict | PreTrainedConfig | None = None
+ qformer_config: dict | PreTrainedConfig | None = None
+ text_config: dict | PreTrainedConfig | None = None
+ num_query_tokens: int = 32
+ image_token_index: int | None = None
+ initializer_factor: float = 1.0
+ initializer_range: float = 0.02
+
+ def __post_init__(self, **kwargs):
+ if self.text_config is None:
+ self.text_config = CONFIG_MAPPING["opt"]()
+ logger.info("text_config is None. Initializing the text config with default values (`OPTConfig`).")
+ elif isinstance(self.text_config, dict):
+ text_model_type = self.text_config.get("model_type", "opt")
+ self.text_config = CONFIG_MAPPING[text_model_type](**self.text_config)
+
+ if self.qformer_config is None:
+ self.qformer_config = InstructBlipQFormerConfig()
+ logger.info("qformer_config is None. Initializing the InstructBlipQFormerConfig with default values.")
+ elif isinstance(self.qformer_config, dict):
+ self.qformer_config = InstructBlipQFormerConfig(**self.qformer_config)
+
+ if self.vision_config is None:
+ self.vision_config = InstructBlipVisionConfig()
+ logger.info("`vision_config` is `None`. initializing the `InstructBlipVisionConfig` with default values.")
+ elif isinstance(self.vision_config, dict):
+ self.vision_config = InstructBlipVisionConfig(**self.vision_config)
+
+ self.qformer_config.encoder_hidden_size = self.vision_config.hidden_size
+ self.use_decoder_only_language_model = self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
+ super().__post_init__(**kwargs)
+
+
+__all__ = ["InstructBlipConfig", "InstructBlipQFormerConfig", "InstructBlipVisionConfig"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/instructblip/modeling_instructblip.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/instructblip/modeling_instructblip.py
new file mode 100644
index 0000000000000000000000000000000000000000..3eec091c4414a5268d1ecd1660899db47946cdd4
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/instructblip/modeling_instructblip.py
@@ -0,0 +1,1405 @@
+# Copyright 2023 The Salesforce Authors and The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch InstructBLIP model."""
+
+import math
+from collections.abc import Callable
+from dataclasses import dataclass
+from typing import Any
+
+import torch
+from torch import nn
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...generation import GenerationMixin
+from ...masking_utils import create_bidirectional_mask
+from ...modeling_flash_attention_utils import FlashAttentionKwargs
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import (
+ BaseModelOutput,
+ BaseModelOutputWithPastAndCrossAttentions,
+ BaseModelOutputWithPooling,
+ BaseModelOutputWithPoolingAndCrossAttentions,
+ CausalLMOutputWithPast,
+ Seq2SeqLMOutput,
+)
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
+from ...processing_utils import Unpack
+from ...pytorch_utils import apply_chunking_to_forward
+from ...utils import ModelOutput, TransformersKwargs, auto_docstring, can_return_tuple, logging, torch_int
+from ...utils.generic import merge_with_config_defaults
+from ...utils.output_capturing import OutputRecorder, capture_outputs
+from ..auto import AutoModel, AutoModelForCausalLM, AutoModelForSeq2SeqLM
+from .configuration_instructblip import InstructBlipConfig, InstructBlipQFormerConfig, InstructBlipVisionConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+@auto_docstring
+@dataclass
+class BaseModelOutputWithVisionQformerOutputs(BaseModelOutputWithPooling):
+ r"""
+ vision_outputs (`BaseModelOutputWithPooling`):
+ Outputs of the vision encoder.
+ qformer_outputs (`BaseModelOutputWithPoolingAndCrossAttentions`):
+ Outputs of the Q-Former (Querying Transformer).
+ """
+
+ vision_outputs: BaseModelOutputWithPooling | None = None
+ qformer_outputs: BaseModelOutputWithPoolingAndCrossAttentions | None = None
+
+
+@auto_docstring(
+ custom_intro="""
+ Class defining the outputs of [`InstructBlipForConditionalGeneration`].
+ """
+)
+@dataclass
+# Copied from transformers.models.blip_2.modeling_blip_2.Blip2ForConditionalGenerationModelOutput with Blip2->InstructBlip
+class InstructBlipForConditionalGenerationModelOutput(ModelOutput):
+ r"""
+ loss (`torch.FloatTensor`, *optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
+ Language modeling loss from the language model.
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
+ Prediction scores of the language modeling head of the language model.
+ vision_outputs (`BaseModelOutputWithPooling`):
+ Outputs of the vision encoder.
+ qformer_outputs (`BaseModelOutputWithPoolingAndCrossAttentions`):
+ Outputs of the Q-Former (Querying Transformer).
+ language_model_outputs (`CausalLMOutputWithPast` or `Seq2SeqLMOutput`):
+ Outputs of the language model.
+ """
+
+ loss: tuple[torch.FloatTensor] | None = None
+ logits: tuple[torch.FloatTensor] | None = None
+ vision_outputs: BaseModelOutputWithPooling | None = None
+ qformer_outputs: BaseModelOutputWithPoolingAndCrossAttentions | None = None
+ language_model_outputs: CausalLMOutputWithPast | Seq2SeqLMOutput | None = None
+
+ def to_tuple(self) -> tuple[Any]:
+ return tuple(
+ self[k]
+ if k not in ["vision_outputs", "qformer_outputs", "language_model_outputs"]
+ else getattr(self, k).to_tuple()
+ for k in self.keys()
+ )
+
+
+# Copied from transformers.models.blip.modeling_blip.BlipVisionEmbeddings with Blip->InstructBlip
+class InstructBlipVisionEmbeddings(nn.Module):
+ def __init__(self, config: InstructBlipVisionConfig):
+ super().__init__()
+ self.config = config
+ self.embed_dim = config.hidden_size
+ self.image_size = config.image_size
+ self.patch_size = config.patch_size
+
+ self.class_embedding = nn.Parameter(torch.randn(1, 1, self.embed_dim))
+
+ self.patch_embedding = nn.Conv2d(
+ in_channels=3, out_channels=self.embed_dim, kernel_size=self.patch_size, stride=self.patch_size
+ )
+
+ self.num_patches = (self.image_size // self.patch_size) ** 2
+ self.num_positions = self.num_patches + 1
+
+ self.position_embedding = nn.Parameter(torch.randn(1, self.num_positions, self.embed_dim))
+
+ def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor:
+ """
+ This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher resolution
+ images. This method is also adapted to support torch.jit tracing.
+
+ Adapted from:
+ - https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174-L194, and
+ - https://github.com/facebookresearch/dinov2/blob/e1277af2ba9496fbadf7aec6eba56e8d882d1e35/dinov2/models/vision_transformer.py#L179-L211
+ """
+
+ num_patches = embeddings.shape[1] - 1
+ num_positions = self.position_embedding.shape[1] - 1
+
+ # always interpolate when tracing to ensure the exported model works for dynamic input shapes
+ if not torch.jit.is_tracing() and num_patches == num_positions and height == width:
+ return self.position_embedding
+
+ class_pos_embed = self.position_embedding[:, :1]
+ patch_pos_embed = self.position_embedding[:, 1:]
+
+ dim = embeddings.shape[-1]
+
+ new_height = height // self.patch_size
+ new_width = width // self.patch_size
+
+ sqrt_num_positions = torch_int(num_positions**0.5)
+ patch_pos_embed = patch_pos_embed.reshape(1, sqrt_num_positions, sqrt_num_positions, dim)
+ patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2)
+
+ patch_pos_embed = nn.functional.interpolate(
+ patch_pos_embed,
+ size=(new_height, new_width),
+ mode="bicubic",
+ align_corners=False,
+ )
+
+ patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
+
+ return torch.cat((class_pos_embed, patch_pos_embed), dim=1)
+
+ def forward(self, pixel_values: torch.FloatTensor, interpolate_pos_encoding: bool = False) -> torch.Tensor:
+ batch_size, _, height, width = pixel_values.shape
+ target_dtype = self.patch_embedding.weight.dtype
+ patch_embeds = self.patch_embedding(pixel_values.to(dtype=target_dtype)) # shape = [*, width, grid, grid]
+ patch_embeds = patch_embeds.flatten(2).transpose(1, 2)
+ class_embeds = self.class_embedding.expand(batch_size, 1, -1).to(target_dtype)
+ embeddings = torch.cat([class_embeds, patch_embeds], dim=1)
+ if interpolate_pos_encoding:
+ position_embedding = self.interpolate_pos_encoding(embeddings, height, width)
+ else:
+ position_embedding = self.position_embedding
+ embeddings = embeddings + position_embedding[:, : embeddings.size(1), :].to(target_dtype)
+ return embeddings
+
+
+# Adapted from transformers.models.siglip.modeling_siglip.eager_attention_forward -> InstructBLIP doesn't cast attn weights to fp32
+def eager_attention_forward(
+ module: nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: torch.Tensor | None,
+ scaling: float,
+ dropout: float = 0.0,
+ **kwargs,
+):
+ attn_weights = torch.matmul(query, key.transpose(-1, -2)) * scaling
+ if attention_mask is not None:
+ attn_weights = attn_weights + attention_mask
+
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
+
+ attn_output = torch.matmul(attn_weights, value)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+
+ return attn_output, attn_weights
+
+
+# Copied from transformers.models.blip_2.modeling_blip_2.Blip2Attention with Blip2->InstructBlip
+class InstructBlipAttention(nn.Module):
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
+
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.embed_dim = config.hidden_size
+ self.num_heads = config.num_attention_heads
+ self.head_dim = self.embed_dim // self.num_heads
+ if self.head_dim * self.num_heads != self.embed_dim:
+ raise ValueError(
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
+ f" {self.num_heads})."
+ )
+ self.scale = self.head_dim**-0.5
+ self.is_causal = False
+ self.attention_dropout = config.attention_dropout
+
+ # small tweak here compared to CLIP, no bias here
+ self.qkv = nn.Linear(self.embed_dim, 3 * self.embed_dim, bias=False)
+
+ if config.qkv_bias:
+ q_bias = nn.Parameter(torch.zeros(self.embed_dim))
+ v_bias = nn.Parameter(torch.zeros(self.embed_dim))
+ else:
+ q_bias = None
+ v_bias = None
+
+ if q_bias is not None:
+ qkv_bias = torch.cat((q_bias, torch.zeros_like(v_bias, requires_grad=False), v_bias))
+ self.qkv.bias = nn.Parameter(qkv_bias)
+
+ self.projection = nn.Linear(self.embed_dim, self.embed_dim)
+
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ **kwargs,
+ ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
+ """Input shape: Batch x Time x Channel"""
+
+ bsz, tgt_len, embed_dim = hidden_states.size()
+
+ mixed_qkv = self.qkv(hidden_states)
+
+ mixed_qkv = mixed_qkv.reshape(bsz, tgt_len, 3, self.num_heads, embed_dim // self.num_heads).permute(
+ 2, 0, 3, 1, 4
+ )
+ query_states, key_states, value_states = mixed_qkv[0], mixed_qkv[1], mixed_qkv[2]
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_states,
+ key_states,
+ value_states,
+ attention_mask=None,
+ dropout=0.0 if not self.training else self.attention_dropout,
+ scaling=self.scale,
+ **kwargs,
+ )
+
+ attn_output = attn_output.reshape(bsz, tgt_len, -1).contiguous()
+ attn_output = self.projection(attn_output)
+
+ return attn_output, attn_weights
+
+
+# Copied from transformers.models.blip.modeling_blip.BlipMLP
+class InstructBlipMLP(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.activation_fn = ACT2FN[config.hidden_act]
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.fc1(hidden_states)
+ hidden_states = self.activation_fn(hidden_states)
+ hidden_states = self.fc2(hidden_states)
+ return hidden_states
+
+
+# Copied from transformers.models.blip.modeling_blip.BlipEncoderLayer with Blip->InstructBlip
+class InstructBlipEncoderLayer(GradientCheckpointingLayer):
+ def __init__(self, config: InstructBlipConfig):
+ super().__init__()
+ self.embed_dim = config.hidden_size
+ self.self_attn = InstructBlipAttention(config)
+ self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
+ self.mlp = InstructBlipMLP(config)
+ self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
+
+ @auto_docstring
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.FloatTensor:
+ residual = hidden_states
+
+ hidden_states = self.layer_norm1(hidden_states)
+ hidden_states, _ = self.self_attn(
+ hidden_states=hidden_states,
+ **kwargs,
+ )
+ hidden_states = hidden_states + residual
+ residual = hidden_states
+ hidden_states = self.layer_norm2(hidden_states)
+ hidden_states = self.mlp(hidden_states)
+
+ hidden_states = hidden_states + residual
+
+ return hidden_states
+
+
+@auto_docstring
+class InstructBlipPreTrainedModel(PreTrainedModel):
+ config: InstructBlipConfig
+ base_model_prefix = "blip"
+ input_modalities = ("image", "text")
+ supports_gradient_checkpointing = True
+ _supports_attention_backend = True
+ _supports_flash_attn = True
+ _supports_sdpa = True
+ _supports_flex_attn = True
+
+ _can_compile_fullgraph = True
+
+ _no_split_modules = [
+ "InstructBlipQFormerEmbeddings",
+ "InstructBlipAttention",
+ "InstructBlipQFormerMultiHeadAttention",
+ "InstructBlipQFormerSelfOutput",
+ ]
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ """Initialize the weights"""
+ super()._init_weights(module)
+ factor = self.config.initializer_range
+ if isinstance(module, InstructBlipVisionEmbeddings):
+ init.trunc_normal_(module.position_embedding, mean=0.0, std=factor)
+ init.trunc_normal_(module.class_embedding, mean=0.0, std=factor)
+ elif isinstance(module, (InstructBlipForConditionalGeneration, InstructBlipModel)):
+ init.zeros_(module.query_tokens)
+ elif isinstance(module, InstructBlipQFormerEmbeddings):
+ init.copy_(module.position_ids, torch.arange(module.position_ids.shape[-1]).expand((1, -1)))
+
+
+# Copied from transformers.models.blip.modeling_blip.BlipEncoder with Blip->InstructBlip
+class InstructBlipEncoder(nn.Module):
+ """
+ Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
+ [`InstructBlipEncoderLayer`].
+
+ Args:
+ config (`InstructBlipConfig`):
+ The corresponding vision configuration for the `InstructBlipEncoder`.
+ """
+
+ def __init__(self, config: InstructBlipConfig):
+ super().__init__()
+ self.config = config
+ self.layers = nn.ModuleList([InstructBlipEncoderLayer(config) for _ in range(config.num_hidden_layers)])
+ self.gradient_checkpointing = False
+
+ @auto_docstring
+ def forward(
+ self,
+ inputs_embeds,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutput:
+ hidden_states = inputs_embeds
+ for encoder_layer in self.layers:
+ hidden_states = encoder_layer(
+ hidden_states,
+ **kwargs,
+ )
+
+ return BaseModelOutput(last_hidden_state=hidden_states)
+
+
+class InstructBlipVisionModel(InstructBlipPreTrainedModel):
+ main_input_name = "pixel_values"
+ input_modalities = ("image",)
+ config: InstructBlipVisionConfig
+ _can_record_outputs = {
+ "hidden_states": InstructBlipEncoderLayer,
+ "attentions": InstructBlipAttention,
+ }
+
+ def __init__(self, config: InstructBlipVisionConfig):
+ super().__init__(config)
+ self.config = config
+ embed_dim = config.hidden_size
+
+ self.embeddings = InstructBlipVisionEmbeddings(config)
+ self.encoder = InstructBlipEncoder(config)
+ self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
+
+ self.post_init()
+
+ @merge_with_config_defaults
+ @capture_outputs(tie_last_hidden_states=False)
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: torch.FloatTensor | None = None,
+ interpolate_pos_encoding: bool = False,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutputWithPooling:
+ if pixel_values is None:
+ raise ValueError("You have to specify pixel_values")
+
+ hidden_states = self.embeddings(pixel_values, interpolate_pos_encoding=interpolate_pos_encoding)
+
+ encoder_outputs: BaseModelOutput = self.encoder(
+ inputs_embeds=hidden_states,
+ **kwargs,
+ )
+
+ last_hidden_state = encoder_outputs.last_hidden_state
+ last_hidden_state = self.post_layernorm(last_hidden_state)
+
+ pooled_output = last_hidden_state[:, 0, :]
+ pooled_output = self.post_layernorm(pooled_output)
+
+ return BaseModelOutputWithPooling(
+ last_hidden_state=last_hidden_state,
+ pooler_output=pooled_output,
+ )
+
+ def get_input_embeddings(self):
+ return self.embeddings
+
+
+class InstructBlipQFormerMultiHeadAttention(nn.Module):
+ def __init__(self, config, is_cross_attention=False):
+ super().__init__()
+ self.config = config
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
+ raise ValueError(
+ "The hidden size (%d) is not a multiple of the number of attention heads (%d)"
+ % (config.hidden_size, config.num_attention_heads)
+ )
+
+ self.num_attention_heads = config.num_attention_heads
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
+
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
+ if is_cross_attention:
+ self.key = nn.Linear(config.encoder_hidden_size, self.all_head_size)
+ self.value = nn.Linear(config.encoder_hidden_size, self.all_head_size)
+ else:
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
+
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
+ self.save_attention = False
+
+ def save_attn_gradients(self, attn_gradients):
+ self.attn_gradients = attn_gradients
+
+ def get_attn_gradients(self):
+ return self.attn_gradients
+
+ def save_attention_map(self, attention_map):
+ self.attention_map = attention_map
+
+ def get_attention_map(self):
+ return self.attention_map
+
+ def transpose_for_scores(self, x):
+ new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
+ x = x.view(*new_x_shape)
+ return x.permute(0, 2, 1, 3)
+
+ def forward(
+ self,
+ hidden_states,
+ attention_mask=None,
+ encoder_hidden_states=None,
+ encoder_attention_mask=None,
+ **kwargs: Unpack[TransformersKwargs],
+ ):
+ # If this is instantiated as a cross-attention module, the keys
+ # and values come from an encoder; the attention mask needs to be
+ # such that the encoder's padding tokens are not attended to.
+ is_cross_attention = encoder_hidden_states is not None
+
+ if is_cross_attention:
+ key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
+ value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
+ attention_mask = encoder_attention_mask
+ else:
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
+
+ mixed_query_layer = self.query(hidden_states)
+
+ query_layer = self.transpose_for_scores(mixed_query_layer)
+
+ # Take the dot product between "query" and "key" to get the raw attention scores.
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
+
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
+ attention_scores_dtype = attention_scores.dtype
+
+ if attention_mask is not None:
+ # Apply the attention mask is (precomputed for all layers in BertModel forward() function)
+ attention_scores = attention_scores + attention_mask
+
+ # Normalize the attention scores to probabilities.
+ attention_probs = nn.Softmax(dim=-1)(attention_scores).to(attention_scores_dtype)
+
+ if is_cross_attention and self.save_attention:
+ self.save_attention_map(attention_probs)
+ attention_probs.register_hook(self.save_attn_gradients)
+
+ # This is actually dropping out entire tokens to attend to, which might
+ # seem a bit unusual, but is taken from the original Transformer paper.
+ attention_probs_dropped = self.dropout(attention_probs)
+
+ context_layer = torch.matmul(attention_probs_dropped, value_layer)
+
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
+ context_layer = context_layer.view(*new_context_layer_shape)
+
+ return context_layer, attention_probs
+
+
+# Copied from transformers.models.bert.modeling_bert.BertSelfOutput with Bert->InstructBlipQFormer
+class InstructBlipQFormerSelfOutput(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
+ return hidden_states
+
+
+# Copied from transformers.models.blip_2.modeling_blip_2.Blip2QFormerAttention with Blip2->InstructBlip
+class InstructBlipQFormerAttention(nn.Module):
+ def __init__(self, config, is_cross_attention=False):
+ super().__init__()
+ self.attention = InstructBlipQFormerMultiHeadAttention(config, is_cross_attention)
+ self.output = InstructBlipQFormerSelfOutput(config)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.FloatTensor | None = None,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ encoder_attention_mask: torch.FloatTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.Tensor:
+ attn_output, _ = self.attention(
+ hidden_states=hidden_states,
+ attention_mask=attention_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ **kwargs,
+ )
+ attention_output = self.output(attn_output, hidden_states)
+ return attention_output
+
+
+# Copied from transformers.models.bert.modeling_bert.BertIntermediate with Bert->InstructBlipQFormer
+class InstructBlipQFormerIntermediate(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
+ if isinstance(config.hidden_act, str):
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
+ else:
+ self.intermediate_act_fn = config.hidden_act
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.intermediate_act_fn(hidden_states)
+ return hidden_states
+
+
+# Copied from transformers.models.bert.modeling_bert.BertOutput with Bert->InstructBlipQFormer
+class InstructBlipQFormerOutput(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
+ return hidden_states
+
+
+class InstructBlipQFormerLayer(GradientCheckpointingLayer):
+ def __init__(self, config, layer_idx):
+ super().__init__()
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
+ self.seq_len_dim = 1
+ self.attention = InstructBlipQFormerAttention(config)
+
+ self.layer_idx = layer_idx
+
+ if layer_idx % config.cross_attention_frequency == 0:
+ self.crossattention = InstructBlipQFormerAttention(config, is_cross_attention=True)
+ self.has_cross_attention = True
+ else:
+ self.has_cross_attention = False
+
+ self.intermediate = InstructBlipQFormerIntermediate(config)
+ self.output = InstructBlipQFormerOutput(config)
+
+ self.intermediate_query = InstructBlipQFormerIntermediate(config)
+ self.output_query = InstructBlipQFormerOutput(config)
+
+ def forward(
+ self,
+ hidden_states,
+ attention_mask=None,
+ encoder_hidden_states=None,
+ encoder_attention_mask=None,
+ query_length=0,
+ **kwargs: Unpack[TransformersKwargs],
+ ):
+ attention_output = self.attention(
+ hidden_states,
+ attention_mask=attention_mask,
+ **kwargs,
+ )
+
+ if query_length > 0:
+ query_attention_output = attention_output[:, :query_length, :]
+
+ if self.has_cross_attention:
+ if encoder_hidden_states is None:
+ raise ValueError("encoder_hidden_states must be given for cross-attention layers")
+ query_attention_output = self.crossattention(
+ query_attention_output,
+ attention_mask=attention_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ **kwargs,
+ )
+
+ layer_output = apply_chunking_to_forward(
+ self.feed_forward_chunk_query,
+ self.chunk_size_feed_forward,
+ self.seq_len_dim,
+ query_attention_output,
+ )
+
+ if attention_output.shape[1] > query_length:
+ layer_output_text = apply_chunking_to_forward(
+ self.feed_forward_chunk,
+ self.chunk_size_feed_forward,
+ self.seq_len_dim,
+ attention_output[:, query_length:, :],
+ ).to(layer_output.device)
+ layer_output = torch.cat([layer_output, layer_output_text], dim=1)
+ else:
+ layer_output = apply_chunking_to_forward(
+ self.feed_forward_chunk,
+ self.chunk_size_feed_forward,
+ self.seq_len_dim,
+ attention_output,
+ )
+ return layer_output
+
+ def feed_forward_chunk(self, attention_output):
+ intermediate_output = self.intermediate(attention_output)
+ layer_output = self.output(intermediate_output, attention_output)
+ return layer_output
+
+ def feed_forward_chunk_query(self, attention_output):
+ intermediate_output = self.intermediate_query(attention_output)
+ layer_output = self.output_query(intermediate_output, attention_output)
+ return layer_output
+
+
+# Copied from transformers.models.blip_2.modeling_blip_2.Blip2QFormerEncoder with Blip2->InstructBlip
+class InstructBlipQFormerEncoder(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.layer = nn.ModuleList(
+ [InstructBlipQFormerLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
+ )
+ self.gradient_checkpointing = False
+
+ @can_return_tuple
+ def forward(
+ self,
+ hidden_states,
+ attention_mask=None,
+ encoder_hidden_states=None,
+ encoder_attention_mask=None,
+ query_length=0,
+ **kwargs: Unpack[TransformersKwargs],
+ ):
+ for i in range(self.config.num_hidden_layers):
+ layer_module = self.layer[i]
+
+ hidden_states = layer_module(
+ hidden_states,
+ attention_mask,
+ encoder_hidden_states, # as a positional argument for gradient checkpointing
+ encoder_attention_mask=encoder_attention_mask,
+ query_length=query_length,
+ **kwargs,
+ )
+
+ return BaseModelOutputWithPastAndCrossAttentions(
+ last_hidden_state=hidden_states,
+ )
+
+
+class InstructBlipQFormerEmbeddings(nn.Module):
+ """Construct the embeddings from word and position embeddings."""
+
+ def __init__(self, config):
+ super().__init__()
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
+ self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
+
+ self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
+ self.register_buffer(
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
+ )
+
+ self.config = config
+
+ def forward(
+ self,
+ input_ids=None,
+ position_ids=None,
+ query_embeds=None,
+ past_key_values_length=0,
+ ):
+ if input_ids is not None:
+ seq_length = input_ids.size()[1]
+ else:
+ seq_length = 0
+
+ if position_ids is None:
+ position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length].clone()
+
+ if input_ids is not None:
+ embeddings = self.word_embeddings(input_ids)
+
+ position_embeddings = self.position_embeddings(position_ids.to(embeddings.device))
+ embeddings = embeddings + position_embeddings
+
+ if query_embeds is not None:
+ embeddings = torch.cat((query_embeds, embeddings), dim=1)
+ else:
+ embeddings = query_embeds
+
+ embeddings = embeddings.to(self.layernorm.weight.dtype)
+ embeddings = self.layernorm(embeddings)
+ embeddings = self.dropout(embeddings)
+ return embeddings
+
+
+class InstructBlipQFormerModel(InstructBlipPreTrainedModel):
+ """
+ Querying Transformer (Q-Former), used in InstructBLIP. Slightly modified from BLIP-2 as it also takes the
+ instruction as input.
+ """
+
+ _supports_attention_backend = False # adds position on attn weights before last matmul
+ _supports_flash_attn = False
+ _supports_sdpa = False
+ _supports_flex_attn = False
+
+ _can_record_outputs = {
+ "hidden_states": InstructBlipQFormerLayer,
+ "attentions": [
+ OutputRecorder(InstructBlipQFormerMultiHeadAttention, index=1, layer_name=".attention"),
+ ],
+ "cross_attentions": [
+ OutputRecorder(InstructBlipQFormerMultiHeadAttention, index=1, layer_name=".crossattention"),
+ ],
+ }
+
+ def __init__(self, config: InstructBlipQFormerConfig):
+ super().__init__(config)
+ self.config = config
+
+ self.embeddings = InstructBlipQFormerEmbeddings(config)
+
+ self.encoder = InstructBlipQFormerEncoder(config)
+
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.embeddings.word_embeddings
+
+ def set_input_embeddings(self, value):
+ self.embeddings.word_embeddings = value
+
+ @merge_with_config_defaults
+ @capture_outputs
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor,
+ attention_mask: torch.FloatTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ query_embeds: torch.Tensor | None = None,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ encoder_attention_mask: torch.FloatTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.FloatTensor] | BaseModelOutputWithPoolingAndCrossAttentions:
+ r"""
+ query_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
+ Hidden states to be used in the attention computation. If cross-attention,
+ will be used for the query (i.e., key and value will use the encoder_hidden_states).
+ """
+ if input_ids is None and query_embeds is None:
+ raise ValueError("You have to specify query_embeds when input_ids is None")
+
+ query_length = query_embeds.shape[1] if query_embeds is not None else 0
+
+ embedding_output = self.embeddings(
+ input_ids=input_ids,
+ position_ids=position_ids,
+ query_embeds=query_embeds,
+ )
+
+ attention_mask = create_bidirectional_mask(
+ config=self.config,
+ inputs_embeds=embedding_output,
+ attention_mask=attention_mask,
+ )
+
+ if encoder_attention_mask is not None:
+ encoder_attention_mask = create_bidirectional_mask(
+ config=self.config,
+ inputs_embeds=embedding_output,
+ attention_mask=encoder_attention_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ )
+
+ encoder_outputs: BaseModelOutput = self.encoder(
+ embedding_output,
+ attention_mask=attention_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ query_length=query_length,
+ **kwargs,
+ )
+ sequence_output = encoder_outputs.last_hidden_state
+ pooled_output = sequence_output[:, 0, :]
+
+ return BaseModelOutputWithPoolingAndCrossAttentions(
+ last_hidden_state=sequence_output,
+ pooler_output=pooled_output,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ InstructBLIP base Model consisting of language model, qformer and vision encoder.
+ """
+)
+class InstructBlipModel(InstructBlipPreTrainedModel):
+ main_input_name = "pixel_values"
+ _keep_in_fp32_modules = ["query_tokens"] # TODO @ArthurZucker I don't know why this is required for FP8
+
+ def __init__(self, config: InstructBlipConfig):
+ super().__init__(config)
+
+ self.vision_model = InstructBlipVisionModel(config.vision_config)
+ self.query_tokens = nn.Parameter(torch.zeros(1, config.num_query_tokens, config.qformer_config.hidden_size))
+ self.qformer = InstructBlipQFormerModel(config.qformer_config)
+
+ self.language_projection = nn.Linear(config.qformer_config.hidden_size, config.text_config.hidden_size)
+ self.language_model = AutoModel.from_config(config.text_config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def _preprocess_accelerate(self):
+ r"""
+ Some pre-processing hacks to make the model `accelerate` compatible. Check
+ https://github.com/huggingface/transformers/pull/21707 for more details.
+ """
+ hf_device_map = self.hf_device_map
+
+ if len(hf_device_map) > 1 and "language_model" not in hf_device_map and torch.cuda.device_count() > 1:
+ # warn users about unexpected behavior when using multi-GPU + InstructBLIP + `accelerate`.
+ logger.warning(
+ "The `language_model` is not in the `hf_device_map` dictionary and you are running your script"
+ " in a multi-GPU environment. this may lead to unexpected behavior when using `accelerate`."
+ " Please pass a `device_map` that contains `language_model` to remove this warning."
+ " Please refer to https://github.com/huggingface/blog/blob/main/accelerate-large-models.md for"
+ " more details on creating a `device_map` for large models.",
+ )
+
+ if hasattr(self.language_model, "_hf_hook"):
+ self.language_model._hf_hook.io_same_device = True # For `generate` compatibility
+
+ def get_placeholder_mask(self, input_ids: torch.LongTensor, inputs_embeds: torch.FloatTensor):
+ """
+ Obtains multimodal placeholder mask from `input_ids` or `inputs_embeds`.
+ """
+ if input_ids is None:
+ special_image_mask = inputs_embeds == self.get_input_embeddings()(
+ torch.tensor(self.config.image_token_id, dtype=torch.long, device=inputs_embeds.device)
+ )
+ special_image_mask = special_image_mask.all(-1)
+ else:
+ special_image_mask = input_ids == self.config.image_token_id
+
+ special_image_mask = special_image_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
+ return special_image_mask
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: torch.FloatTensor,
+ qformer_input_ids: torch.FloatTensor,
+ qformer_attention_mask: torch.LongTensor | None = None,
+ input_ids: torch.FloatTensor | None = None,
+ attention_mask: torch.LongTensor | None = None,
+ decoder_input_ids: torch.LongTensor | None = None,
+ decoder_attention_mask: torch.LongTensor | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ interpolate_pos_encoding: bool = False,
+ **kwargs: Unpack[FlashAttentionKwargs],
+ ) -> tuple | InstructBlipForConditionalGenerationModelOutput:
+ r"""
+ qformer_input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Indices of input sequence tokens in the vocabulary of the Q-Former. Input tokens can optionally be provided
+ to serve as text prompt, which the Q-Former model will encode.
+
+ Indices can be obtained using [`InstructBlipProcessor`]. See [`InstructBlipProcessor.__call__`] for
+ details.
+
+ [What are input IDs?](../glossary#input-ids)
+ qformer_attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
+
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+
+ [What are attention masks?](../glossary#attention-mask)
+ decoder_attention_mask (`torch.BoolTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
+ Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
+ be used by default.
+
+ Only relevant in case an encoder-decoder language model (like T5) is used.
+ """
+
+ # step 1: forward the images through the vision encoder,
+ # to get image embeddings of shape (batch_size, seq_len, hidden_size)
+ vision_outputs = self.vision_model(
+ pixel_values=pixel_values,
+ interpolate_pos_encoding=interpolate_pos_encoding,
+ **kwargs,
+ )
+ image_embeds = vision_outputs[0]
+
+ # step 2: forward the query tokens through the QFormer, using the image embeddings for cross-attention
+ image_attention_mask = torch.ones(image_embeds.size()[:-1], dtype=torch.long, device=image_embeds.device)
+
+ # difference with BLIP-2 here: we also feed the instruction prompt to the Q-Former
+ query_tokens = self.query_tokens.expand(image_embeds.shape[0], -1, -1)
+ query_attention_mask = torch.ones(query_tokens.size()[:-1], dtype=torch.long, device=image_embeds.device)
+ if qformer_attention_mask is None:
+ qformer_attention_mask = torch.ones_like(qformer_input_ids)
+ qformer_attention_mask = torch.cat([query_attention_mask, qformer_attention_mask], dim=1)
+ query_outputs = self.qformer(
+ input_ids=qformer_input_ids,
+ attention_mask=qformer_attention_mask,
+ query_embeds=query_tokens,
+ encoder_hidden_states=image_embeds,
+ encoder_attention_mask=image_attention_mask,
+ **kwargs,
+ )
+ query_output = query_outputs[0][:, : query_tokens.size(1), :]
+
+ if inputs_embeds is None:
+ inputs_embeds = self.language_model.get_input_embeddings()(input_ids)
+ if attention_mask is None:
+ attention_mask = torch.ones_like(input_ids)
+
+ # step 3: use the language model, conditioned on the query outputs and the prompt
+ language_model_inputs = self.language_projection(query_output)
+ language_model_inputs = language_model_inputs.to(inputs_embeds.device, inputs_embeds.dtype)
+ special_image_mask = self.get_placeholder_mask(input_ids, inputs_embeds=inputs_embeds)
+ inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, language_model_inputs)
+
+ if self.config.use_decoder_only_language_model:
+ outputs = self.language_model(
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ **kwargs,
+ )
+ else:
+ outputs = self.language_model(
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ decoder_input_ids=decoder_input_ids,
+ decoder_attention_mask=decoder_attention_mask,
+ **kwargs,
+ )
+
+ return InstructBlipForConditionalGenerationModelOutput(
+ vision_outputs=vision_outputs,
+ qformer_outputs=query_outputs,
+ language_model_outputs=outputs,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ InstructBLIP Model for generating text given an image and an optional text prompt. The model consists of a vision
+ encoder, Querying Transformer (Q-Former) and a language model.
+
+ One can optionally pass `input_ids` to the model, which serve as a text prompt, to make the language model continue
+ the prompt. Otherwise, the language model starts generating text from the [BOS] (beginning-of-sequence) token.
+ """
+)
+class InstructBlipForConditionalGeneration(InstructBlipPreTrainedModel, GenerationMixin):
+ config: InstructBlipConfig
+ main_input_name = "pixel_values"
+
+ _can_compile_fullgraph = True
+ _keep_in_fp32_modules = ["query_tokens"] # TODO @ArthurZucker I don't know why this is required for FP8
+
+ def __init__(self, config: InstructBlipConfig):
+ super().__init__(config)
+
+ self.vision_model = InstructBlipVisionModel._from_config(config.vision_config)
+
+ self.query_tokens = nn.Parameter(torch.zeros(1, config.num_query_tokens, config.qformer_config.hidden_size))
+ self.qformer = InstructBlipQFormerModel._from_config(config.qformer_config)
+
+ self.language_projection = nn.Linear(config.qformer_config.hidden_size, config.text_config.hidden_size)
+
+ if config.use_decoder_only_language_model:
+ language_model = AutoModelForCausalLM.from_config(config.text_config)
+ else:
+ language_model = AutoModelForSeq2SeqLM.from_config(config.text_config)
+
+ self.language_model = language_model
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def set_output_embeddings(self, new_embeddings):
+ self.language_model.set_output_embeddings(new_embeddings)
+
+ def get_output_embeddings(self) -> nn.Module:
+ return self.language_model.get_output_embeddings()
+
+ def get_encoder(self, modality=None):
+ if modality is None:
+ return self.language_model.get_encoder()
+ else:
+ return super().get_encoder(modality=modality)
+
+ def get_decoder(self):
+ return self.language_model.get_decoder()
+
+ # Copied from transformers.models.instructblip.modeling_instructblip.InstructBlipModel._preprocess_accelerate
+ def _preprocess_accelerate(self):
+ r"""
+ Some pre-processing hacks to make the model `accelerate` compatible. Check
+ https://github.com/huggingface/transformers/pull/21707 for more details.
+ """
+ hf_device_map = self.hf_device_map
+
+ if len(hf_device_map) > 1 and "language_model" not in hf_device_map and torch.cuda.device_count() > 1:
+ # warn users about unexpected behavior when using multi-GPU + InstructBLIP + `accelerate`.
+ logger.warning(
+ "The `language_model` is not in the `hf_device_map` dictionary and you are running your script"
+ " in a multi-GPU environment. this may lead to unexpected behavior when using `accelerate`."
+ " Please pass a `device_map` that contains `language_model` to remove this warning."
+ " Please refer to https://github.com/huggingface/blog/blob/main/accelerate-large-models.md for"
+ " more details on creating a `device_map` for large models.",
+ )
+
+ if hasattr(self.language_model, "_hf_hook"):
+ self.language_model._hf_hook.io_same_device = True # For `generate` compatibility
+
+ @can_return_tuple
+ @auto_docstring
+ def get_image_features(
+ self,
+ pixel_values: torch.FloatTensor,
+ qformer_input_ids: torch.LongTensor,
+ qformer_attention_mask: torch.LongTensor | None = None,
+ interpolate_pos_encoding: bool | None = False,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutputWithVisionQformerOutputs:
+ r"""
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
+ The tensors corresponding to the input images.
+ qformer_input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Indices of input sequence tokens in the vocabulary of the Q-Former. Input tokens can optionally be provided
+ to serve as text prompt, which the Q-Former model will encode.
+
+ Indices can be obtained using [`InstructBlipProcessor`]. See [`InstructBlipProcessor.__call__`] for
+ details.
+
+ [What are input IDs?](../glossary#input-ids)
+ qformer_attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
+
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+
+ [What are attention masks?](../glossary#attention-mask)
+ """
+ # step 1: forward the images through the vision encoder,
+ # to get image embeddings of shape (batch_size, seq_len, hidden_size)
+ vision_outputs: BaseModelOutputWithPooling = self.vision_model(
+ pixel_values=pixel_values,
+ interpolate_pos_encoding=interpolate_pos_encoding,
+ return_dict=True,
+ **kwargs,
+ )
+ vision_outputs = BaseModelOutputWithVisionQformerOutputs(**vision_outputs, vision_outputs=vision_outputs)
+ image_embeds = vision_outputs[0]
+
+ # step 2: forward the query tokens through the QFormer, using the image embeddings for cross-attention
+ image_attention_mask = torch.ones(image_embeds.size()[:-1], dtype=torch.long, device=image_embeds.device)
+
+ # difference with BLIP-2 here: we also feed the instruction prompt to the Q-Former
+ query_tokens = self.query_tokens.expand(image_embeds.shape[0], -1, -1)
+ query_attention_mask = torch.ones(query_tokens.size()[:-1], dtype=torch.long, device=image_embeds.device)
+ if qformer_attention_mask is None:
+ qformer_attention_mask = torch.ones_like(qformer_input_ids)
+ qformer_attention_mask = torch.cat([query_attention_mask, qformer_attention_mask], dim=1)
+ qformer_outputs = self.qformer(
+ input_ids=qformer_input_ids,
+ attention_mask=qformer_attention_mask,
+ query_embeds=query_tokens,
+ encoder_hidden_states=image_embeds,
+ encoder_attention_mask=image_attention_mask,
+ return_dict=True,
+ **kwargs,
+ )
+ vision_outputs.qformer_outputs = qformer_outputs
+ query_output = qformer_outputs[0][:, : query_tokens.size(1), :]
+
+ # step 3: use the language model, conditioned on the query outputs and the prompt
+ image_features = self.language_projection(query_output)
+ vision_outputs.pooler_output = image_features
+
+ return vision_outputs
+
+ def get_placeholder_mask(self, input_ids: torch.LongTensor, inputs_embeds: torch.FloatTensor):
+ """
+ Obtains multimodal placeholder mask from `input_ids` or `inputs_embeds`.
+ """
+ if input_ids is None:
+ special_image_mask = inputs_embeds == self.get_input_embeddings()(
+ torch.tensor(self.config.image_token_id, dtype=torch.long, device=inputs_embeds.device)
+ )
+ special_image_mask = special_image_mask.all(-1)
+ else:
+ special_image_mask = input_ids == self.config.image_token_id
+
+ special_image_mask = special_image_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
+ return special_image_mask
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: torch.FloatTensor,
+ qformer_input_ids: torch.FloatTensor,
+ qformer_attention_mask: torch.LongTensor | None = None,
+ input_ids: torch.FloatTensor | None = None,
+ attention_mask: torch.LongTensor | None = None,
+ decoder_input_ids: torch.LongTensor | None = None,
+ decoder_attention_mask: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ interpolate_pos_encoding: bool = False,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | InstructBlipForConditionalGenerationModelOutput:
+ r"""
+ qformer_input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Indices of input sequence tokens in the vocabulary of the Q-Former. Input tokens can optionally be provided
+ to serve as text prompt, which the Q-Former model will encode.
+
+ Indices can be obtained using [`InstructBlipProcessor`]. See [`InstructBlipProcessor.__call__`] for
+ details.
+
+ [What are input IDs?](../glossary#input-ids)
+ qformer_attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
+
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+
+ [What are attention masks?](../glossary#attention-mask)
+ decoder_attention_mask (`torch.BoolTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
+ Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
+ be used by default.
+
+ Only relevant in case an encoder-decoder language model (like T5) is used.
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the language modeling loss. Indices should be in `[-100, 0, ..., config.vocab_size -
+ 1]`. All labels set to `-100` are ignored (masked), the loss is only computed for labels in `[0, ...,
+ config.vocab_size]`
+
+ Examples:
+
+ ```python
+ >>> from transformers import InstructBlipProcessor, InstructBlipForConditionalGeneration
+ >>> import torch
+ >>> from PIL import Image
+ >>> import httpx
+ >>> from io import BytesIO
+
+ >>> model = InstructBlipForConditionalGeneration.from_pretrained("Salesforce/instructblip-vicuna-7b")
+ >>> processor = InstructBlipProcessor.from_pretrained("Salesforce/instructblip-vicuna-7b")
+
+ >>> device = "cuda" if torch.cuda.is_available() else "cpu"
+ >>> model.to(device) # doctest: +IGNORE_RESULT
+
+ >>> url = "https://raw.githubusercontent.com/salesforce/LAVIS/main/docs/_static/Confusing-Pictures.jpg"
+ >>> with httpx.stream("GET", url) as response:
+ ... image = Image.open(BytesIO(response.read())).convert("RGB")
+ >>> prompt = "What is unusual about this image?"
+ >>> inputs = processor(images=image, text=prompt, return_tensors="pt").to(device)
+
+ >>> outputs = model.generate(
+ ... **inputs,
+ ... do_sample=False,
+ ... num_beams=5,
+ ... max_length=256,
+ ... min_length=1,
+ ... top_p=0.9,
+ ... repetition_penalty=1.5,
+ ... length_penalty=1.0,
+ ... temperature=1,
+ ... )
+ >>> generated_text = processor.batch_decode(outputs, skip_special_tokens=True)[0].strip()
+ >>> print(generated_text)
+ The unusual aspect of this image is that a man is ironing clothes on the back of a yellow SUV, which is parked in the middle of a busy city street. This is an unconventional approach to ironing clothes, as it requires the man to balance himself and his ironing equipment on top of the vehicle while navigating through traffic. Additionally, the presence of taxis and other vehicles in the scene further emphasizes the unusual nature of this situation.
+ ```"""
+
+ image_features: BaseModelOutputWithVisionQformerOutputs = self.get_image_features(
+ pixel_values,
+ qformer_input_ids=qformer_input_ids,
+ qformer_attention_mask=qformer_attention_mask,
+ interpolate_pos_encoding=interpolate_pos_encoding,
+ return_dict=True,
+ )
+ language_model_inputs = image_features.pooler_output
+ qformer_outputs = image_features.qformer_outputs
+ vision_outputs = image_features.vision_outputs
+
+ if inputs_embeds is None:
+ inputs_embeds = self.get_input_embeddings()(input_ids)
+
+ if attention_mask is None:
+ attention_mask = torch.ones_like(input_ids)
+
+ language_model_inputs = language_model_inputs.to(inputs_embeds.device, inputs_embeds.dtype)
+ special_image_mask = self.get_placeholder_mask(input_ids, inputs_embeds=inputs_embeds)
+ inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, language_model_inputs)
+
+ if self.config.use_decoder_only_language_model:
+ outputs = self.language_model(
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ **kwargs,
+ )
+ logits = outputs[0]
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(
+ logits=logits, labels=labels, vocab_size=self.config.text_config.vocab_size, **kwargs
+ )
+
+ else:
+ kwargs["return_dict"] = True
+ outputs = self.language_model(
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ decoder_input_ids=decoder_input_ids,
+ decoder_attention_mask=decoder_attention_mask,
+ labels=labels,
+ **kwargs,
+ )
+ loss = outputs.loss
+ logits = outputs.logits
+
+ return InstructBlipForConditionalGenerationModelOutput(
+ loss=loss,
+ logits=logits,
+ vision_outputs=vision_outputs,
+ qformer_outputs=qformer_outputs,
+ language_model_outputs=outputs,
+ )
+
+ @torch.no_grad()
+ def generate(
+ self,
+ pixel_values: torch.FloatTensor,
+ qformer_input_ids: torch.LongTensor | None = None,
+ qformer_attention_mask: torch.LongTensor | None = None,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ interpolate_pos_encoding: bool = False,
+ **generate_kwargs,
+ ) -> torch.LongTensor:
+ """
+ Overrides `generate` function to be able to use the model as a conditional generator.
+
+ Args:
+ pixel_values (`torch.FloatTensor` of shape (batch_size, num_channels, height, width)):
+ Input images to be processed.
+ qformer_input_ids (`torch.LongTensor` of shape (batch_size, sequence_length), *optional*):
+ The sequence used as a prompt to be fed to the Q-Former module.
+ qformer_attention_mask (`torch.LongTensor` of shape (batch_size, sequence_length), *optional*):
+ Mask to avoid performing attention on padding token indices.
+ input_ids (`torch.LongTensor` of shape (batch_size, sequence_length), *optional*):
+ The sequence used as a prompt for the generation.
+ attention_mask (`torch.LongTensor` of shape (batch_size, sequence_length), *optional*):
+ Mask to avoid performing attention on padding token indices.
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
+ Embedded representation of the inputs. Should be float, not int tokens.
+ interpolate_pos_encoding (`bool`, *optional*, defaults to `False`):
+ Whether to interpolate the positional encoding of the image embeddings.
+
+ Returns:
+ captions (list): A list of strings of length batch_size * num_captions.
+ """
+ if hasattr(self, "hf_device_map"):
+ # preprocess for `accelerate`
+ self._preprocess_accelerate()
+
+ batch_size = pixel_values.shape[0]
+ image_features: BaseModelOutputWithVisionQformerOutputs = self.get_image_features(
+ pixel_values,
+ qformer_input_ids=qformer_input_ids,
+ qformer_attention_mask=qformer_attention_mask,
+ interpolate_pos_encoding=interpolate_pos_encoding,
+ return_dict=True,
+ )
+ language_model_inputs = image_features.pooler_output
+
+ if inputs_embeds is None:
+ if input_ids is None:
+ image_tokens = [self.config.image_token_index] * self.config.num_query_tokens
+ start_tokens = image_tokens + [self.config.text_config.bos_token_id]
+ input_ids = torch.tensor([start_tokens], dtype=torch.long, device=pixel_values.device)
+ input_ids = input_ids.repeat(batch_size, 1)
+ inputs_embeds = self.get_input_embeddings()(input_ids)
+
+ if attention_mask is None:
+ attention_mask = torch.ones_like(input_ids)
+
+ language_model_inputs = language_model_inputs.to(inputs_embeds.device, inputs_embeds.dtype)
+ special_image_mask = self.get_placeholder_mask(input_ids, inputs_embeds=inputs_embeds)
+ inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, language_model_inputs)
+
+ inputs = {"inputs_embeds": inputs_embeds, "attention_mask": attention_mask}
+ if not self.language_model.config.is_encoder_decoder:
+ inputs["input_ids"] = input_ids
+
+ outputs = self.language_model.generate(**inputs, **generate_kwargs)
+
+ return outputs
+
+
+__all__ = [
+ "InstructBlipQFormerModel",
+ "InstructBlipPreTrainedModel",
+ "InstructBlipModel",
+ "InstructBlipForConditionalGeneration",
+ "InstructBlipVisionModel",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/instructblip/processing_instructblip.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/instructblip/processing_instructblip.py
new file mode 100644
index 0000000000000000000000000000000000000000..10c69dd79d1d4d7b2a65a6f326dbad9a3f40b3be
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/instructblip/processing_instructblip.py
@@ -0,0 +1,123 @@
+# Copyright 2023 The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""
+Processor class for InstructBLIP. Largely copy of Blip2Processor with addition of a tokenizer for the Q-Former.
+"""
+
+from ...image_processing_utils import BatchFeature
+from ...image_utils import ImageInput
+from ...processing_utils import ProcessingKwargs, ProcessorMixin, Unpack
+from ...tokenization_utils_base import AddedToken, PreTokenizedInput, TextInput
+from ...utils import auto_docstring, logging
+
+
+logger = logging.get_logger(__name__)
+
+
+class InstructBlipProcessorKwargs(ProcessingKwargs, total=False):
+ _defaults = {
+ "text_kwargs": {
+ "add_special_tokens": True,
+ "padding": False,
+ "stride": 0,
+ "return_overflowing_tokens": False,
+ "return_special_tokens_mask": False,
+ "return_offsets_mapping": False,
+ "return_token_type_ids": False,
+ "return_length": False,
+ "verbose": True,
+ },
+ }
+
+
+@auto_docstring
+class InstructBlipProcessor(ProcessorMixin):
+ def __init__(self, image_processor, tokenizer, qformer_tokenizer, num_query_tokens=None, **kwargs):
+ r"""
+ qformer_tokenizer (`AutoTokenizer`):
+ An instance of ['PreTrainedTokenizer`]. The Q-Former tokenizer is a required input.
+ num_query_tokens (`int`, *optional*):
+ "
+ Number of tokens used by the Qformer as queries, should be same as in model's config.
+ """
+ if not hasattr(tokenizer, "image_token"):
+ self.image_token = AddedToken("", normalized=False, special=True)
+ tokenizer.add_tokens([self.image_token], special_tokens=True)
+ else:
+ self.image_token = tokenizer.image_token
+ self.num_query_tokens = num_query_tokens
+
+ super().__init__(image_processor, tokenizer, qformer_tokenizer)
+
+ @auto_docstring
+ def __call__(
+ self,
+ images: ImageInput | None = None,
+ text: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] = None,
+ **kwargs: Unpack[InstructBlipProcessorKwargs],
+ ) -> BatchFeature:
+ if images is None and text is None:
+ raise ValueError("You have to specify at least images or text.")
+
+ output_kwargs = self._merge_kwargs(
+ InstructBlipProcessorKwargs,
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
+ **kwargs,
+ )
+
+ return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None)
+ encoding = {}
+ if text is not None:
+ if isinstance(text, str):
+ text = [text]
+ elif not isinstance(text, list) and not isinstance(text[0], str):
+ raise ValueError("Invalid input text. Please provide a string, or a list of strings")
+
+ qformer_text_encoding = self.qformer_tokenizer(text, **output_kwargs["text_kwargs"])
+ encoding["qformer_input_ids"] = qformer_text_encoding.pop("input_ids")
+ encoding["qformer_attention_mask"] = qformer_text_encoding.pop("attention_mask")
+
+ # We need this hacky manipulation because BLIP expects image tokens to be at the beginning even before BOS token
+ if output_kwargs["text_kwargs"].get("max_length") is not None:
+ output_kwargs["text_kwargs"]["max_length"] -= self.num_query_tokens
+ text_encoding = self.tokenizer(text, **output_kwargs["text_kwargs"])
+
+ if images is not None:
+ # Image tokens should not be padded/truncated or prepended with special BOS token
+ image_tokens = self.image_token.content * self.num_query_tokens
+ output_kwargs["text_kwargs"]["add_special_tokens"] = False
+ output_kwargs["text_kwargs"]["padding"] = False
+ output_kwargs["text_kwargs"]["truncation"] = False
+ image_text_encoding = self.tokenizer(image_tokens, **output_kwargs["text_kwargs"])
+ for k in text_encoding:
+ text_encoding[k] = [image_text_encoding[k] + sample for sample in text_encoding[k]]
+ encoding.update(text_encoding)
+
+ if images is not None:
+ image_encoding = self.image_processor(images, **output_kwargs["images_kwargs"])
+ encoding.update(image_encoding)
+
+ # Cast to desired return tensors type
+ encoding = BatchFeature(encoding, tensor_type=return_tensors)
+ return encoding
+
+ @property
+ def model_input_names(self):
+ tokenizer_input_names = self.tokenizer.model_input_names
+ image_processor_input_names = self.image_processor.model_input_names
+ qformer_input_names = ["qformer_input_ids", "qformer_attention_mask"]
+ return tokenizer_input_names + image_processor_input_names + qformer_input_names
+
+
+__all__ = ["InstructBlipProcessor"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/kosmos2/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/kosmos2/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..51dbdaf40a1050b8ff624d86ed58cd07fcd9174f
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/kosmos2/__init__.py
@@ -0,0 +1,28 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_kosmos2 import *
+ from .modeling_kosmos2 import *
+ from .processing_kosmos2 import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/kosmos2/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/kosmos2/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..47a80d9832cbdf18921a2722066fdbce057bcfe2
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/kosmos2/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/kosmos2/__pycache__/configuration_kosmos2.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/kosmos2/__pycache__/configuration_kosmos2.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8e1b780ff5ff6c94573ff8fd4fc0fb8f37b97da9
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/kosmos2/__pycache__/configuration_kosmos2.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/kosmos2/__pycache__/modeling_kosmos2.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/kosmos2/__pycache__/modeling_kosmos2.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a67b8b61d564b62ebd0ca85f6e859f39eacfae78
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/kosmos2/__pycache__/modeling_kosmos2.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/kosmos2/__pycache__/processing_kosmos2.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/kosmos2/__pycache__/processing_kosmos2.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4b594781f92c8e2714af79753b5c0a78e2d944fb
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/kosmos2/__pycache__/processing_kosmos2.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/kosmos2/configuration_kosmos2.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/kosmos2/configuration_kosmos2.py
new file mode 100644
index 0000000000000000000000000000000000000000..20288a9d79b5d3dca71f7d5ddaed047b616269f5
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/kosmos2/configuration_kosmos2.py
@@ -0,0 +1,125 @@
+# Copyright 2023 Microsoft Research and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""KOSMOS-2 model configuration"""
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring, logging
+
+
+logger = logging.get_logger(__name__)
+
+
+@auto_docstring(checkpoint="microsoft/kosmos-2-patch14-224")
+@strict
+class Kosmos2TextConfig(PreTrainedConfig):
+ model_type = "kosmos_2_text_model"
+ base_config_key = "text_config"
+ keys_to_ignore_at_inference = ["past_key_values"]
+ attribute_map = {
+ "num_attention_heads": "attention_heads",
+ "hidden_size": "embed_dim",
+ "num_hidden_layers": "layers",
+ }
+
+ vocab_size: int = 65037
+ max_position_embeddings: int = 2048
+ embed_dim: int = 2048
+ layers: int = 24
+ ffn_dim: int = 8192
+ attention_heads: int = 32
+ activation_function: str = "gelu"
+ dropout: float | int = 0.1
+ attention_dropout: float | int = 0.1
+ activation_dropout: float | int = 0.0
+ layerdrop: float | int = 0.0
+ layer_norm_eps: float = 1e-5
+ init_std: float = 0.02
+ scale_embedding: bool = True
+ use_cache: bool = True
+ tie_word_embeddings: bool = True
+ pad_token_id: int | None = 1
+ bos_token_id: int | None = 0
+ eos_token_id: int | list[int] | None = 2
+ add_cross_attention: bool = False
+
+
+@auto_docstring(checkpoint="microsoft/kosmos-2-patch14-224")
+@strict
+class Kosmos2VisionConfig(PreTrainedConfig):
+ model_type = "kosmos_2_vision_model"
+ base_config_key = "vision_config"
+
+ hidden_size: int = 1024
+ intermediate_size: int = 4096
+ num_hidden_layers: int = 24
+ num_attention_heads: int = 16
+ num_channels: int = 3
+ image_size: int | list[int] | tuple[int, int] = 224
+ patch_size: int | list[int] | tuple[int, int] = 14
+ hidden_act: str = "quick_gelu"
+ layer_norm_eps: float = 1e-5
+ attention_dropout: float | int = 0.0
+ initializer_range: float = 0.02
+ initializer_factor: float = 1.0
+
+
+@auto_docstring(checkpoint="microsoft/kosmos-2-patch14-224")
+@strict
+class Kosmos2Config(PreTrainedConfig):
+ r"""
+ latent_query_num (`int`, *optional*, defaults to 64):
+ The number of latent query tokens that represent the image features used in the text decoder component.
+
+ Example:
+
+ ```python
+ >>> from transformers import Kosmos2Config, Kosmos2Model
+
+ >>> # Initializing a Kosmos-2 kosmos-2-patch14-224 style configuration
+ >>> configuration = Kosmos2Config()
+
+ >>> # Initializing a model (with random weights) from the kosmos-2-patch14-224 style configuration
+ >>> model = Kosmos2Model(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "kosmos-2"
+ sub_configs = {"text_config": Kosmos2TextConfig, "vision_config": Kosmos2VisionConfig}
+
+ text_config: dict | PreTrainedConfig | None = None
+ vision_config: dict | PreTrainedConfig | None = None
+ latent_query_num: int = 64
+ tie_word_embeddings: bool = True
+
+ def __post_init__(self, **kwargs):
+ if self.text_config is None:
+ self.text_config = Kosmos2TextConfig()
+ logger.info("`text_config` is `None`. initializing the `Kosmos2TextConfig` with default values.")
+ elif isinstance(self.text_config, dict):
+ self.text_config = Kosmos2TextConfig(**self.text_config)
+
+ if self.vision_config is None:
+ self.vision_config = Kosmos2VisionConfig()
+ logger.info("`vision_config` is `None`. initializing the `Kosmos2VisionConfig` with default values.")
+ elif isinstance(self.vision_config, dict):
+ self.vision_config = Kosmos2VisionConfig(**self.vision_config)
+
+ super().__post_init__(**kwargs)
+
+
+__all__ = ["Kosmos2Config", "Kosmos2TextConfig", "Kosmos2VisionConfig"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/kosmos2/modeling_kosmos2.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/kosmos2/modeling_kosmos2.py
new file mode 100644
index 0000000000000000000000000000000000000000..62caf0b539f3117524550a64d92ff5888d588771
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/kosmos2/modeling_kosmos2.py
@@ -0,0 +1,1691 @@
+# Copyright 2023 Microsoft Research and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch KOSMOS-2 model."""
+
+import math
+import warnings
+from collections.abc import Callable
+from dataclasses import dataclass
+from typing import Any
+
+import torch
+from torch import nn
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...cache_utils import Cache, DynamicCache, EncoderDecoderCache
+from ...generation import GenerationMixin
+from ...modeling_flash_attention_utils import FlashAttentionKwargs
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import (
+ BaseModelOutput,
+ BaseModelOutputWithPastAndCrossAttentions,
+ BaseModelOutputWithPooling,
+ CausalLMOutputWithCrossAttentions,
+)
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import ModelOutput, TransformersKwargs, auto_docstring, can_return_tuple, logging, torch_int
+from ...utils.generic import merge_with_config_defaults
+from ...utils.output_capturing import OutputRecorder, capture_outputs
+from .configuration_kosmos2 import Kosmos2Config, Kosmos2TextConfig, Kosmos2VisionConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+@auto_docstring
+class Kosmos2PreTrainedModel(PreTrainedModel):
+ config: Kosmos2Config
+ input_modalities = ("image", "text")
+ supports_gradient_checkpointing = True
+ _no_split_modules = ["Kosmos2VisionEncoderLayer", "Kosmos2TextBlock"]
+ _supports_attention_backend = True
+ _supports_flash_attn = False # cuda device errors
+ _supports_sdpa = True
+
+ @torch.no_grad()
+ def _init_weights(self, module: nn.Module):
+ """Initialize the weights"""
+ if hasattr(self.config, "initializer_factor"):
+ factor = self.config.initializer_factor
+ elif hasattr(self.config, "vision_config"):
+ factor = self.config.vision_config.initializer_factor
+
+ if hasattr(self.config, "init_std"):
+ std = self.config.init_std
+ elif hasattr(self.config, "text_config"):
+ std = self.config.text_config.init_std
+
+ if isinstance(module, Kosmos2VisionEmbeddings):
+ init.normal_(module.class_embedding, mean=0.0, std=module.embed_dim**-0.5 * factor)
+ init.normal_(module.patch_embedding.weight, std=module.config.initializer_range * factor)
+ init.normal_(module.position_embedding.weight, std=module.config.initializer_range * factor)
+ init.copy_(module.position_ids, torch.arange(module.position_ids.shape[-1]).expand((1, -1)))
+ elif isinstance(module, Kosmos2VisionAttention):
+ in_proj_std = (module.embed_dim**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor
+ out_proj_std = (module.embed_dim**-0.5) * factor
+ init.normal_(module.q_proj.weight, std=in_proj_std)
+ init.normal_(module.k_proj.weight, std=in_proj_std)
+ init.normal_(module.v_proj.weight, std=in_proj_std)
+ init.normal_(module.out_proj.weight, std=out_proj_std)
+ elif isinstance(module, Kosmos2VisionMLP):
+ in_proj_std = (module.config.hidden_size**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor
+ fc_std = (2 * module.config.hidden_size) ** -0.5 * factor
+ init.normal_(module.fc1.weight, std=fc_std)
+ init.normal_(module.fc2.weight, std=in_proj_std)
+ elif isinstance(module, KosmosTextAttention):
+ init.normal_(module.q_proj.weight, std=std)
+ init.normal_(module.k_proj.weight, std=std)
+ init.normal_(module.v_proj.weight, std=std)
+ init.normal_(module.out_proj.weight, std=std)
+ elif isinstance(module, Kosmos2TextFFN):
+ init.normal_(module.fc1.weight, std=std)
+ init.normal_(module.fc2.weight, std=std)
+ elif isinstance(module, Kosmos2TextForCausalLM):
+ init.normal_(module.lm_head.weight, std=std)
+ elif isinstance(module, Kosmos2ImageToTextProjection):
+ init.normal_(module.dense.weight, std=std)
+ init.normal_(module.latent_query)
+ elif isinstance(module, Kosmos2TextTransformer):
+ init.normal_(module.embed_tokens.weight, mean=0.0, std=std)
+ if module.embed_tokens.padding_idx is not None:
+ init.zeros_(module.embed_tokens.weight[module.embed_tokens.padding_idx])
+ elif isinstance(module, nn.LayerNorm):
+ init.ones_(module.weight)
+ init.zeros_(module.bias)
+ elif isinstance(module, Kosmos2TextSinusoidalPositionalEmbedding):
+ emb_weights = module.get_embedding(
+ module.num_positions + module.offset, module.embedding_dim, module.padding_idx
+ )
+ init.copy_(module.weights, emb_weights)
+
+ if isinstance(module, nn.Linear) and module.bias is not None:
+ init.zeros_(module.bias)
+
+
+def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: int | None = None):
+ """
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
+ """
+ bsz, src_len = mask.size()
+ tgt_len = tgt_len if tgt_len is not None else src_len
+
+ expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
+
+ inverted_mask = 1.0 - expanded_mask
+
+ return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
+
+
+def _make_causal_mask(
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
+):
+ """
+ Make causal mask used for bi-directional self-attention.
+ """
+ bsz, tgt_len = input_ids_shape
+ mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min, device=device)
+ mask_cond = torch.arange(mask.size(-1), device=device)
+ mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
+ mask = mask.to(dtype)
+
+ if past_key_values_length > 0:
+ mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
+ return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
+
+
+@auto_docstring
+@dataclass
+class BaseModelOutputWithProjectionAttentions(BaseModelOutputWithPooling):
+ r"""
+ projection_attentions (`tuple(torch.FloatTensor)`):
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
+ sequence_length)`.
+
+ Attentions weights given by `Kosmos2ImageToTextProjection`, after the attention softmax, used to compute
+ the weighted average in the self-attention heads.
+ """
+
+ projection_attentions: tuple[torch.FloatTensor] | None = None
+
+
+@auto_docstring(
+ custom_intro="""
+ Base class for text model's outputs that also contains a pooling of the last hidden states.
+ """
+)
+@dataclass
+class Kosmos2ModelOutput(ModelOutput):
+ r"""
+ past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
+ It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
+
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and optionally if
+ `config.is_encoder_decoder=True` in the cross-attention blocks) that can be used (see `past_key_values`
+ input) to speed up sequential decoding.
+ image_embeds (`torch.FloatTensor` of shape `(batch_size, latent_query_num, hidden_size)`, *optional*):
+ Sequence of hidden-states at the output of `Kosmos2ImageToTextProjection`.
+ projection_attentions (`tuple(torch.FloatTensor)`, *optional*):
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
+ sequence_length)`.
+
+ Attentions weights given by `Kosmos2ImageToTextProjection`, after the attention softmax, used to compute
+ the weighted average in the self-attention heads.
+ vision_model_output (`BaseModelOutputWithPooling`, *optional*):
+ The output of the [`Kosmos2VisionModel`].
+ """
+
+ last_hidden_state: torch.FloatTensor | None = None
+ past_key_values: Cache | None = None
+ hidden_states: tuple[torch.FloatTensor] | None = None
+ attentions: tuple[torch.FloatTensor] | None = None
+ image_embeds: torch.FloatTensor | None = None
+ projection_attentions: tuple[torch.FloatTensor] | None = None
+ vision_model_output: BaseModelOutputWithPooling = None
+
+ def to_tuple(self) -> tuple[Any]:
+ return tuple(
+ self[k] if k not in ["text_model_output", "vision_model_output"] else getattr(self, k).to_tuple()
+ for k in self.keys()
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ Model output class for `Kosmos2ForConditionalGeneration`.
+ """
+)
+@dataclass
+class Kosmos2ForConditionalGenerationModelOutput(ModelOutput):
+ r"""
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
+ Language modeling loss (for next-token prediction).
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
+ past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
+ It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
+
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and optionally if
+ `config.is_encoder_decoder=True` in the cross-attention blocks) that can be used (see `past_key_values`
+ input) to speed up sequential decoding.
+ image_embeds (`torch.FloatTensor` of shape `(batch_size, latent_query_num, hidden_size)`, *optional*):
+ Sequence of hidden-states at the output of `Kosmos2ImageToTextProjection`.
+ projection_attentions (`tuple(torch.FloatTensor)`, *optional*):
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
+ sequence_length)`.
+
+ Attentions weights given by `Kosmos2ImageToTextProjection`, after the attention softmax, used to compute
+ the weighted average in the self-attention heads.
+ vision_model_output (`BaseModelOutputWithPooling`, *optional*):
+ The output of the [`Kosmos2VisionModel`].
+ """
+
+ loss: torch.FloatTensor | None = None
+ logits: torch.FloatTensor | None = None
+ past_key_values: Cache | None = None
+ hidden_states: tuple[torch.FloatTensor] | None = None
+ attentions: tuple[torch.FloatTensor] | None = None
+ image_embeds: torch.FloatTensor | None = None
+ projection_attentions: tuple[torch.FloatTensor] | None = None
+ vision_model_output: BaseModelOutputWithPooling = None
+
+ def to_tuple(self) -> tuple[Any]:
+ return tuple(
+ self[k] if k not in ["text_model_output", "vision_model_output"] else getattr(self, k).to_tuple()
+ for k in self.keys()
+ )
+
+
+# Copied from transformers.models.clip.modeling_clip.CLIPVisionEmbeddings with CLIP->Kosmos2
+class Kosmos2VisionEmbeddings(nn.Module):
+ def __init__(self, config: Kosmos2VisionConfig):
+ super().__init__()
+ self.config = config
+ self.embed_dim = config.hidden_size
+ self.image_size = config.image_size
+ self.patch_size = config.patch_size
+
+ self.class_embedding = nn.Parameter(torch.randn(self.embed_dim))
+
+ self.patch_embedding = nn.Conv2d(
+ in_channels=config.num_channels,
+ out_channels=self.embed_dim,
+ kernel_size=self.patch_size,
+ stride=self.patch_size,
+ bias=False,
+ )
+
+ self.num_patches = (self.image_size // self.patch_size) ** 2
+ self.num_positions = self.num_patches + 1
+ self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim)
+ self.register_buffer("position_ids", torch.arange(self.num_positions).expand((1, -1)), persistent=False)
+
+ def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor:
+ """
+ This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher resolution
+ images. This method is also adapted to support torch.jit tracing.
+
+ Adapted from:
+ - https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174-L194, and
+ - https://github.com/facebookresearch/dinov2/blob/e1277af2ba9496fbadf7aec6eba56e8d882d1e35/dinov2/models/vision_transformer.py#L179-L211
+ """
+
+ num_patches = embeddings.shape[1] - 1
+ position_embedding = self.position_embedding.weight.unsqueeze(0)
+ num_positions = position_embedding.shape[1] - 1
+
+ # always interpolate when tracing to ensure the exported model works for dynamic input shapes
+ if not torch.jit.is_tracing() and num_patches == num_positions and height == width:
+ return self.position_embedding(self.position_ids)
+
+ class_pos_embed = position_embedding[:, :1]
+ patch_pos_embed = position_embedding[:, 1:]
+
+ dim = embeddings.shape[-1]
+
+ new_height = height // self.patch_size
+ new_width = width // self.patch_size
+
+ sqrt_num_positions = torch_int(num_positions**0.5)
+ patch_pos_embed = patch_pos_embed.reshape(1, sqrt_num_positions, sqrt_num_positions, dim)
+ patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2)
+
+ patch_pos_embed = nn.functional.interpolate(
+ patch_pos_embed,
+ size=(new_height, new_width),
+ mode="bicubic",
+ align_corners=False,
+ )
+
+ patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
+
+ return torch.cat((class_pos_embed, patch_pos_embed), dim=1)
+
+ def forward(self, pixel_values: torch.FloatTensor, interpolate_pos_encoding=False) -> torch.Tensor:
+ batch_size, _, height, width = pixel_values.shape
+ if not interpolate_pos_encoding and (height != self.image_size or width != self.image_size):
+ raise ValueError(
+ f"Input image size ({height}*{width}) doesn't match model ({self.image_size}*{self.image_size})."
+ )
+ target_dtype = self.patch_embedding.weight.dtype
+ patch_embeds = self.patch_embedding(pixel_values.to(dtype=target_dtype)) # shape = [*, width, grid, grid]
+ patch_embeds = patch_embeds.flatten(2).transpose(1, 2)
+
+ class_embeds = self.class_embedding.expand(batch_size, 1, -1)
+ embeddings = torch.cat([class_embeds, patch_embeds], dim=1)
+ if interpolate_pos_encoding:
+ embeddings = embeddings + self.interpolate_pos_encoding(embeddings, height, width)
+ else:
+ embeddings = embeddings + self.position_embedding(self.position_ids)
+ return embeddings
+
+
+# Adapted from transformers.models.siglip.modeling_siglip.eager_attention_forward -> Kosmos2 doesn't cast attn weights to fp32
+def eager_attention_forward(
+ module: nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: torch.Tensor | None,
+ scaling: float,
+ dropout: float = 0.0,
+ **kwargs,
+):
+ attn_weights = torch.matmul(query, key.transpose(-1, -2)) * scaling
+ if attention_mask is not None:
+ attn_weights = attn_weights + attention_mask
+
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
+
+ attn_output = torch.matmul(attn_weights, value)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+ return attn_output, attn_weights
+
+
+class Kosmos2VisionAttention(nn.Module):
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
+
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.embed_dim = config.hidden_size
+ self.num_heads = config.num_attention_heads
+ self.head_dim = self.embed_dim // self.num_heads
+ if self.head_dim * self.num_heads != self.embed_dim:
+ raise ValueError(
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
+ f" {self.num_heads})."
+ )
+ self.scale = self.head_dim**-0.5
+ self.dropout = config.attention_dropout
+ self.is_causal = False
+
+ self.k_proj = nn.Linear(self.embed_dim, self.embed_dim)
+ self.v_proj = nn.Linear(self.embed_dim, self.embed_dim)
+ self.q_proj = nn.Linear(self.embed_dim, self.embed_dim)
+ self.out_proj = nn.Linear(self.embed_dim, self.embed_dim)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor, torch.Tensor | None]:
+ """Input shape: Batch x Time x Channel"""
+
+ input_shape = hidden_states.shape[:-1]
+
+ hidden_shape = (*input_shape, -1, self.head_dim)
+ queries = self.q_proj(hidden_states)
+ keys = self.k_proj(hidden_states)
+ values = self.v_proj(hidden_states)
+
+ queries = queries.view(hidden_shape).transpose(1, 2)
+ keys = keys.view(hidden_shape).transpose(1, 2)
+ values = values.view(hidden_shape).transpose(1, 2)
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ queries,
+ keys,
+ values,
+ attention_mask,
+ is_causal=self.is_causal,
+ scaling=self.scale,
+ dropout=0.0 if not self.training else self.dropout,
+ **kwargs,
+ )
+
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ attn_output = self.out_proj(attn_output)
+ return attn_output, attn_weights
+
+
+# Copied from transformers.models.clip.modeling_clip.CLIPMLP with CLIP->Kosmos2Vision
+class Kosmos2VisionMLP(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.activation_fn = ACT2FN[config.hidden_act]
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.fc1(hidden_states)
+ hidden_states = self.activation_fn(hidden_states)
+ hidden_states = self.fc2(hidden_states)
+ return hidden_states
+
+
+# Copied from transformers.models.altclip.modeling_altclip.AltCLIPEncoderLayer with AltCLIPVisionConfig->Kosmos2VisionConfig,AltCLIP->Kosmos2Vision
+class Kosmos2VisionEncoderLayer(GradientCheckpointingLayer):
+ def __init__(self, config: Kosmos2VisionConfig):
+ super().__init__()
+ self.embed_dim = config.hidden_size
+ self.self_attn = Kosmos2VisionAttention(config)
+ self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
+ self.mlp = Kosmos2VisionMLP(config)
+ self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.FloatTensor:
+ residual = hidden_states
+
+ hidden_states = self.layer_norm1(hidden_states)
+ hidden_states, _ = self.self_attn(
+ hidden_states=hidden_states,
+ attention_mask=attention_mask,
+ **kwargs,
+ )
+ hidden_states = residual + hidden_states
+
+ residual = hidden_states
+ hidden_states = self.layer_norm2(hidden_states)
+ hidden_states = self.mlp(hidden_states)
+ hidden_states = residual + hidden_states
+
+ return hidden_states
+
+
+class Kosmos2VisionEncoder(nn.Module):
+ """
+ Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
+ [`Kosmos2VisionEncoderLayer`].
+
+ Args:
+ config: Kosmos2VisionConfig
+ """
+
+ def __init__(self, config: Kosmos2VisionConfig):
+ super().__init__()
+ self.config = config
+ self.layers = nn.ModuleList([Kosmos2VisionEncoderLayer(config) for _ in range(config.num_hidden_layers)])
+ self.gradient_checkpointing = False
+
+ def forward(
+ self,
+ inputs_embeds,
+ attention_mask: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutput:
+ r"""
+ Args:
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
+ than the model's internal embedding lookup matrix.
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
+
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+
+ [What are attention masks?](../glossary#attention-mask)
+ """
+ hidden_states = inputs_embeds
+ for encoder_layer in self.layers:
+ hidden_states = encoder_layer(
+ hidden_states,
+ attention_mask,
+ **kwargs,
+ )
+
+ return BaseModelOutputWithProjectionAttentions(
+ last_hidden_state=hidden_states,
+ )
+
+
+# Similar to `transformers.models.clip.modeling_clip.CLIPVisionModel` but without docstring for `forward`
+class Kosmos2VisionTransformer(Kosmos2PreTrainedModel):
+ _can_record_outputs = {
+ "hidden_states": Kosmos2VisionEncoderLayer,
+ "attentions": Kosmos2VisionAttention,
+ }
+
+ def __init__(self, config: Kosmos2VisionConfig):
+ super().__init__(config)
+ embed_dim = config.hidden_size
+
+ self.embeddings = Kosmos2VisionEmbeddings(config)
+ self.pre_layrnorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
+ self.encoder = Kosmos2VisionEncoder(config)
+ self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
+
+ self.post_init()
+
+ @merge_with_config_defaults
+ @capture_outputs(tie_last_hidden_states=False)
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: torch.FloatTensor | None = None,
+ interpolate_pos_encoding: bool = False,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> BaseModelOutputWithPooling:
+ if pixel_values is None:
+ raise ValueError("You have to specify pixel_values")
+
+ hidden_states = self.embeddings(pixel_values, interpolate_pos_encoding=interpolate_pos_encoding)
+ hidden_states = self.pre_layrnorm(hidden_states)
+
+ encoder_outputs = self.encoder(
+ inputs_embeds=hidden_states,
+ **kwargs,
+ )
+
+ last_hidden_state = encoder_outputs[0]
+ pooled_output = last_hidden_state[:, 0, :]
+ pooled_output = self.post_layernorm(pooled_output)
+
+ return BaseModelOutputWithPooling(
+ last_hidden_state=last_hidden_state,
+ pooler_output=pooled_output,
+ )
+
+
+# Similar to `transformers.models.m2m_100.modeling_m2m_100.M2M100SinusoidalPositionalEmbedding` but allowing to pass `position_ids`
+class Kosmos2TextSinusoidalPositionalEmbedding(nn.Module):
+ """This module produces sinusoidal positional embeddings of any length."""
+
+ # Copied from transformers.models.m2m_100.modeling_m2m_100.M2M100SinusoidalPositionalEmbedding.__init__
+ def __init__(self, num_positions: int, embedding_dim: int, padding_idx: int | None = None):
+ super().__init__()
+ self.offset = 2
+ self.num_positions = num_positions
+ self.embedding_dim = embedding_dim
+ self.padding_idx = padding_idx
+ self.make_weights(num_positions + self.offset, embedding_dim, padding_idx)
+
+ # Copied from transformers.models.m2m_100.modeling_m2m_100.M2M100SinusoidalPositionalEmbedding.make_weights
+ def make_weights(self, num_embeddings: int, embedding_dim: int, padding_idx: int | None = None):
+ emb_weights = self.get_embedding(num_embeddings, embedding_dim, padding_idx)
+ if hasattr(self, "weights"):
+ # in forward put the weights on the correct dtype and device of the param
+ emb_weights = emb_weights.to(dtype=self.weights.dtype, device=self.weights.device)
+
+ self.register_buffer("weights", emb_weights, persistent=False)
+
+ @staticmethod
+ # Copied from transformers.models.m2m_100.modeling_m2m_100.M2M100SinusoidalPositionalEmbedding.get_embedding
+ def get_embedding(num_embeddings: int, embedding_dim: int, padding_idx: int | None = None):
+ """
+ Build sinusoidal embeddings.
+
+ This matches the implementation in tensor2tensor, but differs slightly from the description in Section 3.5 of
+ "Attention Is All You Need".
+ """
+ half_dim = embedding_dim // 2
+ emb = math.log(10000) / (half_dim - 1)
+ emb = torch.exp(torch.arange(half_dim, dtype=torch.int64).float() * -emb)
+ emb = torch.arange(num_embeddings, dtype=torch.int64).float().unsqueeze(1) * emb.unsqueeze(0)
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1).view(num_embeddings, -1)
+ if embedding_dim % 2 == 1:
+ # zero pad
+ emb = torch.cat([emb, torch.zeros(num_embeddings, 1)], dim=1)
+ if padding_idx is not None:
+ emb[padding_idx, :] = 0
+
+ return emb.to(torch.get_default_dtype())
+
+ @torch.no_grad()
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ past_key_values_length: int = 0,
+ position_ids: torch.Tensor | None = None,
+ ):
+ if input_ids is not None:
+ bsz, seq_len = input_ids.size()
+ if position_ids is None:
+ # Create the position ids from the input token ids. Any padded tokens remain padded.
+ position_ids = self.create_position_ids_from_input_ids(
+ input_ids, self.padding_idx, past_key_values_length
+ ).to(input_ids.device)
+ else:
+ bsz, seq_len = inputs_embeds.size()[:-1]
+ if position_ids is None:
+ position_ids = self.create_position_ids_from_inputs_embeds(
+ inputs_embeds, past_key_values_length, self.padding_idx
+ )
+
+ # expand embeddings if needed
+ max_pos = self.padding_idx + 1 + seq_len + past_key_values_length
+ if max_pos > self.weights.size(0):
+ self.make_weights(max_pos + self.offset, self.embedding_dim, self.padding_idx)
+
+ return self.weights.index_select(0, position_ids.view(-1)).view(bsz, seq_len, self.weights.shape[-1]).detach()
+
+ @staticmethod
+ # Copied from transformers.models.m2m_100.modeling_m2m_100.M2M100SinusoidalPositionalEmbedding.create_position_ids_from_inputs_embeds
+ def create_position_ids_from_inputs_embeds(inputs_embeds, past_key_values_length, padding_idx):
+ """
+ We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids.
+
+ Args:
+ inputs_embeds: torch.Tensor
+
+ Returns: torch.Tensor
+ """
+ input_shape = inputs_embeds.size()[:-1]
+ sequence_length = input_shape[1]
+
+ position_ids = torch.arange(
+ padding_idx + 1, sequence_length + padding_idx + 1, dtype=torch.long, device=inputs_embeds.device
+ )
+ return position_ids.unsqueeze(0).expand(input_shape).contiguous() + past_key_values_length
+
+ @staticmethod
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaEmbeddings.create_position_ids_from_input_ids
+ def create_position_ids_from_input_ids(input_ids, padding_idx, past_key_values_length=0):
+ """
+ Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols
+ are ignored. This is modified from fairseq's `utils.make_positions`.
+
+ Args:
+ x: torch.Tensor x:
+
+ Returns: torch.Tensor
+ """
+ # The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA.
+ mask = input_ids.ne(padding_idx).int()
+ incremental_indices = (torch.cumsum(mask, dim=1).type_as(mask) + past_key_values_length) * mask
+ return incremental_indices.long() + padding_idx
+
+
+class KosmosTextAttention(nn.Module):
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
+
+ # Similar to transformers.models.bart.modeling_bart.BartAttention.__init__ except an additional `inner_attn_ln`.
+ def __init__(
+ self,
+ config,
+ embed_dim: int,
+ num_heads: int,
+ dropout: float = 0.0,
+ is_decoder: bool | None = False,
+ add_inner_attn_layernorm: bool | None = False,
+ bias: bool | None = True,
+ layer_idx: bool | None = None,
+ ):
+ super().__init__()
+ self.config = config
+ self.embed_dim = embed_dim
+ self.num_heads = num_heads
+ self.dropout = dropout
+ self.head_dim = embed_dim // num_heads
+ self.is_causal = True
+
+ if (self.head_dim * num_heads) != self.embed_dim:
+ raise ValueError(
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
+ f" and `num_heads`: {num_heads})."
+ )
+ self.scaling = self.head_dim**-0.5
+ self.is_decoder = is_decoder
+ self.layer_idx = layer_idx
+
+ self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
+ self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
+
+ # End opy
+ self.inner_attn_ln = None
+ if add_inner_attn_layernorm:
+ self.inner_attn_ln = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: torch.Tensor | None = None,
+ past_key_values: Cache | None = None,
+ attention_mask: torch.Tensor | None = None,
+ **kwargs,
+ ) -> tuple[torch.Tensor, torch.Tensor | None, Cache | None]:
+ """Input shape: Batch x Time x Channel"""
+
+ # if key_value_states are provided this layer is used as a cross-attention layer
+ # for the decoder
+ is_cross_attention = encoder_hidden_states is not None
+ input_shape = hidden_states.shape[:-1]
+
+ hidden_shape = (*input_shape, -1, self.head_dim)
+ query_states = self.q_proj(hidden_states)
+ query_states = query_states.view(hidden_shape).transpose(1, 2)
+
+ is_updated = False
+ if past_key_values is not None:
+ if isinstance(past_key_values, EncoderDecoderCache):
+ is_updated = past_key_values.is_updated.get(self.layer_idx)
+ if is_cross_attention:
+ # after the first generated id, we can subsequently re-use all key/value_states from cache
+ curr_past_key_values = past_key_values.cross_attention_cache
+ else:
+ curr_past_key_values = past_key_values.self_attention_cache
+ else:
+ curr_past_key_values = past_key_values
+
+ current_states = encoder_hidden_states if is_cross_attention else hidden_states
+ if is_cross_attention and past_key_values is not None and is_updated:
+ # reuse k,v, cross_attentions
+ key_states = curr_past_key_values.layers[self.layer_idx].keys
+ value_states = curr_past_key_values.layers[self.layer_idx].values
+ else:
+ kv_shape = (*current_states.shape[:-1], -1, self.head_dim)
+ key_states = self.k_proj(current_states).view(kv_shape).transpose(1, 2)
+ value_states = self.v_proj(current_states).view(kv_shape).transpose(1, 2)
+
+ if past_key_values is not None:
+ # save all key/value_states to cache to be re-used for fast auto-regressive generation
+ key_states, value_states = curr_past_key_values.update(key_states, value_states, self.layer_idx)
+ # set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls
+ if is_cross_attention and isinstance(past_key_values, EncoderDecoderCache):
+ past_key_values.is_updated[self.layer_idx] = True
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_states,
+ key_states,
+ value_states,
+ attention_mask,
+ dropout=0.0 if not self.training else self.dropout,
+ scaling=self.scaling,
+ **kwargs,
+ )
+
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ if self.inner_attn_ln is not None:
+ attn_output = self.inner_attn_ln(attn_output)
+
+ attn_output = self.out_proj(attn_output)
+
+ return attn_output, attn_weights
+
+
+class Kosmos2TextFFN(nn.Module):
+ def __init__(self, config: Kosmos2TextConfig):
+ super().__init__()
+
+ self.dropout = config.dropout
+ self.activation_fn = ACT2FN[config.activation_function]
+ self.activation_dropout = config.activation_dropout
+
+ self.fc1 = nn.Linear(config.embed_dim, config.ffn_dim)
+ self.fc2 = nn.Linear(config.ffn_dim, config.embed_dim)
+
+ self.ffn_layernorm = nn.LayerNorm(config.ffn_dim, eps=config.layer_norm_eps)
+
+ def forward(self, hidden_states):
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
+ hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
+ hidden_states = self.ffn_layernorm(hidden_states)
+ hidden_states = self.fc2(hidden_states)
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
+
+ return hidden_states
+
+
+class Kosmos2TextBlock(GradientCheckpointingLayer):
+ def __init__(self, config: Kosmos2TextConfig, layer_idx=None):
+ super().__init__()
+ self.embed_dim = config.embed_dim
+
+ self.self_attn = KosmosTextAttention(
+ config,
+ embed_dim=self.embed_dim,
+ num_heads=config.attention_heads,
+ dropout=config.attention_dropout,
+ is_decoder=True,
+ add_inner_attn_layernorm=True,
+ layer_idx=layer_idx,
+ )
+ self.dropout = config.dropout
+ self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
+
+ if config.add_cross_attention:
+ self.encoder_attn = KosmosTextAttention(
+ config,
+ embed_dim=self.embed_dim,
+ num_heads=config.attention_heads,
+ dropout=config.attention_dropout,
+ is_decoder=True,
+ add_inner_attn_layernorm=False,
+ layer_idx=layer_idx,
+ )
+ self.encoder_attn_layer_norm = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
+
+ self.ffn = Kosmos2TextFFN(config)
+ self.final_layer_norm = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor | None = None,
+ encoder_hidden_states: torch.Tensor | None = None,
+ encoder_attention_mask: torch.Tensor | None = None,
+ past_key_values: Cache | None = None,
+ output_attentions: bool | None = False,
+ **kwargs,
+ ) -> tuple[torch.FloatTensor, tuple[torch.FloatTensor, torch.FloatTensor] | None]:
+ residual = hidden_states
+ hidden_states = self.self_attn_layer_norm(hidden_states)
+
+ hidden_states, _ = self.self_attn(
+ hidden_states=hidden_states,
+ past_key_values=past_key_values,
+ attention_mask=attention_mask,
+ output_attentions=output_attentions,
+ **kwargs,
+ )
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
+ hidden_states = residual + hidden_states
+
+ # Cross-Attention Block
+ if encoder_hidden_states is not None:
+ if not hasattr(self, "encoder_attn"):
+ raise ValueError(
+ f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
+ " by setting `config.add_cross_attention=True`"
+ )
+
+ residual = hidden_states
+ hidden_states = self.encoder_attn_layer_norm(hidden_states)
+
+ hidden_states, _ = self.encoder_attn(
+ hidden_states=hidden_states,
+ encoder_hidden_states=encoder_hidden_states,
+ attention_mask=encoder_attention_mask,
+ past_key_values=past_key_values,
+ output_attentions=output_attentions,
+ **kwargs,
+ )
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
+ hidden_states = residual + hidden_states
+
+ # Fully Connected
+ residual = hidden_states
+
+ hidden_states = self.final_layer_norm(hidden_states)
+
+ # FFN
+ hidden_states = self.ffn(hidden_states)
+ hidden_states = residual + hidden_states
+
+ return hidden_states
+
+
+class Kosmos2TextTransformer(Kosmos2PreTrainedModel):
+ config: Kosmos2TextConfig
+ input_modalities = ("text",)
+ _can_record_outputs = {
+ "hidden_states": Kosmos2TextBlock,
+ "attentions": OutputRecorder(KosmosTextAttention, index=1, layer_name="self_attn"),
+ "cross_attentions": OutputRecorder(KosmosTextAttention, index=1, layer_name="encoder_attn"),
+ }
+
+ def __init__(self, config: Kosmos2TextConfig):
+ super().__init__(config)
+ self.dropout = config.dropout
+ self.layerdrop = config.layerdrop
+
+ self.embed_scale = math.sqrt(config.embed_dim) if config.scale_embedding else 1.0
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.embed_dim, padding_idx=config.pad_token_id)
+
+ self.embed_positions = Kosmos2TextSinusoidalPositionalEmbedding(
+ num_positions=config.max_position_embeddings,
+ embedding_dim=config.embed_dim,
+ padding_idx=config.pad_token_id,
+ )
+
+ self.layers = nn.ModuleList([Kosmos2TextBlock(config, layer_idx=i) for i in range(config.layers)])
+ self.layer_norm = nn.LayerNorm(config.embed_dim, config.layer_norm_eps)
+
+ self.gradient_checkpointing = False
+
+ self.post_init()
+
+ def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
+ # create causal mask
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
+ combined_attention_mask = None
+ if input_shape[-1] > 1:
+ combined_attention_mask = _make_causal_mask(
+ input_shape,
+ inputs_embeds.dtype,
+ device=inputs_embeds.device,
+ past_key_values_length=past_key_values_length,
+ )
+
+ if attention_mask is not None:
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
+ expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
+ inputs_embeds.device
+ )
+ combined_attention_mask = (
+ expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
+ )
+
+ return combined_attention_mask
+
+ def forward_embedding(
+ self,
+ input_ids,
+ inputs_embeds: torch.Tensor | None = None,
+ image_embeds: torch.Tensor | None = None,
+ img_input_mask: torch.Tensor | None = None,
+ past_key_values_length: int = 0,
+ position_ids: torch.Tensor | None = None,
+ ):
+ # The argument `inputs_embeds` should be the one without being multiplied by `self.embed_scale`.
+ if inputs_embeds is None:
+ inputs_embeds = self.embed_tokens(input_ids)
+
+ if image_embeds is not None:
+ inputs_embeds[img_input_mask.to(dtype=torch.bool)] = image_embeds.to(inputs_embeds.device).view(
+ -1, image_embeds.size(-1)
+ )
+
+ inputs_embeds = inputs_embeds * self.embed_scale
+
+ # embed positions
+ positions = self.embed_positions(
+ input_ids=input_ids,
+ inputs_embeds=inputs_embeds,
+ past_key_values_length=past_key_values_length,
+ position_ids=position_ids,
+ )
+ positions = positions.to(inputs_embeds.device)
+
+ hidden_states = inputs_embeds + positions
+
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
+
+ return hidden_states
+
+ @merge_with_config_defaults
+ @capture_outputs
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ image_embeds: torch.Tensor | None = None,
+ image_embeds_position_mask: torch.Tensor | None = None,
+ encoder_hidden_states: torch.Tensor | None = None,
+ encoder_attention_mask: torch.Tensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ position_ids: torch.Tensor | None = None,
+ use_cache: bool | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs: Unpack[FlashAttentionKwargs],
+ ) -> tuple | BaseModelOutputWithPastAndCrossAttentions:
+ r"""
+ image_embeds (`torch.FloatTensor` of shape `(batch_size, latent_query_num, hidden_size)`, *optional*):
+ Sequence of hidden-states at the output of `Kosmos2ImageToTextProjection`.
+ image_embeds_position_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Mask to indicate the location in a sequence to insert the image features . Mask values selected in `[0,
+ 1]`:
+
+ - 1 for places where to put the image features,
+ - 0 for places that are not for image features (i.e. for text tokens).
+ """
+ if input_ids is not None and inputs_embeds is not None:
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
+ elif input_ids is not None:
+ input_shape = input_ids.shape
+ input_ids = input_ids.view(-1, input_shape[-1])
+ elif inputs_embeds is not None:
+ input_shape = inputs_embeds.size()[:-1]
+ else:
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
+
+ if use_cache and past_key_values is None:
+ past_key_values = (
+ EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache(config=self.config))
+ if encoder_hidden_states is not None or self.config.is_encoder_decoder
+ else DynamicCache(config=self.config)
+ )
+
+ past_key_values_length = past_key_values.get_seq_length() if past_key_values is not None else 0
+
+ # We don't need img info. when `past_key_values_length` > 0
+ if past_key_values_length > 0:
+ image_embeds = None
+ image_embeds_position_mask = None
+
+ hidden_states = self.forward_embedding(
+ input_ids=input_ids,
+ inputs_embeds=inputs_embeds,
+ image_embeds=image_embeds,
+ img_input_mask=image_embeds_position_mask,
+ past_key_values_length=past_key_values_length,
+ position_ids=position_ids,
+ )
+
+ attention_mask = self._prepare_decoder_attention_mask(
+ attention_mask, input_shape, hidden_states, past_key_values_length
+ )
+
+ # expand encoder attention mask
+ if encoder_hidden_states is not None and encoder_attention_mask is not None:
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
+ encoder_attention_mask = _expand_mask(encoder_attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1])
+
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
+
+ for decoder_layer in self.layers:
+ # add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
+ if self.training:
+ dropout_probability = torch.rand([])
+ if dropout_probability < self.layerdrop:
+ continue
+
+ hidden_states = decoder_layer(
+ hidden_states,
+ attention_mask,
+ encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ past_key_values=past_key_values,
+ output_attentions=output_attentions,
+ use_cache=use_cache,
+ **kwargs,
+ )
+
+ # add final layer norm
+ hidden_states = self.layer_norm(hidden_states)
+
+ return BaseModelOutputWithPastAndCrossAttentions(
+ last_hidden_state=hidden_states,
+ past_key_values=past_key_values,
+ )
+
+
+class Kosmos2VisionModel(Kosmos2PreTrainedModel):
+ config: Kosmos2VisionConfig
+ main_input_name = "pixel_values"
+ input_modalities = ("image",)
+
+ def __init__(self, config: Kosmos2VisionConfig):
+ super().__init__(config)
+ self.model = Kosmos2VisionTransformer(config)
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self) -> nn.Module:
+ return self.model.embeddings.patch_embedding
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: torch.FloatTensor | None = None,
+ interpolate_pos_encoding: bool = False,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutputWithProjectionAttentions:
+ return self.model(
+ pixel_values=pixel_values,
+ interpolate_pos_encoding=interpolate_pos_encoding,
+ **kwargs,
+ )
+
+
+class Kosmos2TextModel(Kosmos2PreTrainedModel):
+ config: Kosmos2TextConfig
+ input_modalities = ("text",)
+
+ def __init__(self, config: Kosmos2TextConfig):
+ super().__init__(config)
+ self.model = Kosmos2TextTransformer(config)
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self) -> nn.Module:
+ return self.model.embed_tokens
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ image_embeds: torch.Tensor | None = None,
+ image_embeds_position_mask: torch.Tensor | None = None,
+ encoder_hidden_states: torch.Tensor | None = None,
+ encoder_attention_mask: torch.Tensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ position_ids: torch.Tensor | None = None,
+ use_cache: bool | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutputWithPastAndCrossAttentions:
+ r"""
+ image_embeds (`torch.FloatTensor` of shape `(batch_size, latent_query_num, hidden_size)`, *optional*):
+ Sequence of hidden-states at the output of `Kosmos2ImageToTextProjection`.
+ image_embeds_position_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Mask to indicate the location in a sequence to insert the image features . Mask values selected in `[0,
+ 1]`:
+
+ - 1 for places where to put the image features,
+ - 0 for places that are not for image features (i.e. for text tokens).
+ """
+ return self.model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ image_embeds=image_embeds,
+ image_embeds_position_mask=image_embeds_position_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ position_ids=position_ids,
+ use_cache=use_cache,
+ **kwargs,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ The text model from KOSMOS-2 with a language modeling head on top (linear layer with weights tied to the input
+ embeddings).
+ """
+)
+class Kosmos2TextForCausalLM(Kosmos2PreTrainedModel, GenerationMixin):
+ config: Kosmos2TextConfig
+ _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
+
+ def __init__(self, config: Kosmos2TextConfig):
+ super().__init__(config)
+
+ self.model = Kosmos2TextTransformer(config)
+ self.lm_head = nn.Linear(in_features=config.embed_dim, out_features=config.vocab_size, bias=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self) -> nn.Module:
+ return self.model.embed_tokens
+
+ def get_output_embeddings(self) -> nn.Module:
+ return self.lm_head
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ image_embeds: torch.Tensor | None = None,
+ image_embeds_position_mask: torch.Tensor | None = None,
+ encoder_hidden_states: torch.Tensor | None = None,
+ encoder_attention_mask: torch.Tensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ position_ids: torch.Tensor | None = None,
+ labels: torch.LongTensor | None = None,
+ use_cache: bool | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | CausalLMOutputWithCrossAttentions:
+ r"""
+ image_embeds (`torch.FloatTensor` of shape `(batch_size, latent_query_num, hidden_size)`, *optional*):
+ Sequence of hidden-states at the output of `Kosmos2ImageToTextProjection`.
+ image_embeds_position_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Mask to indicate the location in a sequence to insert the image features . Mask values selected in `[0,
+ 1]`:
+
+ - 1 for places where to put the image features,
+ - 0 for places that are not for image features (i.e. for text tokens).
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
+ `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
+ ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
+ """
+ if labels is not None:
+ if use_cache:
+ logger.warning("The `use_cache` argument is changed to `False` since `labels` is provided.")
+ use_cache = False
+
+ outputs: BaseModelOutputWithPastAndCrossAttentions = self.model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ image_embeds=image_embeds,
+ image_embeds_position_mask=image_embeds_position_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ position_ids=position_ids,
+ use_cache=use_cache,
+ **kwargs,
+ )
+
+ hidden_states = outputs.last_hidden_state
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
+
+ return CausalLMOutputWithCrossAttentions(
+ loss=loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ cross_attentions=outputs.cross_attentions,
+ )
+
+ def prepare_inputs_for_generation(
+ self,
+ input_ids,
+ image_embeds=None,
+ image_embeds_position_mask=None,
+ past_key_values=None,
+ attention_mask=None,
+ inputs_embeds=None,
+ use_cache=None,
+ is_first_iteration=False,
+ **model_kwargs,
+ ):
+ # Overwritten -- in specific circumstances we don't want to forward image inputs to the model
+
+ # Pixel values are used only in the first iteration if available
+ # In subsequent iterations, they are already merged with text and cached
+ # NOTE: first iteration doesn't have to be prefill, it can be the first
+ # iteration with a question and cached system prompt (continue generate from cache)
+ if not is_first_iteration and use_cache:
+ image_embeds = None
+ image_embeds_position_mask = None
+
+ # appending `False` to `image_embeds_position_mask` (because sequence grows during generation)
+ elif image_embeds_position_mask is not None:
+ batch_size, seq_len = inputs_embeds.size()[:-1] if inputs_embeds is not None else attention_mask.size()
+ mask_len = image_embeds_position_mask.size()[-1]
+ image_embeds_position_mask = torch.cat(
+ (
+ image_embeds_position_mask,
+ torch.zeros(size=(batch_size, seq_len - mask_len), dtype=torch.bool, device=input_ids.device),
+ ),
+ dim=1,
+ )
+
+ model_inputs = super().prepare_inputs_for_generation(
+ input_ids,
+ past_key_values=past_key_values,
+ attention_mask=attention_mask,
+ image_embeds=image_embeds,
+ image_embeds_position_mask=image_embeds_position_mask,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ is_first_iteration=is_first_iteration,
+ **model_kwargs,
+ )
+ # Kosmos2 has offset for position ids, so we need to create them correctly in PositionEmbedding layer
+ model_inputs.pop("position_ids", None)
+
+ return model_inputs
+
+
+class Kosmos2ImageToTextProjection(nn.Module):
+ """The layer that transforms the image model's output to part of the text model's input (namely, image features)"""
+
+ def __init__(self, config: Kosmos2Config):
+ super().__init__()
+ self.dense = nn.Linear(config.vision_config.hidden_size, config.text_config.embed_dim)
+ self.latent_query = nn.Parameter(torch.randn(config.latent_query_num, config.text_config.embed_dim))
+
+ self.x_attn = KosmosTextAttention(
+ config.text_config,
+ config.text_config.embed_dim,
+ config.text_config.attention_heads,
+ dropout=config.text_config.attention_dropout,
+ is_decoder=False,
+ add_inner_attn_layernorm=False,
+ )
+
+ def forward(self, features):
+ hidden_states = self.dense(features)
+
+ # shape = [batch, latent_query_num, h_dim]
+ latent_query = self.latent_query.unsqueeze(0).expand(hidden_states.size(0), -1, -1)
+ key_value_states = torch.cat([hidden_states, latent_query], dim=1)
+
+ hidden_states, attn_weights = self.x_attn(
+ hidden_states=latent_query,
+ encoder_hidden_states=key_value_states,
+ past_key_values=None,
+ attention_mask=None,
+ output_attentions=None,
+ )
+
+ return hidden_states, attn_weights
+
+
+@auto_docstring(
+ custom_intro="""
+ KOSMOS-2 Model for generating text and image features. The model consists of a vision encoder and a language model.
+ """
+)
+class Kosmos2Model(Kosmos2PreTrainedModel):
+ config: Kosmos2Config
+ main_input_name = "pixel_values"
+
+ def __init__(self, config: Kosmos2Config):
+ super().__init__(config)
+
+ self.text_model = Kosmos2TextModel(config.text_config)
+ self.vision_model = Kosmos2VisionModel(config.vision_config)
+ self.image_to_text_projection = Kosmos2ImageToTextProjection(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self) -> nn.Module:
+ return self.text_model.model.embed_tokens
+
+ def set_input_embeddings(self, value):
+ self.text_model.model.embed_tokens = value
+
+ @can_return_tuple
+ @auto_docstring
+ def get_image_features(
+ self,
+ pixel_values: torch.FloatTensor,
+ interpolate_pos_encoding: bool | None = False,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutputWithProjectionAttentions:
+ if "return_attentions" in kwargs:
+ warnings.warn(
+ "`return_attentions` is deprecated and will be removed in a future version. Please use `return_dict`"
+ " and access `projection_attentions` from the returned `ModelOutput` instead.",
+ FutureWarning,
+ )
+ kwargs.pop("return_attentions", None)
+
+ vision_output: BaseModelOutputWithProjectionAttentions = self.vision_model(
+ pixel_values=pixel_values,
+ interpolate_pos_encoding=interpolate_pos_encoding,
+ return_dict=True,
+ **kwargs,
+ )
+ # The whole `last_hidden_state` through `post_layernorm` instead of just `pooled_output`.
+ image_embeds = self.vision_model.model.post_layernorm(vision_output[0])
+ # normalized features
+ image_embeds = nn.functional.normalize(image_embeds, dim=-1)
+ image_embeds, projection_attentions = self.image_to_text_projection(image_embeds)
+ vision_output.pooler_output = image_embeds
+ vision_output.projection_attentions = projection_attentions
+
+ return vision_output
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: torch.Tensor | None = None,
+ input_ids: torch.Tensor | None = None,
+ image_embeds_position_mask: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ past_key_values: Cache | None = None,
+ image_embeds: torch.Tensor | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ position_ids: torch.Tensor | None = None,
+ use_cache: bool | None = None,
+ interpolate_pos_encoding: bool = False,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | Kosmos2ModelOutput:
+ r"""
+ image_embeds_position_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Mask to indicate the location in a sequence to insert the image features . Mask values selected in `[0,
+ 1]`:
+
+ - 1 for places where to put the image features,
+ - 0 for places that are not for image features (i.e. for text tokens).
+ image_embeds (`torch.FloatTensor` of shape `(batch_size, latent_query_num, hidden_size)`, *optional*):
+ Sequence of hidden-states at the output of `Kosmos2ImageToTextProjection`.
+
+ Examples:
+
+ ```python
+ >>> from PIL import Image
+ >>> import httpx
+ >>> from io import BytesIO
+ >>> from transformers import AutoProcessor, Kosmos2Model
+
+ >>> model = Kosmos2Model.from_pretrained("microsoft/kosmos-2-patch14-224")
+ >>> processor = AutoProcessor.from_pretrained("microsoft/kosmos-2-patch14-224")
+
+ >>> url = "https://huggingface.co/microsoft/kosmos-2-patch14-224/resolve/main/snowman.jpg"
+ >>> with httpx.stream("GET", url) as response:
+ ... image = Image.open(BytesIO(response.read()))
+
+ >>> text = (
+ ... " An image of a snowman warming himself by a fire"
+ ... )
+
+ >>> inputs = processor(text=text, images=image, return_tensors="pt", add_eos_token=True)
+
+ >>> last_hidden_state = model(
+ ... pixel_values=inputs["pixel_values"],
+ ... input_ids=inputs["input_ids"],
+ ... attention_mask=inputs["attention_mask"],
+ ... image_embeds_position_mask=inputs["image_embeds_position_mask"],
+ ... ).last_hidden_state
+ >>> list(last_hidden_state.shape)
+ [1, 91, 2048]
+ ```"""
+ vision_model_output = None
+ projection_attentions = None
+ if image_embeds is None:
+ if pixel_values is None:
+ raise ValueError("You have to specify either `pixel_values` or `image_embeds`.")
+ image_features = self.get_image_features(
+ pixel_values, interpolate_pos_encoding=interpolate_pos_encoding, return_dict=True, **kwargs
+ )
+ image_embeds = image_features.pooler_output
+ projection_attentions = image_features.projection_attentions
+
+ outputs = self.text_model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ image_embeds=image_embeds,
+ image_embeds_position_mask=image_embeds_position_mask,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ position_ids=position_ids,
+ use_cache=use_cache,
+ return_dict=True,
+ **kwargs,
+ )
+
+ return Kosmos2ModelOutput(
+ last_hidden_state=outputs.last_hidden_state,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ image_embeds=image_embeds,
+ projection_attentions=projection_attentions,
+ vision_model_output=vision_model_output,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ KOSMOS-2 Model for generating text and bounding boxes given an image. The model consists of a vision encoder and a
+ language model.
+ """
+)
+class Kosmos2ForConditionalGeneration(Kosmos2PreTrainedModel, GenerationMixin):
+ config: Kosmos2Config
+ main_input_name = "pixel_values"
+ _tied_weights_keys = {"text_model.lm_head.weight": "text_model.model.embed_tokens.weight"}
+
+ def __init__(self, config: Kosmos2Config):
+ super().__init__(config)
+
+ self.text_model = Kosmos2TextForCausalLM(config.text_config)
+ self.vision_model = Kosmos2VisionModel(config.vision_config)
+
+ self.image_to_text_projection = Kosmos2ImageToTextProjection(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self) -> nn.Module:
+ return self.text_model.model.embed_tokens
+
+ def set_input_embeddings(self, value):
+ self.text_model.model.embed_tokens = value
+
+ def get_output_embeddings(self) -> nn.Module:
+ return self.text_model.get_output_embeddings()
+
+ def set_output_embeddings(self, new_embeddings):
+ self.text_model.set_output_embeddings(new_embeddings)
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: torch.Tensor | None = None,
+ input_ids: torch.Tensor | None = None,
+ image_embeds_position_mask: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ past_key_values: Cache | None = None,
+ image_embeds: torch.Tensor | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ position_ids: torch.Tensor | None = None,
+ labels: torch.LongTensor | None = None,
+ use_cache: bool | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | Kosmos2ForConditionalGenerationModelOutput:
+ r"""
+ image_embeds_position_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Mask to indicate the location in a sequence to insert the image features . Mask values selected in `[0,
+ 1]`:
+
+ - 1 for places where to put the image features,
+ - 0 for places that are not for image features (i.e. for text tokens).
+ image_embeds (`torch.FloatTensor` of shape `(batch_size, latent_query_num, hidden_size)`, *optional*):
+ Sequence of hidden-states at the output of `Kosmos2ImageToTextProjection`.
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
+ `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
+ ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
+
+ Examples:
+
+ ```python
+ >>> from PIL import Image
+ >>> import httpx
+ >>> from io import BytesIO
+ >>> from transformers import AutoProcessor, Kosmos2ForConditionalGeneration
+
+ >>> model = Kosmos2ForConditionalGeneration.from_pretrained("microsoft/kosmos-2-patch14-224")
+ >>> processor = AutoProcessor.from_pretrained("microsoft/kosmos-2-patch14-224")
+
+ >>> url = "https://huggingface.co/microsoft/kosmos-2-patch14-224/resolve/main/snowman.jpg"
+ >>> with httpx.stream("GET", url) as response:
+ ... image = Image.open(BytesIO(response.read()))
+
+ >>> prompt = " An image of"
+
+ >>> inputs = processor(text=prompt, images=image, return_tensors="pt")
+
+ >>> generated_ids = model.generate(
+ ... pixel_values=inputs["pixel_values"],
+ ... input_ids=inputs["input_ids"],
+ ... attention_mask=inputs["attention_mask"],
+ ... image_embeds=None,
+ ... image_embeds_position_mask=inputs["image_embeds_position_mask"],
+ ... use_cache=True,
+ ... max_new_tokens=64,
+ ... )
+ >>> generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
+ >>> processed_text = processor.post_process_generation(generated_text, cleanup_and_extract=False)
+ >>> processed_text
+ ' An image of a snowman warming himself by a fire.'
+
+ >>> caption, entities = processor.post_process_generation(generated_text)
+ >>> caption
+ 'An image of a snowman warming himself by a fire.'
+
+ >>> entities
+ [('a snowman', (12, 21), [(0.390625, 0.046875, 0.984375, 0.828125)]), ('a fire', (41, 47), [(0.171875, 0.015625, 0.484375, 0.890625)])]
+ ```"""
+ vision_model_output = None
+ projection_attentions = None
+ if image_embeds is None:
+ if pixel_values is None:
+ raise ValueError("You have to specify either `pixel_values` or `image_embeds`.")
+
+ vision_model_output = self.vision_model(
+ pixel_values=pixel_values,
+ )
+ # The whole `last_hidden_state` through `post_layernorm` instead of just `pooled_output`.
+ image_embeds = self.vision_model.model.post_layernorm(vision_model_output[0])
+ # normalized features
+ image_embeds = nn.functional.normalize(image_embeds, dim=-1)
+ image_embeds, projection_attentions = self.image_to_text_projection(image_embeds)
+
+ lm_outputs: CausalLMOutputWithCrossAttentions = self.text_model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ image_embeds=image_embeds,
+ image_embeds_position_mask=image_embeds_position_mask,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ position_ids=position_ids,
+ labels=labels,
+ use_cache=use_cache,
+ logits_to_keep=logits_to_keep,
+ **kwargs,
+ )
+
+ return Kosmos2ForConditionalGenerationModelOutput(
+ loss=lm_outputs.loss,
+ logits=lm_outputs.logits,
+ past_key_values=lm_outputs.past_key_values,
+ hidden_states=lm_outputs.hidden_states,
+ attentions=lm_outputs.attentions,
+ image_embeds=image_embeds,
+ projection_attentions=projection_attentions,
+ vision_model_output=vision_model_output,
+ )
+
+ @torch.no_grad()
+ def generate(
+ self,
+ pixel_values: torch.Tensor | None = None,
+ image_embeds_position_mask: torch.Tensor | None = None,
+ input_ids: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ image_embeds: torch.Tensor | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ **kwargs,
+ ):
+ # in order to allow `inputs` argument (as in `GenerationMixin`)
+ inputs = kwargs.pop("inputs", None)
+ if pixel_values is not None and inputs is not None:
+ raise ValueError(
+ f"`inputs`: {inputs} were passed alongside `pixel_values` which is not allowed."
+ f"Make sure to either pass `inputs` or pixel_values=..."
+ )
+ if pixel_values is None and inputs is not None:
+ pixel_values = inputs
+
+ if image_embeds is None:
+ vision_model_output = self.vision_model(pixel_values)
+ # The whole `last_hidden_state` through `post_layernorm` instead of just `pooled_output`.
+ image_embeds = self.vision_model.model.post_layernorm(vision_model_output[0])
+ # normalized features
+ image_embeds = nn.functional.normalize(image_embeds, dim=-1)
+ image_embeds, projection_attentions = self.image_to_text_projection(image_embeds)
+
+ output = self.text_model.generate(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ image_embeds=image_embeds,
+ image_embeds_position_mask=image_embeds_position_mask,
+ inputs_embeds=inputs_embeds,
+ **kwargs,
+ )
+
+ return output
+
+
+__all__ = ["Kosmos2ForConditionalGeneration", "Kosmos2Model", "Kosmos2PreTrainedModel"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/kosmos2/processing_kosmos2.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/kosmos2/processing_kosmos2.py
new file mode 100644
index 0000000000000000000000000000000000000000..fbd8abb9ea9f7e25c0a93985b90cc4baca676a30
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/kosmos2/processing_kosmos2.py
@@ -0,0 +1,677 @@
+# Copyright 2023 Microsoft Research and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Processor class for KOSMOS-2."""
+
+import copy
+import math
+import re
+
+from ...image_processing_utils import BatchFeature
+from ...image_utils import ImageInput
+from ...processing_utils import ImagesKwargs, ProcessingKwargs, ProcessorMixin, TextKwargs, Unpack
+from ...tokenization_python import AddedToken
+from ...tokenization_utils_base import BatchEncoding, TextInput
+from ...utils import auto_docstring
+
+
+BboxInput = (
+ list[tuple[int, int]]
+ | list[tuple[float, float, float, float]]
+ | list[list[tuple[int, int]]]
+ | list[list[tuple[float, float, float]]]
+)
+
+
+NestedList = list[tuple | None | list[tuple | None | list[tuple | None | list[tuple | None]]]]
+
+
+class Kosmos2ImagesKwargs(ImagesKwargs, total=False):
+ """
+ bboxes (`Union[list[tuple[int]], list[tuple[float]], list[list[tuple[int]]], list[list[tuple[float]]]]`, *optional*):
+ The bounding bboxes associated to `texts`.
+ num_image_tokens (`int`, *optional* defaults to 64):
+ The number of (consecutive) places that are used to mark the placeholders to store image information.
+ This should be the same as `latent_query_num` in the instance of `Kosmos2Config` you are using.
+ first_image_token_id (`int`, *optional*):
+ The token id that will be used for the first place of the subsequence that is reserved to store image
+ information. If unset, will default to `self.tokenizer.unk_token_id + 1`.
+ """
+
+ bboxes: NestedList | None # NOTE: hub validators can't accept `Sequence`
+ num_image_tokens: int
+ first_image_token_id: int | None
+
+
+class Kosmos2TextKwargs(TextKwargs, total=False):
+ """
+ add_eos_token (`bool`, defaults to `False`):
+ Whether or not to include `EOS` token id in the encoding when `add_special_tokens=True`.
+ """
+
+ add_eos_token: bool
+
+
+class Kosmos2ProcessorKwargs(ProcessingKwargs, total=False):
+ text_kwargs: Kosmos2TextKwargs
+ images_kwargs: Kosmos2ImagesKwargs
+ _defaults = {
+ "text_kwargs": {
+ "add_special_tokens": True,
+ "padding": False,
+ "stride": 0,
+ "return_overflowing_tokens": False,
+ "return_special_tokens_mask": False,
+ "return_offsets_mapping": False,
+ "return_token_type_ids": False,
+ "verbose": True,
+ "add_eos_token": False,
+ },
+ "images_kwargs": {
+ "num_image_tokens": 64,
+ },
+ }
+
+
+@auto_docstring
+class Kosmos2Processor(ProcessorMixin):
+ def __init__(self, image_processor, tokenizer, num_patch_index_tokens=1024, *kwargs):
+ r"""
+ num_patch_index_tokens (`int`, *optional*, defaults to 1024):
+ The number of tokens that represent patch indices.
+ """
+ tokenizer.return_token_type_ids = False
+
+ self.eod_token = ""
+
+ self.boi_token = ""
+ self.eoi_token = ""
+
+ self.eoc_token = ""
+ self.eol_token = ""
+
+ self.bop_token = ""
+ self.eop_token = ""
+
+ self.boo_token = ""
+
+ self.dom_token = ""
+
+ self.grd_token = ""
+
+ self.tag_tokens = [
+ self.eod_token,
+ self.boi_token,
+ self.eoi_token,
+ self.eoc_token,
+ self.eol_token,
+ self.bop_token,
+ self.eop_token,
+ self.boo_token,
+ self.eoo_token,
+ self.dom_token,
+ self.grd_token,
+ ]
+
+ self.num_patch_index_tokens = num_patch_index_tokens
+ patch_index_tokens = [f"" for x in range(self.num_patch_index_tokens)]
+
+ tokens_to_add = []
+ for token in self.tag_tokens + patch_index_tokens:
+ tokens_to_add.append(AddedToken(token, lstrip=True, rstrip=False, normalized=False))
+ tokenizer.add_tokens(tokens_to_add)
+
+ super().__init__(image_processor, tokenizer)
+
+ @auto_docstring
+ def __call__(
+ self,
+ images: ImageInput | None = None,
+ text: TextInput | list[TextInput] = None,
+ **kwargs: Unpack[Kosmos2ProcessorKwargs],
+ ) -> BatchFeature:
+ if images is None and text is None:
+ raise ValueError("You have to specify either images or text.")
+
+ output_kwargs = self._merge_kwargs(
+ Kosmos2ProcessorKwargs,
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
+ **kwargs,
+ )
+
+ bboxes = output_kwargs["images_kwargs"].pop("bboxes", None)
+ num_image_tokens = output_kwargs["images_kwargs"].pop("num_image_tokens", 64)
+ first_image_token_id = output_kwargs["images_kwargs"].pop("first_image_token_id", None)
+ add_eos_token = output_kwargs["text_kwargs"].pop("add_eos_token", False)
+
+ add_special_tokens = output_kwargs["text_kwargs"]["add_special_tokens"]
+ padding = output_kwargs["text_kwargs"]["padding"]
+ return_tensors = output_kwargs["text_kwargs"].setdefault("return_tensors", None)
+
+ encoding = BatchFeature()
+
+ if images is not None:
+ image_encoding = self.image_processor(images, **output_kwargs["images_kwargs"])
+ encoding.update(image_encoding)
+
+ if text is not None:
+ text = self.preprocess_examples(text, images, bboxes, num_image_tokens=num_image_tokens)
+
+ if add_special_tokens and not add_eos_token:
+ if isinstance(text, str):
+ text = f"{self.tokenizer.bos_token}{text}"
+ elif isinstance(text, list):
+ text = [f"{self.tokenizer.bos_token}{s}" for s in text]
+ output_kwargs["text_kwargs"]["add_special_tokens"] = (
+ output_kwargs["text_kwargs"]["add_special_tokens"] and add_eos_token
+ )
+ output_kwargs["text_kwargs"]["padding"] = padding if images is None else False
+ output_kwargs["text_kwargs"]["return_tensors"] = return_tensors if images is None else None
+ text_encoding = self.tokenizer(text=text, **output_kwargs["text_kwargs"])
+ encoding.update(text_encoding)
+
+ output_kwargs["text_kwargs"]["add_special_tokens"] = add_special_tokens
+ output_kwargs["text_kwargs"]["padding"] = padding
+ output_kwargs["text_kwargs"]["return_tensors"] = return_tensors
+
+ if text is not None and images is not None:
+ # Use the id of the first token after
+ if first_image_token_id is None:
+ first_image_token_id = self.tokenizer.unk_token_id + 1
+
+ # To see if we need one more `0` (for ``) at the beginning of `image_embeds_position_mask`.
+ with_bos = add_special_tokens
+
+ # The first (actual) `` token is always at the 1st or 2nd place (after `` if any). Here we look
+ # for the second `` token (which indicate the first image token).
+ start_index = int(with_bos) + 1
+
+ # Add `image_embeds_position_mask`: the leading and trailing `0` are for `boi` and `eoi` tokens. The `1` indicates
+ # the places of image tokens.
+ image_token_ids = list(range(first_image_token_id, first_image_token_id + num_image_tokens))
+ base_image_embeds_position_mask = [0] + [1] * num_image_tokens + [0]
+
+ # loop over `encoding["input_ids"]`
+ input_ids = []
+ image_embeds_position_mask = []
+ all_input_ids = encoding["input_ids"]
+ # not batched -> (changed to) batch of size 1
+ if isinstance(text, str):
+ all_input_ids = [all_input_ids]
+ encoding["attention_mask"] = [encoding["attention_mask"]]
+ for text_ids in all_input_ids:
+ # change the ids for the fake `` tokens in `input_ids`
+ text_ids = text_ids[:start_index] + image_token_ids + text_ids[start_index + num_image_tokens :]
+ input_ids.append(text_ids)
+
+ mask = copy.copy(base_image_embeds_position_mask)
+ if with_bos:
+ # for ``
+ mask = [0] + mask
+ # trailing part (which are not related to the image)
+ mask += [0] * (len(text_ids) - len(mask))
+ image_embeds_position_mask.append(mask)
+
+ if isinstance(text, list):
+ sorted_length = sorted(
+ [(idx, len(x)) for idx, x in enumerate(text_encoding.input_ids)], key=lambda x: x[-1]
+ )
+ _, min_len_not_padded = sorted_length[0]
+ idx, _ = sorted_length[-1]
+ output_kwargs["text_kwargs"]["add_special_tokens"] = (
+ output_kwargs["text_kwargs"]["add_special_tokens"] and add_eos_token
+ )
+ output_kwargs["text_kwargs"]["return_tensors"] = None
+
+ text_encoding = self.tokenizer(text=[text[idx]], **output_kwargs["text_kwargs"])
+ max_len_padded = len(text_encoding.input_ids[0])
+
+ if min_len_not_padded != max_len_padded:
+ if self.tokenizer.padding_side == "right":
+ input_ids = [x + [self.tokenizer.pad_token_id] * (max_len_padded - len(x)) for x in input_ids]
+ image_embeds_position_mask = [
+ x + [0] * (max_len_padded - len(x)) for x in image_embeds_position_mask
+ ]
+ encoding["attention_mask"] = [
+ x + [0] * (max_len_padded - len(x)) for x in encoding["attention_mask"]
+ ]
+ elif self.tokenizer.padding_side == "left":
+ input_ids = [[self.tokenizer.pad_token_id] * (max_len_padded - len(x)) + x for x in input_ids]
+ image_embeds_position_mask = [
+ [0] * (max_len_padded - len(x)) + x for x in image_embeds_position_mask
+ ]
+ encoding["attention_mask"] = [
+ [0] * (max_len_padded - len(x)) + x for x in encoding["attention_mask"]
+ ]
+
+ # un-batch if necessary
+ if isinstance(text, str) and return_tensors is None:
+ input_ids = input_ids[0]
+ encoding["attention_mask"] = encoding["attention_mask"][0]
+ image_embeds_position_mask = image_embeds_position_mask[0]
+
+ # update (with the target tensor type if specified)
+ encoding.update(
+ BatchEncoding(
+ data={
+ "input_ids": input_ids,
+ "attention_mask": encoding["attention_mask"],
+ "image_embeds_position_mask": image_embeds_position_mask,
+ },
+ tensor_type=return_tensors,
+ )
+ )
+
+ return encoding
+
+ def _check_bboxes_for_single_text(self, bboxes):
+ """
+ Check `bboxes` for a single text example. It could be
+ - `None`: no bounding box associated to a text.
+ - A list with each element being the bounding boxes associated to one ` ... ` pair found
+ in a text. This could be:
+ - `None`: no bounding box associated to a ` ... ` pair.
+ - A tuple of 2 integers: A single bounding box specified by patch indices.
+ - A tuple of 4 float point number: A single bounding box specified by (normalized) coordinates.
+ - A list containing the above 2 tuple types: Multiple bounding boxes for a
+ ` ... ` pair.
+ """
+ if bboxes is None:
+ return
+ elif not isinstance(bboxes, list):
+ raise ValueError("`bboxes` (for a single text example) should be `None` or a list.")
+
+ # `bbox` is the bounding boxes for a single pair
+ for bbox in bboxes:
+ if bbox is None:
+ continue
+ elif not isinstance(bbox, list):
+ bbox = [bbox]
+ for element in bbox:
+ if not isinstance(element, tuple) or not (
+ (len(element) == 2 and all(isinstance(x, int) for x in element))
+ or (len(element) == 4 and all(isinstance(x, float) for x in element))
+ ):
+ raise ValueError(
+ "Each element in `bboxes` (for a single text example) should be either `None`, a tuple containing "
+ "2 integers or 4 float point numbers, or a list containing such tuples. Also "
+ "make sure the arguments `texts` and `bboxes` passed to `preprocess_text` are both in "
+ "batches or both for a single example."
+ )
+
+ def _preprocess_single_example(self, text, image, bboxes, img_info_tokens):
+ text = text.strip()
+ if image is not None:
+ # Add ` ... (fake) image tokens ... `
+ text = f"{img_info_tokens} {text}"
+
+ # Add `` after ` phrase text `
+ text = self._insert_patch_index_tokens(text, bboxes)
+ return text
+
+ def preprocess_examples(
+ self,
+ texts: TextInput | list[TextInput],
+ images: ImageInput | None = None,
+ bboxes: BboxInput = None,
+ num_image_tokens: int | None = 64,
+ ) -> str | list[str]:
+ """Add image and bounding box information to `texts` as image and patch index tokens.
+
+ Args:
+ texts (`Union[TextInput, list[TextInput]]`): The texts to be processed.
+ images (`ImageInput`, *optional*): The images associated to `texts`.
+ bboxes (`Union[list[tuple[int]], list[tuple[float]], list[list[tuple[int]]], list[list[tuple[float]]]]`, *optional*):
+ The bounding bboxes associated to `texts`.
+ num_image_tokens (`int`, *optional*, defaults to 64):
+ The number of image tokens (used as latent queries). This should corresponds to the `latent_query_num`
+ attribute in `Kosmos2Config`.
+
+ Returns:
+ `Union[TextInput, list[TextInput]]`: The processed texts with image and patch index tokens.
+ """
+ # These are fake `` tokens enclosed between (the actual) `` token and ``.
+ img_tokens = [self.boi_token] * num_image_tokens
+ img_info_tokens = " ".join([self.boi_token] + img_tokens + [self.eoi_token])
+
+ # make batch to simplify processing logic
+ batched = True
+ if isinstance(texts, str):
+ batched = False
+ texts = [texts]
+
+ if images is None:
+ images = [None] * len(texts)
+ elif not isinstance(images, list):
+ images = [images]
+ if len(texts) != len(images):
+ raise ValueError(
+ f"The number of examples in `texts` and `images` should be the same. Got {len(texts)} v.s. {len(images)} instead."
+ )
+
+ if not batched:
+ self._check_bboxes_for_single_text(bboxes)
+ bboxes = [bboxes]
+ elif bboxes is not None:
+ if not isinstance(bboxes, list):
+ raise ValueError("`bboxes` should be `None` or a list (as a batch) when `texts` is passed as a batch.")
+ for x in bboxes:
+ self._check_bboxes_for_single_text(x)
+ else:
+ bboxes = [None] * len(texts)
+
+ if len(bboxes) != len(texts):
+ raise ValueError(
+ f"The number of examples in `texts` and `bboxes` should be the same. Got {len(texts)} v.s. {len(bboxes)} instead."
+ )
+
+ result = [
+ self._preprocess_single_example(text, image, bbox, img_info_tokens)
+ for text, image, bbox in zip(texts, images, bboxes)
+ ]
+ # un-batch if necessary
+ if not batched:
+ result = result[0]
+
+ return result
+
+ def post_process_generation(self, text, cleanup_and_extract=True):
+ caption = text.split(self.eoi_token)[-1]
+ if cleanup_and_extract:
+ return clean_text_and_extract_entities_with_bboxes(caption)
+ return caption
+
+ def post_process_image_text_to_text(self, generated_outputs, skip_special_tokens=True, **kwargs):
+ """
+ Post-process the output of the model to decode the text.
+
+ Args:
+ generated_outputs (`torch.Tensor` or `np.ndarray`):
+ The output of the model `generate` function. The output is expected to be a tensor of shape `(batch_size, sequence_length)`
+ or `(sequence_length,)`.
+ skip_special_tokens (`bool`, *optional*, defaults to `True`):
+ Whether or not to remove special tokens in the output. Argument passed to the tokenizer's `batch_decode` method.
+ **kwargs:
+ Additional arguments to be passed to the tokenizer's `batch_decode method`.
+
+ Returns:
+ `list[str]`: The decoded text.
+ """
+ generated_texts = self.batch_decode(generated_outputs, skip_special_tokens=skip_special_tokens, **kwargs)
+ return [self.post_process_generation(text, cleanup_and_extract=False) for text in generated_texts]
+
+ @property
+ def model_input_names(self):
+ tokenizer_input_names = self.tokenizer.model_input_names
+ image_processor_input_names = self.image_processor.model_input_names
+ return tokenizer_input_names + image_processor_input_names + ["image_embeds_position_mask"]
+
+ def _insert_patch_index_tokens(self, text: str, bboxes: list[tuple[int]] | list[tuple[float]]) -> str:
+ if bboxes is None or len(bboxes) == 0:
+ return text
+
+ matched_phrases = list(re.finditer(r".+?", string=text))
+ if len(matched_phrases) != len(bboxes):
+ raise ValueError(
+ f"The number of elements in `bboxes` should be the same as the number of ` ... ` pairs in `text`. Got {len(matched_phrases)} v.s. {len(bboxes)} instead."
+ )
+
+ # insert object's patch index tokens
+ # the found ` ... ` pairs.
+ curr_pos = 0
+ buffer = []
+ for matched, bbox in zip(matched_phrases, bboxes):
+ _, end = matched.span()
+ buffer.append(text[curr_pos:end])
+ curr_pos = end
+ # A phrase without bbox
+ if bbox is None:
+ continue
+ # A phrase with a single bbox
+ if isinstance(bbox, tuple):
+ bbox = [bbox]
+ patch_index_strings = []
+ # A phrase could have multiple bboxes
+ if not all(box is not None for box in bbox):
+ raise ValueError(
+ "The multiple bounding boxes for a single phrase should not contain any `None` value."
+ )
+ for box in bbox:
+ patch_index_1, patch_index_2 = self._convert_bbox_to_patch_index_tokens(box)
+ patch_index_strings.append(f"{patch_index_1} {patch_index_2}")
+ # `bbox` being an empty list
+ if len(patch_index_strings) == 0:
+ continue
+ position_str = " ".join(patch_index_strings)
+ buffer.append(f"")
+ # remaining
+ if curr_pos < len(text):
+ buffer.append(text[curr_pos:])
+
+ text = "".join(buffer)
+ return text
+
+ def _convert_bbox_to_patch_index_tokens(
+ self, bbox: tuple[int, int] | tuple[float, float, float, float]
+ ) -> tuple[str, str]:
+ # already computed patch indices
+ if len(bbox) == 2:
+ idx_1, idx_2 = bbox
+ # bbox specified with (normalized) coordinates
+ else:
+ # use `self.tokenizer` to get `num_patches_per_side`
+ num_patches_per_side = int(math.sqrt(self.num_patch_index_tokens))
+ idx_1, idx_2 = coordinate_to_patch_index(bbox, num_patches_per_side)
+
+ token_1 = f""
+ token_2 = f""
+
+ return token_1, token_2
+
+
+def coordinate_to_patch_index(bbox: tuple[float, float, float, float], num_patches_per_side: int) -> tuple[int, int]:
+ """Convert a bounding box to a pair of patch indices.
+
+ Args:
+ bbox (`tuple[float, float, float, float]`):
+ The 4 coordinates of the bounding box, with the format being (x1, y1, x2, y2) specifying the upper-left and
+ lower-right corners of the box. It should have x2 > x1 and y2 > y1.
+ num_patches_per_side (`int`): the number of patches along each side.
+
+ Returns:
+ `tuple[int, int]`: A pair of patch indices representing the upper-left patch and lower-right patch.
+ """
+ (x1, y1, x2, y2) = bbox
+
+ if not (x2 > x1 and y2 > y1):
+ raise ValueError("The coordinates in `bbox` should be `(x1, y1, x2, y2)` with `x2 > x1` and `y2 > y1`.")
+
+ ul_x = math.floor(x1 * num_patches_per_side)
+ ul_y = math.floor(y1 * num_patches_per_side)
+
+ lr_x = math.ceil(x2 * num_patches_per_side - 1)
+ lr_y = math.ceil(y2 * num_patches_per_side - 1)
+
+ ul_idx = ul_y * num_patches_per_side + ul_x
+ lr_idx = lr_y * num_patches_per_side + lr_x
+
+ return ul_idx, lr_idx
+
+
+# copied from https://github.com/microsoft/unilm/blob/97e4923e97d3ee10b57e97013556e3fd0d207a9b/kosmos-2/demo/decode_string.py#L35C1-L75C38
+# (with format modifications)
+def patch_index_to_coordinate(ul_idx: int, lr_idx: int, num_patches_per_side: int):
+ """
+ Given a grid of length `num_patches_per_side` and the indices of the upper-left and lower-right corners of a
+ bounding box, returns the normalized coordinates of the bounding box, in the form (x1, y1, x2, y2).
+
+ Args:
+ ul_idx (`int`): the index of the grid cell that corresponds to the upper-left corner of the bounding box.
+ lr_idx (`int`): the index of the grid cell that corresponds to the lower-right corner of the bounding box.
+ num_patches_per_side (`int`): the number of patches along each side.
+
+ Returns:
+ `tuple[float]`: the normalized coordinates of the bounding box, in the form (x1, y1, x2, y2).
+ """
+ # Compute the size of each cell in the grid
+ cell_size = 1.0 / num_patches_per_side
+
+ # Compute the x and y indices of the upper-left and lower-right corners of the bounding box
+ ul_x = ul_idx % num_patches_per_side
+ ul_y = ul_idx // num_patches_per_side
+
+ lr_x = lr_idx % num_patches_per_side
+ lr_y = lr_idx // num_patches_per_side
+
+ # Compute the normalized coordinates of the bounding box
+ if ul_idx == lr_idx:
+ x1 = ul_x * cell_size
+ y1 = ul_y * cell_size
+ x2 = lr_x * cell_size + cell_size
+ y2 = lr_y * cell_size + cell_size
+ elif ul_x == lr_x or ul_y == lr_y:
+ x1 = ul_x * cell_size
+ y1 = ul_y * cell_size
+ x2 = lr_x * cell_size + cell_size
+ y2 = lr_y * cell_size + cell_size
+ else:
+ x1 = ul_x * cell_size + cell_size / 2
+ y1 = ul_y * cell_size + cell_size / 2
+ x2 = lr_x * cell_size + cell_size / 2
+ y2 = lr_y * cell_size + cell_size / 2
+
+ return x1, y1, x2, y2
+
+
+# copied from https://github.com/microsoft/unilm/blob/97e4923e97d3ee10b57e97013556e3fd0d207a9b/kosmos-2/demo/decode_string.py#L4-L33
+# (with format modifications)
+def extract_entities_with_patch_indices(text):
+ """Extract entities contained in `text`. The bounding bboxes is given in the form of patch indices.
+
+ This function is only intended to be used within `clean_text_and_extract_entities_with_bboxes` where further
+ processing happens, including converting to normalized coordinates and whitespace character cleaning up.
+
+ Examples:
+
+ ```python
+ >>> text = " An image of a snowman warming himself by a fire."
+ >>> entities = extract_entities_with_patch_indices(text)
+ >>> entities
+ [(' a snowman', (31, 41), [(44, 863)]), (' a fire', (130, 137), [(5, 911)])]
+ ```"""
+ # The regular expression pattern for matching the required formats
+ pattern = r"(?:(([^<]+)))?"
+
+ # Find all matches in the given string
+ matches = re.finditer(pattern, text)
+
+ # Initialize an empty list to store the valid patch_index combinations
+ entities_with_patch_indices = []
+
+ for match in matches:
+ # span of a `phrase` that is between and
+ span = match.span(2)
+ phrase_tag, phrase, match_content = match.groups()
+ if not phrase_tag:
+ phrase = None
+ # We take the starting position of `"`):
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
+ sequence classification or for a text and a question for question answering. It is also used as the last
+ token of a sequence built with special tokens.
+ cls_token (`str`, *optional*, defaults to `""`):
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
+ unk_token (`str`, *optional*, defaults to `""`):
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
+ token instead.
+ pad_token (`str`, *optional*, defaults to `""`):
+ The token used for padding, for example when batching sequences of different lengths.
+ mask_token (`str`, *optional*, defaults to `""`):
+ The token used for masking values. This is the token used when training this model with masked language
+ modeling. This is the token which the model will try to predict.
+ add_prefix_space (`bool`, *optional*, defaults to `False`):
+ Whether or not to add an initial space to the input. This allows to treat the leading word just as any
+ other word. (RoBERTa tokenizer detect beginning of words by the preceding space).
+ """
+
+ vocab_files_names = VOCAB_FILES_NAMES
+ model_input_names = ["input_ids", "token_type_ids", "attention_mask"]
+ model = BPE
+
+ def __init__(
+ self,
+ tags_dict,
+ vocab: str | dict[str, int] | list[tuple[str, float]] | None = None,
+ merges: str | list[str] | None = None,
+ errors="replace",
+ bos_token="",
+ eos_token="",
+ sep_token="",
+ cls_token="",
+ unk_token="",
+ pad_token="",
+ mask_token="",
+ add_prefix_space=False,
+ max_depth=50,
+ max_width=1000,
+ pad_width=1001,
+ pad_token_label=-100,
+ only_label_first_subword=True,
+ trim_offsets=False,
+ **kwargs,
+ ):
+ bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token
+ eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
+ sep_token = AddedToken(sep_token, lstrip=False, rstrip=False) if isinstance(sep_token, str) else sep_token
+ cls_token = AddedToken(cls_token, lstrip=False, rstrip=False) if isinstance(cls_token, str) else cls_token
+ unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token
+ pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token
+ # Mask token behave like a normal word, i.e. include the space before it
+ mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token
+
+ if vocab is None:
+ vocab = {
+ str(pad_token): 0,
+ str(unk_token): 1,
+ str(cls_token): 2,
+ str(sep_token): 3,
+ str(mask_token): 4,
+ }
+ merges = merges or []
+ tokenizer = Tokenizer(
+ BPE(
+ vocab=vocab,
+ merges=merges,
+ dropout=None,
+ continuing_subword_prefix="",
+ end_of_word_suffix="",
+ fuse_unk=False,
+ )
+ )
+ tokenizer.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=add_prefix_space)
+ tokenizer.decoder = decoders.ByteLevel()
+ self._vocab = vocab
+ self._merges = merges
+ self._tokenizer = tokenizer
+ super().__init__(
+ tags_dict=tags_dict,
+ errors=errors,
+ bos_token=bos_token,
+ eos_token=eos_token,
+ unk_token=unk_token,
+ sep_token=sep_token,
+ cls_token=cls_token,
+ pad_token=pad_token,
+ mask_token=mask_token,
+ add_prefix_space=add_prefix_space,
+ trim_offsets=trim_offsets,
+ max_depth=max_depth,
+ max_width=max_width,
+ pad_width=pad_width,
+ pad_token_label=pad_token_label,
+ only_label_first_subword=only_label_first_subword,
+ **kwargs,
+ )
+ sep_token_str = str(sep_token)
+ cls_token_str = str(cls_token)
+ cls_token_id = self.cls_token_id
+ sep_token_id = self.sep_token_id
+ self._tokenizer.post_processor = processors.TemplateProcessing(
+ single=f"{cls_token_str} $A {sep_token_str}",
+ pair=f"{cls_token_str} $A {sep_token_str} $B {sep_token_str}",
+ special_tokens=[
+ (cls_token_str, cls_token_id),
+ (sep_token_str, sep_token_id),
+ ],
+ )
+
+ self.tags_dict = tags_dict
+
+ # additional properties
+ self.max_depth = max_depth
+ self.max_width = max_width
+ self.pad_width = pad_width
+ self.unk_tag_id = len(self.tags_dict)
+ self.pad_tag_id = self.unk_tag_id + 1
+ self.pad_xpath_tags_seq = [self.pad_tag_id] * self.max_depth
+ self.pad_xpath_subs_seq = [self.pad_width] * self.max_depth
+ self.pad_token_label = pad_token_label
+ self.only_label_first_subword = only_label_first_subword
+
+ def get_xpath_seq(self, xpath):
+ """
+ Given the xpath expression of one particular node (like "/html/body/div/li[1]/div/span[2]"), return a list of
+ tag IDs and corresponding subscripts, taking into account max depth.
+ """
+ xpath_tags_list = []
+ xpath_subs_list = []
+
+ xpath_units = xpath.split("/")
+ for unit in xpath_units:
+ if not unit.strip():
+ continue
+ name_subs = unit.strip().split("[")
+ tag_name = name_subs[0]
+ sub = 0 if len(name_subs) == 1 else int(name_subs[1][:-1])
+ xpath_tags_list.append(self.tags_dict.get(tag_name, self.unk_tag_id))
+ xpath_subs_list.append(min(self.max_width, sub))
+
+ xpath_tags_list = xpath_tags_list[: self.max_depth]
+ xpath_subs_list = xpath_subs_list[: self.max_depth]
+ xpath_tags_list += [self.pad_tag_id] * (self.max_depth - len(xpath_tags_list))
+ xpath_subs_list += [self.pad_width] * (self.max_depth - len(xpath_subs_list))
+
+ return xpath_tags_list, xpath_subs_list
+
+ @add_end_docstrings(ENCODE_KWARGS_DOCSTRING, MARKUPLM_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
+ def __call__(
+ self,
+ text: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput],
+ text_pair: PreTokenizedInput | list[PreTokenizedInput] | None = None,
+ xpaths: list[list[int]] | list[list[list[int]]] | None = None,
+ node_labels: list[int] | list[list[int]] | None = None,
+ add_special_tokens: bool = True,
+ padding: bool | str | PaddingStrategy = False,
+ truncation: bool | str | TruncationStrategy = None,
+ max_length: int | None = None,
+ stride: int = 0,
+ is_split_into_words: bool = False,
+ pad_to_multiple_of: int | None = None,
+ padding_side: str | None = None,
+ return_tensors: str | TensorType | None = None,
+ return_token_type_ids: bool | None = None,
+ return_attention_mask: bool | None = None,
+ return_overflowing_tokens: bool = False,
+ return_special_tokens_mask: bool = False,
+ return_offsets_mapping: bool = False,
+ return_length: bool = False,
+ verbose: bool = True,
+ **kwargs,
+ ) -> BatchEncoding:
+ """
+ Main method to tokenize and prepare for the model one or several sequence(s) or one or several pair(s) of
+ sequences with nodes, xpaths and optional labels.
+
+ Args:
+ text (`str`, `list[str]`, `list[list[str]]`):
+ The sequence or batch of sequences to be encoded. Each sequence can be a string, a list of strings
+ (words of a single example or questions of a batch of examples) or a list of list of strings (batch of
+ words).
+ text_pair (`list[str]`, `list[list[str]]`):
+ The sequence or batch of sequences to be encoded. Each sequence should be a list of strings
+ (pretokenized string).
+ xpaths (`list[list[int]]`, `list[list[list[int]]]`):
+ Node-level xpaths. Each bounding box should be normalized to be on a 0-1000 scale.
+ node_labels (`list[int]`, `list[list[int]]`, *optional*):
+ Node-level integer labels (for token classification tasks).
+ is_split_into_words (`bool`, *optional*):
+ Set to `True` if the inputs are already provided as pretokenized word lists.
+ """
+
+ placeholder_xpath = "/document/node"
+
+ if isinstance(text, tuple):
+ text = list(text)
+ if text_pair is not None and isinstance(text_pair, tuple):
+ text_pair = list(text_pair)
+
+ if xpaths is None and not is_split_into_words:
+ nodes_source = text if text_pair is None else text_pair
+ if isinstance(nodes_source, tuple):
+ nodes_source = list(nodes_source)
+ processed_nodes = nodes_source
+
+ if isinstance(nodes_source, str):
+ processed_nodes = nodes_source.split()
+ elif isinstance(nodes_source, list):
+ if nodes_source and isinstance(nodes_source[0], str):
+ requires_split = any(" " in entry for entry in nodes_source)
+ if requires_split:
+ processed_nodes = [entry.split() for entry in nodes_source]
+ else:
+ processed_nodes = nodes_source
+ elif nodes_source and isinstance(nodes_source[0], tuple):
+ processed_nodes = [list(sample) for sample in nodes_source]
+
+ if text_pair is None:
+ text = processed_nodes
+ else:
+ text_pair = processed_nodes
+
+ if isinstance(processed_nodes, list) and processed_nodes and isinstance(processed_nodes[0], (list, tuple)):
+ xpaths = [[placeholder_xpath] * len(sample) for sample in processed_nodes]
+ else:
+ length = len(processed_nodes) if hasattr(processed_nodes, "__len__") else 0
+ xpaths = [placeholder_xpath] * length
+
+ def _is_valid_text_input(t):
+ if isinstance(t, str):
+ return True
+ if isinstance(t, (list, tuple)):
+ if len(t) == 0:
+ return True
+ if isinstance(t[0], str):
+ return True
+ if isinstance(t[0], (list, tuple)):
+ return len(t[0]) == 0 or isinstance(t[0][0], str)
+ return False
+
+ if text_pair is not None:
+ # in case text + text_pair are provided, text = questions, text_pair = nodes
+ if not _is_valid_text_input(text):
+ raise ValueError("text input must of type `str` (single example) or `list[str]` (batch of examples). ")
+ if not isinstance(text_pair, (list, tuple)):
+ raise ValueError(
+ "Nodes must be of type `list[str]` (single pretokenized example), "
+ "or `list[list[str]]` (batch of pretokenized examples)."
+ )
+ is_batched = isinstance(text, (list, tuple))
+ else:
+ # in case only text is provided => must be nodes
+ if not isinstance(text, (list, tuple)):
+ raise ValueError(
+ "Nodes must be of type `list[str]` (single pretokenized example), "
+ "or `list[list[str]]` (batch of pretokenized examples)."
+ )
+ is_batched = isinstance(text, (list, tuple)) and text and isinstance(text[0], (list, tuple))
+
+ nodes = text if text_pair is None else text_pair
+ assert xpaths is not None, "You must provide corresponding xpaths"
+ if is_batched:
+ assert len(nodes) == len(xpaths), "You must provide nodes and xpaths for an equal amount of examples"
+ for nodes_example, xpaths_example in zip(nodes, xpaths):
+ assert len(nodes_example) == len(xpaths_example), "You must provide as many nodes as there are xpaths"
+ else:
+ assert len(nodes) == len(xpaths), "You must provide as many nodes as there are xpaths"
+
+ if is_batched:
+ if text_pair is not None and len(text) != len(text_pair):
+ raise ValueError(
+ f"batch length of `text`: {len(text)} does not match batch length of `text_pair`:"
+ f" {len(text_pair)}."
+ )
+ batch_text_or_text_pairs = list(zip(text, text_pair)) if text_pair is not None else text
+ is_pair = bool(text_pair is not None)
+ return self.batch_encode_plus(
+ batch_text_or_text_pairs=batch_text_or_text_pairs,
+ is_pair=is_pair,
+ xpaths=xpaths,
+ node_labels=node_labels,
+ add_special_tokens=add_special_tokens,
+ padding=padding,
+ truncation=truncation,
+ max_length=max_length,
+ stride=stride,
+ pad_to_multiple_of=pad_to_multiple_of,
+ padding_side=padding_side,
+ return_tensors=return_tensors,
+ return_token_type_ids=return_token_type_ids,
+ return_attention_mask=return_attention_mask,
+ return_overflowing_tokens=return_overflowing_tokens,
+ return_special_tokens_mask=return_special_tokens_mask,
+ return_offsets_mapping=return_offsets_mapping,
+ return_length=return_length,
+ verbose=verbose,
+ **kwargs,
+ )
+ else:
+ return self.encode_plus(
+ text=text,
+ text_pair=text_pair,
+ xpaths=xpaths,
+ node_labels=node_labels,
+ add_special_tokens=add_special_tokens,
+ padding=padding,
+ truncation=truncation,
+ max_length=max_length,
+ stride=stride,
+ pad_to_multiple_of=pad_to_multiple_of,
+ padding_side=padding_side,
+ return_tensors=return_tensors,
+ return_token_type_ids=return_token_type_ids,
+ return_attention_mask=return_attention_mask,
+ return_overflowing_tokens=return_overflowing_tokens,
+ return_special_tokens_mask=return_special_tokens_mask,
+ return_offsets_mapping=return_offsets_mapping,
+ return_length=return_length,
+ verbose=verbose,
+ **kwargs,
+ )
+
+ @add_end_docstrings(ENCODE_KWARGS_DOCSTRING, MARKUPLM_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
+ def batch_encode_plus(
+ self,
+ batch_text_or_text_pairs: list[TextInput] | list[TextInputPair] | list[PreTokenizedInput],
+ is_pair: bool | None = None,
+ xpaths: list[list[list[int]]] | None = None,
+ node_labels: list[int] | list[list[int]] | None = None,
+ add_special_tokens: bool = True,
+ padding: bool | str | PaddingStrategy = False,
+ truncation: bool | str | TruncationStrategy = None,
+ max_length: int | None = None,
+ stride: int = 0,
+ pad_to_multiple_of: int | None = None,
+ padding_side: str | None = None,
+ return_tensors: str | TensorType | None = None,
+ return_token_type_ids: bool | None = None,
+ return_attention_mask: bool | None = None,
+ return_overflowing_tokens: bool = False,
+ return_special_tokens_mask: bool = False,
+ return_offsets_mapping: bool = False,
+ return_length: bool = False,
+ verbose: bool = True,
+ **kwargs,
+ ) -> BatchEncoding:
+ # Backward compatibility for 'truncation_strategy', 'pad_to_max_length'
+ padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(
+ padding=padding,
+ truncation=truncation,
+ max_length=max_length,
+ pad_to_multiple_of=pad_to_multiple_of,
+ verbose=verbose,
+ **kwargs,
+ )
+
+ return self._batch_encode_plus(
+ batch_text_or_text_pairs=batch_text_or_text_pairs,
+ is_pair=is_pair,
+ xpaths=xpaths,
+ node_labels=node_labels,
+ add_special_tokens=add_special_tokens,
+ padding_strategy=padding_strategy,
+ truncation_strategy=truncation_strategy,
+ max_length=max_length,
+ stride=stride,
+ pad_to_multiple_of=pad_to_multiple_of,
+ padding_side=padding_side,
+ return_tensors=return_tensors,
+ return_token_type_ids=return_token_type_ids,
+ return_attention_mask=return_attention_mask,
+ return_overflowing_tokens=return_overflowing_tokens,
+ return_special_tokens_mask=return_special_tokens_mask,
+ return_offsets_mapping=return_offsets_mapping,
+ return_length=return_length,
+ verbose=verbose,
+ **kwargs,
+ )
+
+ def tokenize(self, text: str, pair: str | None = None, add_special_tokens: bool = False, **kwargs) -> list[str]:
+ batched_input = [(text, pair)] if pair else [text]
+ encodings = self._tokenizer.encode_batch(
+ batched_input, add_special_tokens=add_special_tokens, is_pretokenized=False, **kwargs
+ )
+
+ return encodings[0].tokens
+
+ @add_end_docstrings(ENCODE_KWARGS_DOCSTRING, MARKUPLM_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
+ def encode_plus(
+ self,
+ text: TextInput | PreTokenizedInput,
+ text_pair: PreTokenizedInput | None = None,
+ xpaths: list[list[int]] | None = None,
+ node_labels: list[int] | None = None,
+ add_special_tokens: bool = True,
+ padding: bool | str | PaddingStrategy = False,
+ truncation: bool | str | TruncationStrategy = None,
+ max_length: int | None = None,
+ stride: int = 0,
+ pad_to_multiple_of: int | None = None,
+ padding_side: str | None = None,
+ return_tensors: str | TensorType | None = None,
+ return_token_type_ids: bool | None = None,
+ return_attention_mask: bool | None = None,
+ return_overflowing_tokens: bool = False,
+ return_special_tokens_mask: bool = False,
+ return_offsets_mapping: bool = False,
+ return_length: bool = False,
+ verbose: bool = True,
+ **kwargs,
+ ) -> BatchEncoding:
+ """
+ Tokenize and prepare for the model a sequence or a pair of sequences. .. warning:: This method is deprecated,
+ `__call__` should be used instead.
+
+ Args:
+ text (`str`, `list[str]`, `list[list[str]]`):
+ The first sequence to be encoded. This can be a string, a list of strings or a list of list of strings.
+ text_pair (`list[str]` or `list[int]`, *optional*):
+ Optional second sequence to be encoded. This can be a list of strings (words of a single example) or a
+ list of list of strings (words of a batch of examples).
+ """
+
+ # Backward compatibility for 'truncation_strategy', 'pad_to_max_length'
+ padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(
+ padding=padding,
+ truncation=truncation,
+ max_length=max_length,
+ pad_to_multiple_of=pad_to_multiple_of,
+ verbose=verbose,
+ **kwargs,
+ )
+
+ return self._encode_plus(
+ text=text,
+ xpaths=xpaths,
+ text_pair=text_pair,
+ node_labels=node_labels,
+ add_special_tokens=add_special_tokens,
+ padding_strategy=padding_strategy,
+ truncation_strategy=truncation_strategy,
+ max_length=max_length,
+ stride=stride,
+ pad_to_multiple_of=pad_to_multiple_of,
+ padding_side=padding_side,
+ return_tensors=return_tensors,
+ return_token_type_ids=return_token_type_ids,
+ return_attention_mask=return_attention_mask,
+ return_overflowing_tokens=return_overflowing_tokens,
+ return_special_tokens_mask=return_special_tokens_mask,
+ return_offsets_mapping=return_offsets_mapping,
+ return_length=return_length,
+ verbose=verbose,
+ **kwargs,
+ )
+
+ def _batch_encode_plus(
+ self,
+ batch_text_or_text_pairs: list[TextInput] | list[TextInputPair] | list[PreTokenizedInput],
+ is_pair: bool | None = None,
+ xpaths: list[list[list[int]]] | None = None,
+ node_labels: list[list[int]] | None = None,
+ add_special_tokens: bool = True,
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
+ truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
+ max_length: int | None = None,
+ stride: int = 0,
+ pad_to_multiple_of: int | None = None,
+ padding_side: str | None = None,
+ return_tensors: str | None = None,
+ return_token_type_ids: bool | None = None,
+ return_attention_mask: bool | None = None,
+ return_overflowing_tokens: bool = False,
+ return_special_tokens_mask: bool = False,
+ return_offsets_mapping: bool = False,
+ return_length: bool = False,
+ verbose: bool = True,
+ ) -> BatchEncoding:
+ if not isinstance(batch_text_or_text_pairs, list):
+ raise TypeError(f"batch_text_or_text_pairs has to be a list (got {type(batch_text_or_text_pairs)})")
+
+ # Set the truncation and padding strategy and restore the initial configuration
+ self.set_truncation_and_padding(
+ padding_strategy=padding_strategy,
+ truncation_strategy=truncation_strategy,
+ max_length=max_length,
+ stride=stride,
+ pad_to_multiple_of=pad_to_multiple_of,
+ padding_side=padding_side,
+ )
+
+ if is_pair:
+ processed_inputs = []
+ for text, text_pair in batch_text_or_text_pairs:
+ if isinstance(text, tuple):
+ text = list(text)
+ if isinstance(text, str):
+ text = [text]
+ if isinstance(text_pair, tuple):
+ text_pair = list(text_pair)
+ if isinstance(text_pair, str):
+ text_pair = [text_pair]
+ processed_inputs.append((text, text_pair))
+ batch_text_or_text_pairs = processed_inputs
+ else:
+ processed_inputs = []
+ for text in batch_text_or_text_pairs:
+ if isinstance(text, tuple):
+ text = list(text)
+ if isinstance(text, str):
+ text = [text]
+ processed_inputs.append(text)
+ batch_text_or_text_pairs = processed_inputs
+
+ encodings = self._tokenizer.encode_batch(
+ batch_text_or_text_pairs,
+ add_special_tokens=add_special_tokens,
+ is_pretokenized=True, # we set this to True as MarkupLM always expects pretokenized inputs
+ )
+
+ # Convert encoding to dict
+ # `Tokens` is a tuple of (list[dict[str, list[list[int]]]] or list[dict[str, 2D-Tensor]],
+ # list[EncodingFast]) with nested dimensions corresponding to batch, overflows, sequence length
+ tokens_and_encodings = [
+ self._convert_encoding(
+ encoding=encoding,
+ return_token_type_ids=return_token_type_ids,
+ return_attention_mask=return_attention_mask,
+ return_overflowing_tokens=return_overflowing_tokens,
+ return_special_tokens_mask=return_special_tokens_mask,
+ return_offsets_mapping=True
+ if node_labels is not None
+ else return_offsets_mapping, # we use offsets to create the labels
+ return_length=return_length,
+ verbose=verbose,
+ )
+ for encoding in encodings
+ ]
+
+ # Convert the output to have dict[list] from list[dict] and remove the additional overflows dimension
+ # From (variable) shape (batch, overflows, sequence length) to ~ (batch * overflows, sequence length)
+ # (we say ~ because the number of overflow varies with the example in the batch)
+ #
+ # To match each overflowing sample with the original sample in the batch
+ # we add an overflow_to_sample_mapping array (see below)
+ sanitized_tokens = {}
+ for key in tokens_and_encodings[0][0]:
+ stack = [e for item, _ in tokens_and_encodings for e in item[key]]
+ sanitized_tokens[key] = stack
+ sanitized_encodings = [e for _, item in tokens_and_encodings for e in item]
+
+ # If returning overflowing tokens, we need to return a mapping
+ # from the batch idx to the original sample
+ if return_overflowing_tokens:
+ overflow_to_sample_mapping = []
+ for i, (toks, _) in enumerate(tokens_and_encodings):
+ overflow_to_sample_mapping += [i] * len(toks["input_ids"])
+ sanitized_tokens["overflow_to_sample_mapping"] = overflow_to_sample_mapping
+
+ for input_ids in sanitized_tokens["input_ids"]:
+ self._eventual_warn_about_too_long_sequence(input_ids, max_length, verbose)
+
+ # create the token-level xpaths tags and subscripts
+ xpath_tags_seq = []
+ xpath_subs_seq = []
+ for batch_index in range(len(sanitized_tokens["input_ids"])):
+ if return_overflowing_tokens:
+ original_index = sanitized_tokens["overflow_to_sample_mapping"][batch_index]
+ else:
+ original_index = batch_index
+ xpath_tags_seq_example = []
+ xpath_subs_seq_example = []
+ for id, sequence_id, word_id in zip(
+ sanitized_tokens["input_ids"][batch_index],
+ sanitized_encodings[batch_index].sequence_ids,
+ sanitized_encodings[batch_index].word_ids,
+ ):
+ if word_id is not None:
+ if is_pair and sequence_id == 0:
+ xpath_tags_seq_example.append(self.pad_xpath_tags_seq)
+ xpath_subs_seq_example.append(self.pad_xpath_subs_seq)
+ else:
+ xpath_tags_list, xpath_subs_list = self.get_xpath_seq(xpaths[original_index][word_id])
+ xpath_tags_seq_example.extend([xpath_tags_list])
+ xpath_subs_seq_example.extend([xpath_subs_list])
+ else:
+ if id in [self.cls_token_id, self.sep_token_id, self.pad_token_id]:
+ xpath_tags_seq_example.append(self.pad_xpath_tags_seq)
+ xpath_subs_seq_example.append(self.pad_xpath_subs_seq)
+ else:
+ raise ValueError("Id not recognized")
+ xpath_tags_seq.append(xpath_tags_seq_example)
+ xpath_subs_seq.append(xpath_subs_seq_example)
+
+ sanitized_tokens["xpath_tags_seq"] = xpath_tags_seq
+ sanitized_tokens["xpath_subs_seq"] = xpath_subs_seq
+
+ # optionally, create the labels
+ if node_labels is not None:
+ labels = []
+ for batch_index in range(len(sanitized_tokens["input_ids"])):
+ if return_overflowing_tokens:
+ original_index = sanitized_tokens["overflow_to_sample_mapping"][batch_index]
+ else:
+ original_index = batch_index
+ labels_example = []
+ for id, offset, word_id in zip(
+ sanitized_tokens["input_ids"][batch_index],
+ sanitized_tokens["offset_mapping"][batch_index],
+ sanitized_encodings[batch_index].word_ids,
+ ):
+ if word_id is not None:
+ if self.only_label_first_subword:
+ if offset[0] == 0:
+ # Use the real label id for the first token of the word, and padding ids for the remaining tokens
+ labels_example.append(node_labels[original_index][word_id])
+ else:
+ labels_example.append(self.pad_token_label)
+ else:
+ labels_example.append(node_labels[original_index][word_id])
+ else:
+ labels_example.append(self.pad_token_label)
+ labels.append(labels_example)
+
+ sanitized_tokens["labels"] = labels
+ # finally, remove offsets if the user didn't want them
+ if not return_offsets_mapping:
+ del sanitized_tokens["offset_mapping"]
+
+ return BatchEncoding(sanitized_tokens, sanitized_encodings, tensor_type=return_tensors)
+
+ def _encode_plus(
+ self,
+ text: TextInput | PreTokenizedInput,
+ text_pair: PreTokenizedInput | None = None,
+ xpaths: list[list[int]] | None = None,
+ node_labels: list[int] | None = None,
+ add_special_tokens: bool = True,
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
+ truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
+ max_length: int | None = None,
+ stride: int = 0,
+ pad_to_multiple_of: int | None = None,
+ padding_side: str | None = None,
+ return_tensors: bool | None = None,
+ return_token_type_ids: bool | None = None,
+ return_attention_mask: bool | None = None,
+ return_overflowing_tokens: bool = False,
+ return_special_tokens_mask: bool = False,
+ return_offsets_mapping: bool = False,
+ return_length: bool = False,
+ verbose: bool = True,
+ **kwargs,
+ ) -> BatchEncoding:
+ placeholder_xpath = "/document/node"
+
+ if isinstance(text, tuple):
+ text = list(text)
+ if text_pair is not None and isinstance(text_pair, tuple):
+ text_pair = list(text_pair)
+
+ nodes_single = text if text_pair is None else text_pair
+ processed_nodes = nodes_single
+
+ if isinstance(nodes_single, str):
+ processed_nodes = nodes_single.split()
+ elif isinstance(nodes_single, list) and nodes_single and isinstance(nodes_single[0], str):
+ processed_nodes = nodes_single
+
+ if text_pair is None:
+ text = processed_nodes
+ else:
+ text_pair = processed_nodes
+
+ if xpaths is None:
+ length = len(processed_nodes) if hasattr(processed_nodes, "__len__") else 0
+ xpaths = [placeholder_xpath] * length
+
+ # make it a batched input
+ # 2 options:
+ # 1) only text, in case text must be a list of str
+ # 2) text + text_pair, in which case text = str and text_pair a list of str
+ batched_input = [(text, text_pair)] if text_pair else [text]
+ batched_xpaths = [xpaths]
+ batched_node_labels = [node_labels] if node_labels is not None else None
+ batched_output = self._batch_encode_plus(
+ batched_input,
+ is_pair=bool(text_pair is not None),
+ xpaths=batched_xpaths,
+ node_labels=batched_node_labels,
+ add_special_tokens=add_special_tokens,
+ padding_strategy=padding_strategy,
+ truncation_strategy=truncation_strategy,
+ max_length=max_length,
+ stride=stride,
+ pad_to_multiple_of=pad_to_multiple_of,
+ padding_side=padding_side,
+ return_tensors=return_tensors,
+ return_token_type_ids=return_token_type_ids,
+ return_attention_mask=return_attention_mask,
+ return_overflowing_tokens=return_overflowing_tokens,
+ return_special_tokens_mask=return_special_tokens_mask,
+ return_offsets_mapping=return_offsets_mapping,
+ return_length=return_length,
+ verbose=verbose,
+ **kwargs,
+ )
+
+ # Return tensor is None, then we can remove the leading batch axis
+ # Overflowing tokens are returned as a batch of output so we keep them in this case
+ if return_tensors is None and not return_overflowing_tokens:
+ batched_output = BatchEncoding(
+ {
+ key: value[0] if len(value) > 0 and isinstance(value[0], list) else value
+ for key, value in batched_output.items()
+ },
+ batched_output.encodings,
+ )
+
+ self._eventual_warn_about_too_long_sequence(batched_output["input_ids"], max_length, verbose)
+
+ return batched_output
+
+ def _pad(
+ self,
+ encoded_inputs: dict[str, EncodedInput] | BatchEncoding,
+ max_length: int | None = None,
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
+ pad_to_multiple_of: int | None = None,
+ padding_side: str | None = None,
+ return_attention_mask: bool | None = None,
+ ) -> dict:
+ """
+ Args:
+ Pad encoded inputs (on left/right and up to predefined length or max length in the batch)
+ encoded_inputs:
+ Dictionary of tokenized inputs (`list[int]`) or batch of tokenized inputs (`list[list[int]]`).
+ max_length: maximum length of the returned list and optionally padding length (see below).
+ Will truncate by taking into account the special tokens.
+ padding_strategy: PaddingStrategy to use for padding.
+ - PaddingStrategy.LONGEST Pad to the longest sequence in the batch
+ - PaddingStrategy.MAX_LENGTH: Pad to the max length (default)
+ - PaddingStrategy.DO_NOT_PAD: Do not pad
+ The tokenizer padding sides are defined in self.padding_side:
+ - 'left': pads on the left of the sequences
+ - 'right': pads on the right of the sequences
+ pad_to_multiple_of: (optional) Integer if set will pad the sequence to a multiple of the provided value.
+ This is especially useful to enable the use of Tensor Core on NVIDIA hardware with compute capability
+ `>= 7.5` (Volta).
+ padding_side:
+ The side on which the model should have padding applied. Should be selected between ['right', 'left'].
+ Default value is picked from the class attribute of the same name.
+ return_attention_mask:
+ (optional) Set to False to avoid returning attention mask (default: set to model specifics)
+ """
+ # Load from model defaults
+ if return_attention_mask is None:
+ return_attention_mask = "attention_mask" in self.model_input_names
+
+ required_input = encoded_inputs[self.model_input_names[0]]
+
+ if padding_strategy == PaddingStrategy.LONGEST:
+ max_length = len(required_input)
+
+ if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
+ max_length = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of
+
+ needs_to_be_padded = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(required_input) != max_length
+
+ # Initialize attention mask if not present.
+ if return_attention_mask and "attention_mask" not in encoded_inputs:
+ encoded_inputs["attention_mask"] = [1] * len(required_input)
+
+ if needs_to_be_padded:
+ difference = max_length - len(required_input)
+ padding_side = padding_side if padding_side is not None else self.padding_side
+ if padding_side == "right":
+ if return_attention_mask:
+ encoded_inputs["attention_mask"] = encoded_inputs["attention_mask"] + [0] * difference
+ if "token_type_ids" in encoded_inputs:
+ encoded_inputs["token_type_ids"] = (
+ encoded_inputs["token_type_ids"] + [self.pad_token_type_id] * difference
+ )
+ if "xpath_tags_seq" in encoded_inputs:
+ encoded_inputs["xpath_tags_seq"] = (
+ encoded_inputs["xpath_tags_seq"] + [self.pad_xpath_tags_seq] * difference
+ )
+ if "xpath_subs_seq" in encoded_inputs:
+ encoded_inputs["xpath_subs_seq"] = (
+ encoded_inputs["xpath_subs_seq"] + [self.pad_xpath_subs_seq] * difference
+ )
+ if "labels" in encoded_inputs:
+ encoded_inputs["labels"] = encoded_inputs["labels"] + [self.pad_token_label] * difference
+ if "special_tokens_mask" in encoded_inputs:
+ encoded_inputs["special_tokens_mask"] = encoded_inputs["special_tokens_mask"] + [1] * difference
+ encoded_inputs[self.model_input_names[0]] = required_input + [self.pad_token_id] * difference
+ elif padding_side == "left":
+ if return_attention_mask:
+ encoded_inputs["attention_mask"] = [0] * difference + encoded_inputs["attention_mask"]
+ if "token_type_ids" in encoded_inputs:
+ encoded_inputs["token_type_ids"] = [self.pad_token_type_id] * difference + encoded_inputs[
+ "token_type_ids"
+ ]
+ if "xpath_tags_seq" in encoded_inputs:
+ encoded_inputs["xpath_tags_seq"] = [self.pad_xpath_tags_seq] * difference + encoded_inputs[
+ "xpath_tags_seq"
+ ]
+ if "xpath_subs_seq" in encoded_inputs:
+ encoded_inputs["xpath_subs_seq"] = [self.pad_xpath_subs_seq] * difference + encoded_inputs[
+ "xpath_subs_seq"
+ ]
+ if "labels" in encoded_inputs:
+ encoded_inputs["labels"] = [self.pad_token_label] * difference + encoded_inputs["labels"]
+ if "special_tokens_mask" in encoded_inputs:
+ encoded_inputs["special_tokens_mask"] = [1] * difference + encoded_inputs["special_tokens_mask"]
+ encoded_inputs[self.model_input_names[0]] = [self.pad_token_id] * difference + required_input
+ else:
+ raise ValueError("Invalid padding strategy:" + str(padding_side))
+
+ return encoded_inputs
+
+ def build_inputs_with_special_tokens(
+ self, token_ids_0: list[int], token_ids_1: list[int] | None = None
+ ) -> list[int]:
+ """
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
+ adding special tokens. A RoBERTa sequence has the following format:
+ - single sequence: ` X `
+ - pair of sequences: ` A B `
+
+ Args:
+ token_ids_0 (`list[int]`):
+ List of IDs to which the special tokens will be added.
+ token_ids_1 (`list[int]`, *optional*):
+ Optional second list of IDs for sequence pairs.
+ Returns:
+ `list[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
+ """
+ if token_ids_1 is None:
+ return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
+ cls = [self.cls_token_id]
+ sep = [self.sep_token_id]
+ return cls + token_ids_0 + sep + token_ids_1 + sep
+
+ def create_token_type_ids_from_sequences(
+ self, token_ids_0: list[int], token_ids_1: list[int] | None = None
+ ) -> list[int]:
+ """
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. RoBERTa does not
+ make use of token type ids, therefore a list of zeros is returned.
+
+ Args:
+ token_ids_0 (`list[int]`):
+ List of IDs.
+ token_ids_1 (`list[int]`, *optional*):
+ Optional second list of IDs for sequence pairs.
+ Returns:
+ `list[int]`: List of zeros.
+ """
+ sep = [self.sep_token_id]
+ cls = [self.cls_token_id]
+
+ if token_ids_1 is None:
+ return len(cls + token_ids_0 + sep) * [0]
+ return len(cls + token_ids_0 + sep + token_ids_1 + sep) * [0]
+
+ def save_vocabulary(self, save_directory: str, filename_prefix: str | None = None) -> tuple[str]:
+ files = self._tokenizer.model.save(save_directory, name=filename_prefix)
+ return tuple(files)
+
+
+MarkupLMTokenizerFast = MarkupLMTokenizer
+
+
+__all__ = ["MarkupLMTokenizer", "MarkupLMTokenizerFast"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mask2former/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mask2former/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..edfde256fdbe3eaf9fe05a110f977f2f4a412def
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mask2former/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mask2former/__pycache__/configuration_mask2former.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mask2former/__pycache__/configuration_mask2former.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f1bd94089947d6704c9000510e8a01134ce4a73f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mask2former/__pycache__/configuration_mask2former.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mask2former/__pycache__/image_processing_mask2former.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mask2former/__pycache__/image_processing_mask2former.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dfaa5943958059d99cd10b05a50f541d459226ef
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mask2former/__pycache__/image_processing_mask2former.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mask2former/__pycache__/image_processing_pil_mask2former.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mask2former/__pycache__/image_processing_pil_mask2former.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c6f31d04f8d73fa091f134e934e642e80c4b2b9b
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mask2former/__pycache__/image_processing_pil_mask2former.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mask2former/__pycache__/modular_mask2former.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mask2former/__pycache__/modular_mask2former.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fc8c2dc5cab29d7101cf3b3f84bd56d9253eb23f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mask2former/__pycache__/modular_mask2former.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mimi/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mimi/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5b67cd67839b66f65596d6f7738f29b9df3818c7
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mimi/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mimi/__pycache__/configuration_mimi.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mimi/__pycache__/configuration_mimi.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b65ea4105abb8383ec3513dd6dad9dbe5d08869a
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mimi/__pycache__/configuration_mimi.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mimi/__pycache__/modeling_mimi.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mimi/__pycache__/modeling_mimi.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0e22e78747cc31554472f5aa43c749b7807a8a3b
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mimi/__pycache__/modeling_mimi.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/minicpmv4_6/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/minicpmv4_6/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ddb42d4c2fa0ab71bb5c1139918c8755e0410e9c
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/minicpmv4_6/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/minicpmv4_6/__pycache__/configuration_minicpmv4_6.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/minicpmv4_6/__pycache__/configuration_minicpmv4_6.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..029ed4363a57e91a39252a25f6ae54afbf321164
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/minicpmv4_6/__pycache__/configuration_minicpmv4_6.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/minicpmv4_6/__pycache__/image_processing_minicpmv4_6.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/minicpmv4_6/__pycache__/image_processing_minicpmv4_6.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..74f7816453cc4971c4bf8229e4240726e6cc9461
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/minicpmv4_6/__pycache__/image_processing_minicpmv4_6.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/minicpmv4_6/__pycache__/image_processing_pil_minicpmv4_6.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/minicpmv4_6/__pycache__/image_processing_pil_minicpmv4_6.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..54b013c2f29d894a4e5b32191b9771b755732074
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/minicpmv4_6/__pycache__/image_processing_pil_minicpmv4_6.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/minicpmv4_6/__pycache__/modeling_minicpmv4_6.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/minicpmv4_6/__pycache__/modeling_minicpmv4_6.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9fa10ecbd7e547c85da93a58019ac1258796707e
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/minicpmv4_6/__pycache__/modeling_minicpmv4_6.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/minicpmv4_6/__pycache__/modular_minicpmv4_6.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/minicpmv4_6/__pycache__/modular_minicpmv4_6.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..78b98a33f2b72dfc82ebc0674cfdac02a9a5a84c
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/minicpmv4_6/__pycache__/modular_minicpmv4_6.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/minicpmv4_6/__pycache__/processing_minicpmv4_6.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/minicpmv4_6/__pycache__/processing_minicpmv4_6.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..52ac282b635222009360ce59311fd016c1025364
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/minicpmv4_6/__pycache__/processing_minicpmv4_6.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/minicpmv4_6/__pycache__/video_processing_minicpmv4_6.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/minicpmv4_6/__pycache__/video_processing_minicpmv4_6.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0b2a638290644df3cb50e6c36741741cf050060b
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/minicpmv4_6/__pycache__/video_processing_minicpmv4_6.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/ministral3/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/ministral3/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..59fdb90b750abe0e66e8c3f04d7cab3fec74affc
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/ministral3/__init__.py
@@ -0,0 +1,27 @@
+# Copyright 2025 Mistral AI and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_ministral3 import *
+ from .modeling_ministral3 import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/ministral3/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/ministral3/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7790cd33bb4846e9beb1363262f480c17a32e022
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/ministral3/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/ministral3/__pycache__/configuration_ministral3.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/ministral3/__pycache__/configuration_ministral3.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..20f832c6fc35b922ee9b3b62b18149a82bad14c6
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/ministral3/__pycache__/configuration_ministral3.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/ministral3/__pycache__/modeling_ministral3.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/ministral3/__pycache__/modeling_ministral3.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a4b9bdd2acf198086e1c099a4abdfe9235db4999
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/ministral3/__pycache__/modeling_ministral3.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/ministral3/__pycache__/modular_ministral3.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/ministral3/__pycache__/modular_ministral3.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..09f89a971167e8bf955e3d38be38723dd9b11943
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/ministral3/__pycache__/modular_ministral3.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/ministral3/configuration_ministral3.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/ministral3/configuration_ministral3.py
new file mode 100644
index 0000000000000000000000000000000000000000..76d55710d5aeeba3b2d5e27c15b79476e8c7328f
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/ministral3/configuration_ministral3.py
@@ -0,0 +1,121 @@
+# Copyright 2025 Mistral AI and the HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Ministral model configuration"""
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...modeling_rope_utils import RopeParameters
+from ...utils import auto_docstring, logging
+
+
+logger = logging.get_logger(__name__)
+
+
+@auto_docstring(checkpoint="mistralai/Ministral-3-8B-Base-2512")
+@strict
+class Ministral3Config(PreTrainedConfig):
+ r"""
+ Example:
+
+ ```python
+ >>> from transformers import Ministral3Config, Ministral3ForCausalLM, Mistral3Config, Mistral3ForConditionalGeneration, PixtralVisionConfig
+
+ >>> # Initializing a Pixtral-vision config
+ >>> vision_config = PixtralVisionConfig()
+
+ >>> # Initializing a Ministral3 config
+ >>> text_config = Ministral3Config()
+
+ >>> # Initializing a Mistral3 configuration
+ >>> configuration = Mistral3Config(vision_config, text_config)
+
+ >>> # Initializing a model from the Ministral3 configuration
+ >>> text_model = Ministral3ForCausalLM(text_config)
+
+ >>> # Initializing a model from the Mistral3 configuration
+ >>> model = Mistral3ForConditionalGeneration(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "ministral3"
+ keys_to_ignore_at_inference = ["past_key_values"]
+ # Default tensor parallel plan for base model `MistralModel`
+ base_model_tp_plan = {
+ "layers.*.self_attn.q_proj": "colwise",
+ "layers.*.self_attn.k_proj": "colwise",
+ "layers.*.self_attn.v_proj": "colwise",
+ "layers.*.self_attn.o_proj": "rowwise",
+ "layers.*.mlp.gate_proj": "colwise",
+ "layers.*.mlp.up_proj": "colwise",
+ "layers.*.mlp.down_proj": "rowwise",
+ }
+ base_model_pp_plan = {
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
+ "norm": (["hidden_states"], ["hidden_states"]),
+ }
+ ignore_keys_at_rope_validation = {"llama_4_scaling_beta", "max_position_embeddings"}
+
+ vocab_size: int = 131072
+ hidden_size: int = 4096
+ intermediate_size: int = 14336
+ num_hidden_layers: int = 34
+ num_attention_heads: int = 32
+ num_key_value_heads: int = 8
+ head_dim: int = 128
+ hidden_act: str = "silu"
+ max_position_embeddings: int = 262144
+ initializer_range: float = 0.02
+ rms_norm_eps: float = 1e-5
+ use_cache: bool = True
+ pad_token_id: int | None = 11
+ bos_token_id: int | None = 1
+ eos_token_id: int | list[int] | None = 2
+ tie_word_embeddings: bool = False
+ rope_parameters: RopeParameters | dict | None = None
+ sliding_window: int | None = None
+ attention_dropout: float | int = 0.0
+
+ def __post_init__(self, **kwargs):
+ if self.rope_parameters is None:
+ self.rope_parameters = {
+ "type": "yarn",
+ "rope_theta": 1000000.0,
+ "factor": 16.0,
+ "original_max_position_embeddings": 16384,
+ "max_position_embeddings": self.max_position_embeddings,
+ "beta_fast": 32.0,
+ "beta_slow": 1.0,
+ "mscale_all_dim": 1.0,
+ "mscale": 1.0,
+ "llama_4_scaling_beta": 0.1,
+ }
+
+ self.head_dim = self.head_dim if self.head_dim is not None else self.hidden_size // self.num_attention_heads
+
+ if self.num_key_value_heads is None:
+ self.num_key_value_heads = self.num_attention_heads
+
+ if "layer_types" in kwargs:
+ logger.warning_once(
+ "Detected Mistral model with layer_types. Consider using AutoModel or Ministral classes instead to enable alternating attention compatibility."
+ )
+
+ super().__post_init__(**kwargs)
+
+
+__all__ = ["Ministral3Config"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/ministral3/modeling_ministral3.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/ministral3/modeling_ministral3.py
new file mode 100644
index 0000000000000000000000000000000000000000..6aacf4c8ce3a9e06d53f3ab4c7e3d1228a15f2dd
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/ministral3/modeling_ministral3.py
@@ -0,0 +1,505 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/ministral3/modular_ministral3.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_ministral3.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+from collections.abc import Callable
+from typing import Optional
+
+import torch
+from torch import nn
+
+from ...activations import ACT2FN
+from ...cache_utils import Cache, DynamicCache
+from ...generation import GenerationMixin
+from ...integrations import use_kernel_forward_from_hub, use_kernel_func_from_hub, use_kernelized_func
+from ...masking_utils import create_causal_mask, create_sliding_window_causal_mask
+from ...modeling_flash_attention_utils import FlashAttentionKwargs
+from ...modeling_layers import (
+ GenericForQuestionAnswering,
+ GenericForSequenceClassification,
+ GenericForTokenClassification,
+ GradientCheckpointingLayer,
+)
+from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
+from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import TransformersKwargs, auto_docstring, can_return_tuple
+from ...utils.generic import maybe_autocast, merge_with_config_defaults
+from ...utils.output_capturing import capture_outputs
+from .configuration_ministral3 import Ministral3Config
+
+
+def rotate_half(x):
+ """Rotates half the hidden dims of the input."""
+ x1 = x[..., : x.shape[-1] // 2]
+ x2 = x[..., x.shape[-1] // 2 :]
+ return torch.cat((-x2, x1), dim=-1)
+
+
+@use_kernel_func_from_hub("rotary_pos_emb")
+def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
+ """Applies Rotary Position Embedding to the query and key tensors.
+
+ Args:
+ q (`torch.Tensor`): The query tensor.
+ k (`torch.Tensor`): The key tensor.
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
+ Returns:
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
+ """
+ cos = cos.unsqueeze(unsqueeze_dim)
+ sin = sin.unsqueeze(unsqueeze_dim)
+ q_embed = (q * cos) + (rotate_half(q) * sin)
+ k_embed = (k * cos) + (rotate_half(k) * sin)
+ return q_embed, k_embed
+
+
+def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
+ """
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
+ """
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
+ if n_rep == 1:
+ return hidden_states
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
+
+
+def eager_attention_forward(
+ module: nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: torch.Tensor | None,
+ scaling: float,
+ dropout: float = 0.0,
+ **kwargs: Unpack[TransformersKwargs],
+):
+ key_states = repeat_kv(key, module.num_key_value_groups)
+ value_states = repeat_kv(value, module.num_key_value_groups)
+
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
+ if attention_mask is not None:
+ attn_weights = attn_weights + attention_mask
+
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
+ attn_output = torch.matmul(attn_weights, value_states)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+
+ return attn_output, attn_weights
+
+
+def get_llama_4_attn_scale(positions_ids: torch.Tensor, beta: float, max_position_embeddings: int) -> torch.Tensor:
+ scaling = 1 + beta * torch.log(1 + torch.floor(positions_ids / max_position_embeddings))
+ return scaling[:, None, :, None]
+
+
+@use_kernelized_func(apply_rotary_pos_emb)
+class Ministral3Attention(nn.Module):
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
+
+ def __init__(self, config: Ministral3Config, layer_idx: int):
+ super().__init__()
+ self.config = config
+ self.layer_idx = layer_idx
+ self.head_dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
+ self.scaling = self.head_dim**-0.5
+ self.attention_dropout = config.attention_dropout
+ self.is_causal = True
+ self.q_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=False)
+ self.k_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=False)
+ self.v_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=False)
+ self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
+ attention_mask: torch.Tensor | None,
+ position_ids: torch.Tensor,
+ past_key_values: Cache | None = None,
+ **kwargs: Unpack[FlashAttentionKwargs],
+ ) -> tuple[torch.Tensor, torch.Tensor | None]:
+ input_shape = hidden_states.shape[:-1]
+ hidden_shape = (*input_shape, -1, self.head_dim)
+
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+
+ cos, sin = position_embeddings
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
+ query_states = query_states * get_llama_4_attn_scale(
+ position_ids,
+ self.config.rope_parameters.get("llama_4_scaling_beta"),
+ self.config.rope_parameters.get("original_max_position_embeddings"),
+ ).to(query_states.dtype)
+
+ if past_key_values is not None:
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_states,
+ key_states,
+ value_states,
+ attention_mask,
+ dropout=0.0 if not self.training else self.attention_dropout,
+ scaling=self.scaling,
+ sliding_window=getattr(self.config, "sliding_window", None), # main diff with Llama
+ **kwargs,
+ )
+
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ attn_output = self.o_proj(attn_output)
+ return attn_output, attn_weights
+
+
+class Ministral3MLP(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.hidden_size = config.hidden_size
+ self.intermediate_size = config.intermediate_size
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
+ self.act_fn = ACT2FN[config.hidden_act]
+
+ def forward(self, x):
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
+ return down_proj
+
+
+@use_kernel_forward_from_hub("RMSNorm")
+class Ministral3RMSNorm(nn.Module):
+ def __init__(self, hidden_size, eps: float = 1e-6) -> None:
+ """
+ Ministral3RMSNorm is equivalent to T5LayerNorm
+ """
+ super().__init__()
+ self.weight = nn.Parameter(torch.ones(hidden_size))
+ self.variance_epsilon = eps
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ input_dtype = hidden_states.dtype
+ hidden_states = hidden_states.to(torch.float32)
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
+ return self.weight * hidden_states.to(input_dtype)
+
+ def extra_repr(self):
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
+
+
+class Ministral3DecoderLayer(GradientCheckpointingLayer):
+ def __init__(self, config: Ministral3Config, layer_idx: int):
+ super().__init__()
+ self.hidden_size = config.hidden_size
+ self.self_attn = Ministral3Attention(config=config, layer_idx=layer_idx)
+ self.mlp = Ministral3MLP(config)
+ self.input_layernorm = Ministral3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.post_attention_layernorm = Ministral3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ use_cache: bool | None = False,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.Tensor:
+ residual = hidden_states
+ hidden_states = self.input_layernorm(hidden_states)
+ # Self Attention
+ hidden_states, _ = self.self_attn(
+ hidden_states=hidden_states,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ position_embeddings=position_embeddings,
+ **kwargs,
+ )
+ hidden_states = residual + hidden_states
+
+ # Fully Connected
+ residual = hidden_states
+ hidden_states = self.post_attention_layernorm(hidden_states)
+ hidden_states = self.mlp(hidden_states)
+ hidden_states = residual + hidden_states
+ return hidden_states
+
+
+@auto_docstring
+class Ministral3PreTrainedModel(PreTrainedModel):
+ config: Ministral3Config
+ base_model_prefix = "model"
+ supports_gradient_checkpointing = True
+ _no_split_modules = ["Ministral3DecoderLayer"]
+ _skip_keys_device_placement = ["past_key_values"]
+ _supports_flash_attn = True
+ _supports_sdpa = True
+ _supports_flex_attn = True
+
+ _can_compile_fullgraph = True
+ _supports_attention_backend = True
+ _can_record_outputs = {
+ "hidden_states": Ministral3DecoderLayer,
+ "attentions": Ministral3Attention,
+ }
+
+
+class Ministral3RotaryEmbedding(nn.Module):
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
+
+ def __init__(self, config: Ministral3Config, device=None):
+ super().__init__()
+ self.max_seq_len_cached = config.max_position_embeddings
+ self.original_max_seq_len = config.max_position_embeddings
+
+ self.config = config
+
+ self.rope_type = self.config.rope_parameters["rope_type"]
+ rope_init_fn: Callable = self.compute_default_rope_parameters
+ if self.rope_type != "default":
+ rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
+ inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
+
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
+ self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
+
+ @staticmethod
+ def compute_default_rope_parameters(
+ config: Ministral3Config | None = None,
+ device: Optional["torch.device"] = None,
+ seq_len: int | None = None,
+ ) -> tuple["torch.Tensor", float]:
+ """
+ Computes the inverse frequencies according to the original RoPE implementation
+ Args:
+ config ([`~transformers.PreTrainedConfig`]):
+ The model configuration.
+ device (`torch.device`):
+ The device to use for initialization of the inverse frequencies.
+ seq_len (`int`, *optional*):
+ The current sequence length. Unused for this type of RoPE.
+ Returns:
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
+ """
+ base = config.rope_parameters["rope_theta"]
+ dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
+
+ attention_factor = 1.0 # Unused in this type of RoPE
+
+ # Compute the inverse frequencies
+ inv_freq = 1.0 / (
+ base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
+ )
+ return inv_freq, attention_factor
+
+ @torch.no_grad()
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
+ def forward(self, x, position_ids):
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
+ position_ids_expanded = position_ids[:, None, :].float()
+
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
+ with maybe_autocast(device_type=device_type, enabled=False): # Force float32
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
+ emb = torch.cat((freqs, freqs), dim=-1)
+ cos = emb.cos() * self.attention_scaling
+ sin = emb.sin() * self.attention_scaling
+
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
+
+
+@auto_docstring
+class Ministral3Model(Ministral3PreTrainedModel):
+ def __init__(self, config: Ministral3Config):
+ super().__init__(config)
+ self.padding_idx = config.pad_token_id
+ self.vocab_size = config.vocab_size
+
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
+ self.layers = nn.ModuleList(
+ [Ministral3DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
+ )
+ self.norm = Ministral3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.rotary_emb = Ministral3RotaryEmbedding(config=config)
+ self.gradient_checkpointing = False
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @merge_with_config_defaults
+ @capture_outputs
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ use_cache: bool | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> BaseModelOutputWithPast:
+ if (input_ids is None) ^ (inputs_embeds is not None):
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
+
+ if inputs_embeds is None:
+ inputs_embeds = self.embed_tokens(input_ids)
+
+ if use_cache and past_key_values is None:
+ past_key_values = DynamicCache(config=self.config)
+
+ if position_ids is None:
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
+ position_ids = position_ids.unsqueeze(0)
+
+ mask_function = create_causal_mask if self.config.sliding_window is None else create_sliding_window_causal_mask
+ causal_mask = mask_function(
+ config=self.config,
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ position_ids=position_ids,
+ )
+
+ hidden_states = inputs_embeds
+ position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
+
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
+ hidden_states = decoder_layer(
+ hidden_states,
+ attention_mask=causal_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ position_embeddings=position_embeddings,
+ **kwargs,
+ )
+ hidden_states = self.norm(hidden_states)
+ return BaseModelOutputWithPast(
+ last_hidden_state=hidden_states,
+ past_key_values=past_key_values if use_cache else None,
+ )
+
+
+@auto_docstring
+class Ministral3ForCausalLM(Ministral3PreTrainedModel, GenerationMixin):
+ _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
+ _tp_plan = {"lm_head": "colwise_gather_output"}
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
+
+ def __init__(self, config):
+ super().__init__(config)
+ self.model = Ministral3Model(config)
+ self.vocab_size = config.vocab_size
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ use_cache: bool | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> CausalLMOutputWithPast:
+ r"""
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, Ministral3ForCausalLM
+
+ >>> model = Ministral3ForCausalLM.from_pretrained("meta-ministral3/Ministral3-2-7b-hf")
+ >>> tokenizer = AutoTokenizer.from_pretrained("meta-ministral3/Ministral3-2-7b-hf")
+
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
+
+ >>> # Generate
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
+ ```"""
+ outputs: BaseModelOutputWithPast = self.model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ **kwargs,
+ )
+
+ hidden_states = outputs.last_hidden_state
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
+
+ return CausalLMOutputWithPast(
+ loss=loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+class Ministral3ForTokenClassification(GenericForTokenClassification, Ministral3PreTrainedModel):
+ pass
+
+
+class Ministral3ForSequenceClassification(GenericForSequenceClassification, Ministral3PreTrainedModel):
+ pass
+
+
+class Ministral3ForQuestionAnswering(GenericForQuestionAnswering, Ministral3PreTrainedModel):
+ pass
+
+
+__all__ = [
+ "Ministral3ForCausalLM",
+ "Ministral3ForQuestionAnswering",
+ "Ministral3Model",
+ "Ministral3PreTrainedModel",
+ "Ministral3ForSequenceClassification",
+ "Ministral3ForTokenClassification",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/ministral3/modular_ministral3.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/ministral3/modular_ministral3.py
new file mode 100644
index 0000000000000000000000000000000000000000..0a925f5d404d26530f3834489f0154f8bb5b7ce5
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/ministral3/modular_ministral3.py
@@ -0,0 +1,121 @@
+from collections.abc import Callable
+
+import torch
+
+from ...cache_utils import Cache
+from ...modeling_flash_attention_utils import FlashAttentionKwargs
+from ...modeling_layers import (
+ GenericForQuestionAnswering,
+ GenericForSequenceClassification,
+ GenericForTokenClassification,
+)
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS
+from ...processing_utils import Unpack
+from ...utils import auto_docstring, logging
+from ..mistral.modeling_mistral import (
+ MistralAttention,
+ MistralDecoderLayer,
+ MistralForCausalLM,
+ MistralModel,
+ MistralPreTrainedModel,
+ apply_rotary_pos_emb,
+ eager_attention_forward,
+)
+
+
+logger = logging.get_logger(__name__)
+
+
+def get_llama_4_attn_scale(positions_ids: torch.Tensor, beta: float, max_position_embeddings: int) -> torch.Tensor:
+ scaling = 1 + beta * torch.log(1 + torch.floor(positions_ids / max_position_embeddings))
+ return scaling[:, None, :, None]
+
+
+class Ministral3Attention(MistralAttention):
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
+ attention_mask: torch.Tensor | None,
+ position_ids: torch.Tensor,
+ past_key_values: Cache | None = None,
+ **kwargs: Unpack[FlashAttentionKwargs],
+ ) -> tuple[torch.Tensor, torch.Tensor | None]:
+ input_shape = hidden_states.shape[:-1]
+ hidden_shape = (*input_shape, -1, self.head_dim)
+
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+
+ cos, sin = position_embeddings
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
+ query_states = query_states * get_llama_4_attn_scale(
+ position_ids,
+ self.config.rope_parameters.get("llama_4_scaling_beta"),
+ self.config.rope_parameters.get("original_max_position_embeddings"),
+ ).to(query_states.dtype)
+
+ if past_key_values is not None:
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_states,
+ key_states,
+ value_states,
+ attention_mask,
+ dropout=0.0 if not self.training else self.attention_dropout,
+ scaling=self.scaling,
+ sliding_window=getattr(self.config, "sliding_window", None), # main diff with Llama
+ **kwargs,
+ )
+
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ attn_output = self.o_proj(attn_output)
+ return attn_output, attn_weights
+
+
+class Ministral3DecoderLayer(MistralDecoderLayer):
+ pass
+
+
+@auto_docstring
+class Ministral3PreTrainedModel(MistralPreTrainedModel):
+ pass
+
+
+@auto_docstring
+class Ministral3Model(MistralModel):
+ pass
+
+
+@auto_docstring
+class Ministral3ForCausalLM(MistralForCausalLM):
+ pass
+
+
+class Ministral3ForTokenClassification(GenericForTokenClassification, Ministral3PreTrainedModel):
+ pass
+
+
+class Ministral3ForSequenceClassification(GenericForSequenceClassification, Ministral3PreTrainedModel):
+ pass
+
+
+class Ministral3ForQuestionAnswering(GenericForQuestionAnswering, Ministral3PreTrainedModel):
+ pass
+
+
+__all__ = [
+ "Ministral3ForCausalLM",
+ "Ministral3ForQuestionAnswering",
+ "Ministral3Model",
+ "Ministral3PreTrainedModel",
+ "Ministral3ForSequenceClassification",
+ "Ministral3ForTokenClassification",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mistral/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mistral/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8d070cd931c1702e955fbdaa63a4bad70cc6a68c
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mistral/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mistral/__pycache__/configuration_mistral.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mistral/__pycache__/configuration_mistral.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fc616d1f49e4d3a06a405d262995ac6d7c61965d
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mistral/__pycache__/configuration_mistral.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mistral/__pycache__/modeling_mistral.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mistral/__pycache__/modeling_mistral.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d5e8ab6148f39a6a389730115d8a5dcfa3c55db7
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mistral/__pycache__/modeling_mistral.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mistral/__pycache__/modular_mistral.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mistral/__pycache__/modular_mistral.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4f1583ec217defe4a9b4a9a6edde591b3b7c4e41
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mistral/__pycache__/modular_mistral.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mobilevit/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mobilevit/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..5ee9c65f364990069cdab3a66ef273b832822a5d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mobilevit/__init__.py
@@ -0,0 +1,29 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_mobilevit import *
+ from .image_processing_mobilevit import *
+ from .image_processing_pil_mobilevit import *
+ from .modeling_mobilevit import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mobilevit/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mobilevit/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d6ac247b8ed1f41acf8335e2b1cc357e13c8956b
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mobilevit/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mobilevit/__pycache__/configuration_mobilevit.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mobilevit/__pycache__/configuration_mobilevit.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..71cb4b76a65b54302bb061c38974c658db3d8102
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mobilevit/__pycache__/configuration_mobilevit.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mobilevit/__pycache__/image_processing_mobilevit.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mobilevit/__pycache__/image_processing_mobilevit.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..87ec8aefd63da9201070cf701963dc28d9615df9
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mobilevit/__pycache__/image_processing_mobilevit.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mobilevit/__pycache__/image_processing_pil_mobilevit.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mobilevit/__pycache__/image_processing_pil_mobilevit.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6faa84b55bc6769202e87a2fddf6347dcfc4fd91
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mobilevit/__pycache__/image_processing_pil_mobilevit.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mobilevit/__pycache__/modeling_mobilevit.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mobilevit/__pycache__/modeling_mobilevit.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3b244a340b073885b44b16694629e6b5c7306754
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mobilevit/__pycache__/modeling_mobilevit.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mobilevit/configuration_mobilevit.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mobilevit/configuration_mobilevit.py
new file mode 100644
index 0000000000000000000000000000000000000000..6d811285eca664ec8750ed56453e7a3a149aef48
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mobilevit/configuration_mobilevit.py
@@ -0,0 +1,75 @@
+# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""MobileViT model configuration"""
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring
+
+
+@auto_docstring(checkpoint="google/mobilenet_v2_1.0_224")
+@strict
+class MobileViTConfig(PreTrainedConfig):
+ r"""
+ neck_hidden_sizes (`list[int]`, *optional*, defaults to `[16, 32, 64, 96, 128, 160, 640]`):
+ The number of channels for the feature maps of the backbone.
+ aspp_out_channels (`int`, *optional*, defaults to 256):
+ Number of output channels used in the ASPP layer for semantic segmentation.
+ atrous_rates (`list[int]`, *optional*, defaults to `[6, 12, 18]`):
+ Dilation (atrous) factors used in the ASPP layer for semantic segmentation.
+ aspp_dropout_prob (`float`, *optional*, defaults to 0.1):
+ The dropout ratio for the ASPP layer for semantic segmentation.
+
+ Example:
+
+ ```python
+ >>> from transformers import MobileViTConfig, MobileViTModel
+
+ >>> # Initializing a mobilevit-small style configuration
+ >>> configuration = MobileViTConfig()
+
+ >>> # Initializing a model from the mobilevit-small style configuration
+ >>> model = MobileViTModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "mobilevit"
+
+ num_channels: int = 3
+ image_size: int | list[int] | tuple[int, int] = 256
+ patch_size: int | list[int] | tuple[int, int] = 2
+ hidden_sizes: list[int] | tuple[int, ...] = (144, 192, 240)
+ neck_hidden_sizes: list[int] | tuple[int, ...] = (16, 32, 64, 96, 128, 160, 640)
+ num_attention_heads: int = 4
+ mlp_ratio: float = 2.0
+ expand_ratio: float = 4.0
+ hidden_act: str = "silu"
+ conv_kernel_size: int = 3
+ output_stride: int = 32
+ hidden_dropout_prob: float | int = 0.1
+ attention_probs_dropout_prob: float | int = 0.0
+ classifier_dropout_prob: float | int = 0.1
+ initializer_range: float = 0.02
+ layer_norm_eps: float = 1e-5
+ qkv_bias: bool = True
+ aspp_out_channels: int = 256
+ atrous_rates: list[int] | tuple[int, ...] = (6, 12, 18)
+ aspp_dropout_prob: float | int = 0.1
+ semantic_loss_ignore_index: int = 255
+
+
+__all__ = ["MobileViTConfig"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mobilevit/image_processing_mobilevit.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mobilevit/image_processing_mobilevit.py
new file mode 100644
index 0000000000000000000000000000000000000000..d94c1912fbd9fb7e29d11de407ca3f45d0940a5f
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mobilevit/image_processing_mobilevit.py
@@ -0,0 +1,231 @@
+# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Image processor class for MobileViT."""
+
+from typing import Union
+
+import torch
+from torchvision.transforms.v2 import functional as tvF
+
+from ...image_processing_backends import TorchvisionBackend
+from ...image_processing_utils import BatchFeature
+from ...image_transforms import group_images_by_shape, reorder_images
+from ...image_utils import (
+ IMAGENET_STANDARD_MEAN,
+ IMAGENET_STANDARD_STD,
+ ChannelDimension,
+ ImageInput,
+ PILImageResampling,
+ SizeDict,
+)
+from ...processing_utils import ImagesKwargs, Unpack
+from ...utils import (
+ TensorType,
+ auto_docstring,
+ logging,
+ requires_backends,
+)
+
+
+logger = logging.get_logger(__name__)
+
+
+class MobileVitImageProcessorKwargs(ImagesKwargs, total=False):
+ """
+ do_flip_channel_order (`bool`, *optional*, defaults to `self.do_flip_channel_order`):
+ Whether to flip the color channels from RGB to BGR or vice versa.
+ do_reduce_labels (`bool`, *optional*, defaults to `self.do_reduce_labels`):
+ Whether or not to reduce all label values of segmentation maps by 1. Usually used for datasets where 0
+ is used for background, and background itself is not included in all classes of a dataset (e.g.
+ ADE20k). The background label will be replaced by 255.
+ """
+
+ do_flip_channel_order: bool
+ do_reduce_labels: bool
+
+
+@auto_docstring
+class MobileViTImageProcessor(TorchvisionBackend):
+ """Torchvision backend for MobileViT with flip_channel_order and reduce_label support."""
+
+ valid_kwargs = MobileVitImageProcessorKwargs
+
+ resample = PILImageResampling.BICUBIC
+ image_mean = IMAGENET_STANDARD_MEAN
+ image_std = IMAGENET_STANDARD_STD
+ size = {"shortest_edge": 224}
+ default_to_square = False
+ crop_size = {"height": 256, "width": 256}
+ do_resize = True
+ do_center_crop = True
+ do_rescale = True
+ do_normalize = None
+ do_convert_rgb = None
+ do_flip_channel_order = True
+ do_reduce_labels = False
+
+ def __init__(self, **kwargs: Unpack[MobileVitImageProcessorKwargs]):
+ super().__init__(**kwargs)
+
+ @auto_docstring
+ def preprocess(
+ self,
+ images: ImageInput,
+ segmentation_maps: ImageInput | None = None,
+ **kwargs: Unpack[MobileVitImageProcessorKwargs],
+ ) -> BatchFeature:
+ r"""
+ segmentation_maps (`ImageInput`, *optional*):
+ The segmentation maps to preprocess.
+ """
+ return super().preprocess(images, segmentation_maps, **kwargs)
+
+ def _preprocess_image_like_inputs(
+ self,
+ images: ImageInput,
+ segmentation_maps: ImageInput | None,
+ do_convert_rgb: bool,
+ input_data_format: ChannelDimension,
+ return_tensors: str | TensorType | None,
+ device: Union[str, "torch.device"] | None = None,
+ **kwargs,
+ ) -> BatchFeature:
+ """Handle extra inputs beyond images."""
+ images = self._prepare_image_like_inputs(
+ images=images, do_convert_rgb=do_convert_rgb, input_data_format=input_data_format, device=device
+ )
+ images_kwargs = kwargs.copy()
+ images_kwargs["do_reduce_labels"] = False
+ data = {}
+ data["pixel_values"] = self._preprocess(images, **images_kwargs)
+
+ if segmentation_maps is not None:
+ processed_segmentation_maps = self._prepare_image_like_inputs(
+ images=segmentation_maps,
+ expected_ndims=2,
+ do_convert_rgb=False,
+ input_data_format=ChannelDimension.FIRST,
+ )
+
+ segmentation_maps_kwargs = kwargs.copy()
+ segmentation_maps_kwargs.update(
+ {
+ "do_rescale": False,
+ "do_flip_channel_order": False,
+ # Nearest interpolation is used for segmentation maps instead of BICUBIC.
+ "resample": PILImageResampling.NEAREST,
+ }
+ )
+
+ processed_segmentation_maps = self._preprocess(
+ images=processed_segmentation_maps, **segmentation_maps_kwargs
+ )
+
+ processed_segmentation_maps = [
+ processed_segmentation_map.squeeze(0).to(torch.int64)
+ for processed_segmentation_map in processed_segmentation_maps
+ ]
+ data["labels"] = processed_segmentation_maps
+
+ return BatchFeature(data=data, tensor_type=return_tensors)
+
+ def reduce_label(self, labels: list["torch.Tensor"]) -> list["torch.Tensor"]:
+ """Reduce label values by 1, replacing 0 with 255."""
+ for idx in range(len(labels)):
+ label = labels[idx]
+ label = torch.where(label == 0, torch.tensor(255, dtype=label.dtype, device=label.device), label)
+ label = label - 1
+ label = torch.where(label == 254, torch.tensor(255, dtype=label.dtype, device=label.device), label)
+ labels[idx] = label
+ return labels
+
+ def flip_channel_order(self, images: "torch.Tensor") -> "torch.Tensor":
+ """Flip RGB to BGR or vice versa."""
+ if images.ndim == 3:
+ # Single image: (C, H, W)
+ flipped = images.clone()
+ flipped[0:3] = images[[2, 1, 0]]
+ return flipped
+ elif images.ndim == 4:
+ # Batched images: (B, C, H, W)
+ flipped = images.clone()
+ flipped[:, 0:3] = images[:, [2, 1, 0]]
+ return flipped
+ return images
+
+ def _preprocess(
+ self,
+ images: list["torch.Tensor"],
+ do_resize: bool,
+ size: SizeDict,
+ resample: "PILImageResampling | tvF.InterpolationMode | int | None",
+ do_center_crop: bool,
+ crop_size: SizeDict,
+ do_rescale: bool,
+ rescale_factor: float,
+ disable_grouping: bool | None,
+ do_reduce_labels: bool = False,
+ do_flip_channel_order: bool = True,
+ **kwargs,
+ ) -> list["torch.Tensor"]:
+ """Custom preprocessing for MobileViT."""
+ if do_reduce_labels:
+ images = self.reduce_label(images)
+
+ grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping)
+ resized_images_grouped = {}
+ for shape, stacked_images in grouped_images.items():
+ if do_resize:
+ stacked_images = self.resize(stacked_images, size, resample)
+ resized_images_grouped[shape] = stacked_images
+ resized_images = reorder_images(resized_images_grouped, grouped_images_index)
+
+ grouped_images, grouped_images_index = group_images_by_shape(resized_images, disable_grouping=disable_grouping)
+ processed_images_grouped = {}
+ for shape, stacked_images in grouped_images.items():
+ if do_center_crop:
+ stacked_images = self.center_crop(stacked_images, crop_size)
+ if do_rescale:
+ stacked_images = self.rescale(stacked_images, rescale_factor)
+ if do_flip_channel_order:
+ stacked_images = self.flip_channel_order(stacked_images)
+ processed_images_grouped[shape] = stacked_images
+ processed_images = reorder_images(processed_images_grouped, grouped_images_index)
+ return processed_images
+
+ def post_process_semantic_segmentation(self, outputs, target_sizes: list[tuple] | None = None):
+ """Converts the output of [`MobileViTForSemanticSegmentation`] into semantic segmentation maps."""
+ requires_backends(self, "torch")
+ logits = outputs.logits
+ if target_sizes is not None:
+ if len(logits) != len(target_sizes):
+ raise ValueError(
+ "Make sure that you pass in as many target sizes as the batch dimension of the logits"
+ )
+ if isinstance(target_sizes, torch.Tensor):
+ target_sizes = target_sizes.numpy()
+ semantic_segmentation = []
+ for idx in range(len(logits)):
+ resized_logits = torch.nn.functional.interpolate(
+ logits[idx].unsqueeze(dim=0), size=target_sizes[idx], mode="bilinear", align_corners=False
+ )
+ semantic_map = resized_logits[0].argmax(dim=0)
+ semantic_segmentation.append(semantic_map)
+ else:
+ semantic_segmentation = logits.argmax(dim=1)
+ semantic_segmentation = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0])]
+ return semantic_segmentation
+
+
+__all__ = ["MobileViTImageProcessor"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mobilevit/image_processing_pil_mobilevit.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mobilevit/image_processing_pil_mobilevit.py
new file mode 100644
index 0000000000000000000000000000000000000000..893e27fe4ccff64513a4a708ebae87d777375fd5
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mobilevit/image_processing_pil_mobilevit.py
@@ -0,0 +1,212 @@
+# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Image processor class for MobileViT."""
+
+from typing import TYPE_CHECKING
+
+import numpy as np
+
+
+if TYPE_CHECKING:
+ pass
+
+from ...image_processing_backends import PilBackend
+from ...image_processing_utils import BatchFeature
+from ...image_transforms import flip_channel_order as np_flip_channel_order
+from ...image_utils import (
+ IMAGENET_STANDARD_MEAN,
+ IMAGENET_STANDARD_STD,
+ ChannelDimension,
+ ImageInput,
+ PILImageResampling,
+ SizeDict,
+)
+from ...processing_utils import ImagesKwargs, Unpack
+from ...utils import TensorType, auto_docstring, logging
+from ...utils.import_utils import requires
+
+
+logger = logging.get_logger(__name__)
+
+
+# Adapted from transformers.models.mobilevit.image_processing_mobilevit.MobileVitImageProcessorKwargs
+class MobileVitImageProcessorKwargs(ImagesKwargs, total=False):
+ """
+ do_flip_channel_order (`bool`, *optional*, defaults to `self.do_flip_channel_order`):
+ Whether to flip the color channels from RGB to BGR or vice versa.
+ do_reduce_labels (`bool`, *optional*, defaults to `self.do_reduce_labels`):
+ Whether or not to reduce all label values of segmentation maps by 1. Usually used for datasets where 0
+ is used for background, and background itself is not included in all classes of a dataset (e.g.
+ ADE20k). The background label will be replaced by 255.
+ """
+
+ do_flip_channel_order: bool
+ do_reduce_labels: bool
+
+
+@auto_docstring
+class MobileViTImageProcessorPil(PilBackend):
+ """PIL backend for MobileViT with flip_channel_order and reduce_label support."""
+
+ valid_kwargs = MobileVitImageProcessorKwargs
+
+ resample = PILImageResampling.BICUBIC
+ image_mean = IMAGENET_STANDARD_MEAN
+ image_std = IMAGENET_STANDARD_STD
+ size = {"shortest_edge": 224}
+ default_to_square = False
+ crop_size = {"height": 256, "width": 256}
+ do_resize = True
+ do_center_crop = True
+ do_rescale = True
+ do_normalize = None
+ do_convert_rgb = None
+ do_flip_channel_order = True
+ do_reduce_labels = False
+
+ def __init__(self, **kwargs: Unpack[MobileVitImageProcessorKwargs]):
+ super().__init__(**kwargs)
+
+ @auto_docstring
+ def preprocess(
+ self,
+ images: ImageInput,
+ segmentation_maps: ImageInput | None = None,
+ **kwargs: Unpack[MobileVitImageProcessorKwargs],
+ ) -> BatchFeature:
+ r"""
+ segmentation_maps (`ImageInput`, *optional*):
+ The segmentation maps to preprocess.
+ """
+ return super().preprocess(images, segmentation_maps, **kwargs)
+
+ def _preprocess_image_like_inputs(
+ self,
+ images: ImageInput,
+ segmentation_maps: ImageInput | None,
+ do_convert_rgb: bool,
+ input_data_format: ChannelDimension,
+ return_tensors: str | TensorType | None,
+ device: str | None = None,
+ **kwargs,
+ ) -> BatchFeature:
+ """Handle extra inputs beyond images."""
+ images = self._prepare_image_like_inputs(
+ images=images, do_convert_rgb=do_convert_rgb, input_data_format=input_data_format, device=device
+ )
+ images_kwargs = kwargs.copy()
+ images_kwargs["do_reduce_labels"] = False
+ data = {}
+ data["pixel_values"] = self._preprocess(images, **images_kwargs)
+
+ if segmentation_maps is not None:
+ processed_segmentation_maps = self._prepare_image_like_inputs(
+ images=segmentation_maps,
+ expected_ndims=2,
+ do_convert_rgb=False,
+ input_data_format=ChannelDimension.FIRST,
+ )
+
+ segmentation_maps_kwargs = kwargs.copy()
+ segmentation_maps_kwargs.update(
+ {
+ "do_rescale": False,
+ "do_flip_channel_order": False,
+ # Nearest interpolation is used for segmentation maps instead of BICUBIC.
+ "resample": PILImageResampling.NEAREST,
+ }
+ )
+
+ processed_segmentation_maps = self._preprocess(
+ images=processed_segmentation_maps, **segmentation_maps_kwargs
+ )
+
+ processed_segmentation_maps = [
+ processed_segmentation_map.squeeze(0).astype(np.int64)
+ for processed_segmentation_map in processed_segmentation_maps
+ ]
+ data["labels"] = processed_segmentation_maps
+
+ return BatchFeature(data=data, tensor_type=return_tensors)
+
+ def reduce_label(self, image: np.ndarray) -> np.ndarray:
+ """Reduce label values by 1, replacing 0 with 255."""
+ image[image == 0] = 255
+ image = image - 1
+ image[image == 254] = 255
+ return image
+
+ def flip_channel_order(self, image: np.ndarray) -> np.ndarray:
+ """Flip RGB to BGR or vice versa."""
+ return np_flip_channel_order(
+ image, data_format=ChannelDimension.FIRST, input_data_format=ChannelDimension.FIRST
+ )
+
+ def _preprocess(
+ self,
+ images: list[np.ndarray],
+ do_resize: bool,
+ size: SizeDict,
+ resample: PILImageResampling | None,
+ do_center_crop: bool,
+ crop_size: SizeDict,
+ do_rescale: bool,
+ rescale_factor: float,
+ do_reduce_labels: bool = False,
+ do_flip_channel_order: bool = True,
+ **kwargs,
+ ) -> list[np.ndarray]:
+ """Custom preprocessing for MobileViT."""
+ processed_images = []
+ for image in images:
+ if do_reduce_labels:
+ image = self.reduce_label(image)
+ if do_resize:
+ image = self.resize(image, size, resample)
+ if do_rescale:
+ image = self.rescale(image, rescale_factor)
+ if do_center_crop:
+ image = self.center_crop(image, crop_size)
+ if do_flip_channel_order:
+ image = self.flip_channel_order(image)
+ processed_images.append(image)
+ return processed_images
+
+ @requires(backends=("torch",))
+ def post_process_semantic_segmentation(self, outputs, target_sizes: list[tuple] | None = None):
+ """Converts the output of [`MobileViTForSemanticSegmentation`] into semantic segmentation maps."""
+ import torch
+
+ logits = outputs.logits
+ if target_sizes is not None:
+ if len(logits) != len(target_sizes):
+ raise ValueError(
+ "Make sure that you pass in as many target sizes as the batch dimension of the logits"
+ )
+ if isinstance(target_sizes, torch.Tensor):
+ target_sizes = target_sizes.numpy()
+ semantic_segmentation = []
+ for idx in range(len(logits)):
+ resized_logits = torch.nn.functional.interpolate(
+ logits[idx].unsqueeze(dim=0), size=target_sizes[idx], mode="bilinear", align_corners=False
+ )
+ semantic_map = resized_logits[0].argmax(dim=0)
+ semantic_segmentation.append(semantic_map)
+ else:
+ semantic_segmentation = logits.argmax(dim=1)
+ semantic_segmentation = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0])]
+ return semantic_segmentation
+
+
+__all__ = ["MobileViTImageProcessorPil"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mobilevit/modeling_mobilevit.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mobilevit/modeling_mobilevit.py
new file mode 100644
index 0000000000000000000000000000000000000000..763360ef82117465be6fa08f8a595755403379f2
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mobilevit/modeling_mobilevit.py
@@ -0,0 +1,963 @@
+# Copyright 2022 Apple Inc. and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# Original license: https://github.com/apple/ml-cvnets/blob/main/LICENSE
+"""PyTorch MobileViT model."""
+
+import math
+
+import torch
+from torch import nn
+from torch.nn import CrossEntropyLoss
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import (
+ BaseModelOutputWithNoAttention,
+ BaseModelOutputWithPoolingAndNoAttention,
+ ImageClassifierOutputWithNoAttention,
+ SemanticSegmenterOutput,
+)
+from ...modeling_utils import PreTrainedModel
+from ...utils import auto_docstring, logging, torch_int
+from .configuration_mobilevit import MobileViTConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+def make_divisible(value: int, divisor: int = 8, min_value: int | None = None) -> int:
+ """
+ Ensure that all layers have a channel count that is divisible by `divisor`.
+ """
+ if min_value is None:
+ min_value = divisor
+ new_value = max(min_value, int(value + divisor / 2) // divisor * divisor)
+ # Make sure that round down does not go down by more than 10%.
+ if new_value < 0.9 * value:
+ new_value += divisor
+ return int(new_value)
+
+
+class MobileViTConvLayer(nn.Module):
+ def __init__(
+ self,
+ config: MobileViTConfig,
+ in_channels: int,
+ out_channels: int,
+ kernel_size: int,
+ stride: int = 1,
+ groups: int = 1,
+ bias: bool = False,
+ dilation: int = 1,
+ use_normalization: bool = True,
+ use_activation: bool | str = True,
+ ) -> None:
+ super().__init__()
+ padding = int((kernel_size - 1) / 2) * dilation
+
+ if in_channels % groups != 0:
+ raise ValueError(f"Input channels ({in_channels}) are not divisible by {groups} groups.")
+ if out_channels % groups != 0:
+ raise ValueError(f"Output channels ({out_channels}) are not divisible by {groups} groups.")
+
+ self.convolution = nn.Conv2d(
+ in_channels=in_channels,
+ out_channels=out_channels,
+ kernel_size=kernel_size,
+ stride=stride,
+ padding=padding,
+ dilation=dilation,
+ groups=groups,
+ bias=bias,
+ padding_mode="zeros",
+ )
+
+ if use_normalization:
+ self.normalization = nn.BatchNorm2d(
+ num_features=out_channels,
+ eps=1e-5,
+ momentum=0.1,
+ affine=True,
+ track_running_stats=True,
+ )
+ else:
+ self.normalization = None
+
+ if use_activation:
+ if isinstance(use_activation, str):
+ self.activation = ACT2FN[use_activation]
+ elif isinstance(config.hidden_act, str):
+ self.activation = ACT2FN[config.hidden_act]
+ else:
+ self.activation = config.hidden_act
+ else:
+ self.activation = None
+
+ def forward(self, features: torch.Tensor) -> torch.Tensor:
+ features = self.convolution(features)
+ if self.normalization is not None:
+ features = self.normalization(features)
+ if self.activation is not None:
+ features = self.activation(features)
+ return features
+
+
+class MobileViTInvertedResidual(nn.Module):
+ """
+ Inverted residual block (MobileNetv2): https://huggingface.co/papers/1801.04381
+ """
+
+ def __init__(
+ self, config: MobileViTConfig, in_channels: int, out_channels: int, stride: int, dilation: int = 1
+ ) -> None:
+ super().__init__()
+ expanded_channels = make_divisible(int(round(in_channels * config.expand_ratio)), 8)
+
+ if stride not in [1, 2]:
+ raise ValueError(f"Invalid stride {stride}.")
+
+ self.use_residual = (stride == 1) and (in_channels == out_channels)
+
+ self.expand_1x1 = MobileViTConvLayer(
+ config, in_channels=in_channels, out_channels=expanded_channels, kernel_size=1
+ )
+
+ self.conv_3x3 = MobileViTConvLayer(
+ config,
+ in_channels=expanded_channels,
+ out_channels=expanded_channels,
+ kernel_size=3,
+ stride=stride,
+ groups=expanded_channels,
+ dilation=dilation,
+ )
+
+ self.reduce_1x1 = MobileViTConvLayer(
+ config,
+ in_channels=expanded_channels,
+ out_channels=out_channels,
+ kernel_size=1,
+ use_activation=False,
+ )
+
+ def forward(self, features: torch.Tensor) -> torch.Tensor:
+ residual = features
+
+ features = self.expand_1x1(features)
+ features = self.conv_3x3(features)
+ features = self.reduce_1x1(features)
+
+ return residual + features if self.use_residual else features
+
+
+class MobileViTMobileNetLayer(nn.Module):
+ def __init__(
+ self, config: MobileViTConfig, in_channels: int, out_channels: int, stride: int = 1, num_stages: int = 1
+ ) -> None:
+ super().__init__()
+
+ self.layer = nn.ModuleList()
+ for i in range(num_stages):
+ layer = MobileViTInvertedResidual(
+ config,
+ in_channels=in_channels,
+ out_channels=out_channels,
+ stride=stride if i == 0 else 1,
+ )
+ self.layer.append(layer)
+ in_channels = out_channels
+
+ def forward(self, features: torch.Tensor) -> torch.Tensor:
+ for layer_module in self.layer:
+ features = layer_module(features)
+ return features
+
+
+class MobileViTSelfAttention(nn.Module):
+ def __init__(self, config: MobileViTConfig, hidden_size: int) -> None:
+ super().__init__()
+
+ if hidden_size % config.num_attention_heads != 0:
+ raise ValueError(
+ f"The hidden size {hidden_size} is not a multiple of the number of attention "
+ f"heads {config.num_attention_heads}."
+ )
+
+ self.num_attention_heads = config.num_attention_heads
+ self.attention_head_size = int(hidden_size / config.num_attention_heads)
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
+
+ self.query = nn.Linear(hidden_size, self.all_head_size, bias=config.qkv_bias)
+ self.key = nn.Linear(hidden_size, self.all_head_size, bias=config.qkv_bias)
+ self.value = nn.Linear(hidden_size, self.all_head_size, bias=config.qkv_bias)
+
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ input_shape = hidden_states.shape[:-1]
+ hidden_shape = (*input_shape, -1, self.attention_head_size)
+ query_layer = self.query(hidden_states).view(hidden_shape).transpose(1, 2)
+ key_layer = self.key(hidden_states).view(hidden_shape).transpose(1, 2)
+ value_layer = self.value(hidden_states).view(hidden_shape).transpose(1, 2)
+
+ # Take the dot product between "query" and "key" to get the raw attention scores.
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
+
+ # Normalize the attention scores to probabilities.
+ attention_probs = nn.functional.softmax(attention_scores, dim=-1)
+
+ # This is actually dropping out entire tokens to attend to, which might
+ # seem a bit unusual, but is taken from the original Transformer paper.
+ attention_probs = self.dropout(attention_probs)
+
+ context_layer = torch.matmul(attention_probs, value_layer)
+
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
+ context_layer = context_layer.view(*new_context_layer_shape)
+ return context_layer
+
+
+class MobileViTSelfOutput(nn.Module):
+ def __init__(self, config: MobileViTConfig, hidden_size: int) -> None:
+ super().__init__()
+ self.dense = nn.Linear(hidden_size, hidden_size)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ return hidden_states
+
+
+class MobileViTAttention(nn.Module):
+ def __init__(self, config: MobileViTConfig, hidden_size: int) -> None:
+ super().__init__()
+ self.attention = MobileViTSelfAttention(config, hidden_size)
+ self.output = MobileViTSelfOutput(config, hidden_size)
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ self_outputs = self.attention(hidden_states)
+ attention_output = self.output(self_outputs)
+ return attention_output
+
+
+class MobileViTIntermediate(nn.Module):
+ def __init__(self, config: MobileViTConfig, hidden_size: int, intermediate_size: int) -> None:
+ super().__init__()
+ self.dense = nn.Linear(hidden_size, intermediate_size)
+ if isinstance(config.hidden_act, str):
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
+ else:
+ self.intermediate_act_fn = config.hidden_act
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.intermediate_act_fn(hidden_states)
+ return hidden_states
+
+
+class MobileViTOutput(nn.Module):
+ def __init__(self, config: MobileViTConfig, hidden_size: int, intermediate_size: int) -> None:
+ super().__init__()
+ self.dense = nn.Linear(intermediate_size, hidden_size)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = hidden_states + input_tensor
+ return hidden_states
+
+
+class MobileViTTransformerLayer(nn.Module):
+ def __init__(self, config: MobileViTConfig, hidden_size: int, intermediate_size: int) -> None:
+ super().__init__()
+ self.attention = MobileViTAttention(config, hidden_size)
+ self.intermediate = MobileViTIntermediate(config, hidden_size, intermediate_size)
+ self.output = MobileViTOutput(config, hidden_size, intermediate_size)
+ self.layernorm_before = nn.LayerNorm(hidden_size, eps=config.layer_norm_eps)
+ self.layernorm_after = nn.LayerNorm(hidden_size, eps=config.layer_norm_eps)
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ attention_output = self.attention(self.layernorm_before(hidden_states))
+ hidden_states = attention_output + hidden_states
+
+ layer_output = self.layernorm_after(hidden_states)
+ layer_output = self.intermediate(layer_output)
+ layer_output = self.output(layer_output, hidden_states)
+ return layer_output
+
+
+class MobileViTTransformer(nn.Module):
+ def __init__(self, config: MobileViTConfig, hidden_size: int, num_stages: int) -> None:
+ super().__init__()
+
+ self.layer = nn.ModuleList()
+ for _ in range(num_stages):
+ transformer_layer = MobileViTTransformerLayer(
+ config,
+ hidden_size=hidden_size,
+ intermediate_size=int(hidden_size * config.mlp_ratio),
+ )
+ self.layer.append(transformer_layer)
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ for layer_module in self.layer:
+ hidden_states = layer_module(hidden_states)
+ return hidden_states
+
+
+class MobileViTLayer(GradientCheckpointingLayer):
+ """
+ MobileViT block: https://huggingface.co/papers/2110.02178
+ """
+
+ def __init__(
+ self,
+ config: MobileViTConfig,
+ in_channels: int,
+ out_channels: int,
+ stride: int,
+ hidden_size: int,
+ num_stages: int,
+ dilation: int = 1,
+ ) -> None:
+ super().__init__()
+ self.patch_width = config.patch_size
+ self.patch_height = config.patch_size
+
+ if stride == 2:
+ self.downsampling_layer = MobileViTInvertedResidual(
+ config,
+ in_channels=in_channels,
+ out_channels=out_channels,
+ stride=stride if dilation == 1 else 1,
+ dilation=dilation // 2 if dilation > 1 else 1,
+ )
+ in_channels = out_channels
+ else:
+ self.downsampling_layer = None
+
+ self.conv_kxk = MobileViTConvLayer(
+ config,
+ in_channels=in_channels,
+ out_channels=in_channels,
+ kernel_size=config.conv_kernel_size,
+ )
+
+ self.conv_1x1 = MobileViTConvLayer(
+ config,
+ in_channels=in_channels,
+ out_channels=hidden_size,
+ kernel_size=1,
+ use_normalization=False,
+ use_activation=False,
+ )
+
+ self.transformer = MobileViTTransformer(
+ config,
+ hidden_size=hidden_size,
+ num_stages=num_stages,
+ )
+
+ self.layernorm = nn.LayerNorm(hidden_size, eps=config.layer_norm_eps)
+
+ self.conv_projection = MobileViTConvLayer(
+ config, in_channels=hidden_size, out_channels=in_channels, kernel_size=1
+ )
+
+ self.fusion = MobileViTConvLayer(
+ config, in_channels=2 * in_channels, out_channels=in_channels, kernel_size=config.conv_kernel_size
+ )
+
+ def unfolding(self, features: torch.Tensor) -> tuple[torch.Tensor, dict]:
+ patch_width, patch_height = self.patch_width, self.patch_height
+ patch_area = int(patch_width * patch_height)
+
+ batch_size, channels, orig_height, orig_width = features.shape
+
+ new_height = (
+ torch_int(torch.ceil(orig_height / patch_height) * patch_height)
+ if torch.jit.is_tracing()
+ else int(math.ceil(orig_height / patch_height) * patch_height)
+ )
+ new_width = (
+ torch_int(torch.ceil(orig_width / patch_width) * patch_width)
+ if torch.jit.is_tracing()
+ else int(math.ceil(orig_width / patch_width) * patch_width)
+ )
+
+ interpolate = False
+ if new_width != orig_width or new_height != orig_height:
+ # Note: Padding can be done, but then it needs to be handled in attention function.
+ features = nn.functional.interpolate(
+ features, size=(new_height, new_width), mode="bilinear", align_corners=False
+ )
+ interpolate = True
+
+ # number of patches along width and height
+ num_patch_width = new_width // patch_width
+ num_patch_height = new_height // patch_height
+ num_patches = num_patch_height * num_patch_width
+
+ # convert from shape (batch_size, channels, orig_height, orig_width)
+ # to the shape (batch_size * patch_area, num_patches, channels)
+ patches = features.reshape(
+ batch_size * channels * num_patch_height, patch_height, num_patch_width, patch_width
+ )
+ patches = patches.transpose(1, 2)
+ patches = patches.reshape(batch_size, channels, num_patches, patch_area)
+ patches = patches.transpose(1, 3)
+ patches = patches.reshape(batch_size * patch_area, num_patches, -1)
+
+ info_dict = {
+ "orig_size": (orig_height, orig_width),
+ "batch_size": batch_size,
+ "channels": channels,
+ "interpolate": interpolate,
+ "num_patches": num_patches,
+ "num_patches_width": num_patch_width,
+ "num_patches_height": num_patch_height,
+ }
+ return patches, info_dict
+
+ def folding(self, patches: torch.Tensor, info_dict: dict) -> torch.Tensor:
+ patch_width, patch_height = self.patch_width, self.patch_height
+ patch_area = int(patch_width * patch_height)
+
+ batch_size = info_dict["batch_size"]
+ channels = info_dict["channels"]
+ num_patches = info_dict["num_patches"]
+ num_patch_height = info_dict["num_patches_height"]
+ num_patch_width = info_dict["num_patches_width"]
+
+ # convert from shape (batch_size * patch_area, num_patches, channels)
+ # back to shape (batch_size, channels, orig_height, orig_width)
+ features = patches.contiguous().view(batch_size, patch_area, num_patches, -1)
+ features = features.transpose(1, 3)
+ features = features.reshape(
+ batch_size * channels * num_patch_height, num_patch_width, patch_height, patch_width
+ )
+ features = features.transpose(1, 2)
+ features = features.reshape(
+ batch_size, channels, num_patch_height * patch_height, num_patch_width * patch_width
+ )
+
+ if info_dict["interpolate"]:
+ features = nn.functional.interpolate(
+ features, size=info_dict["orig_size"], mode="bilinear", align_corners=False
+ )
+
+ return features
+
+ def forward(self, features: torch.Tensor) -> torch.Tensor:
+ # reduce spatial dimensions if needed
+ if self.downsampling_layer:
+ features = self.downsampling_layer(features)
+
+ residual = features
+
+ # local representation
+ features = self.conv_kxk(features)
+ features = self.conv_1x1(features)
+
+ # convert feature map to patches
+ patches, info_dict = self.unfolding(features)
+
+ # learn global representations
+ patches = self.transformer(patches)
+ patches = self.layernorm(patches)
+
+ # convert patches back to feature maps
+ features = self.folding(patches, info_dict)
+
+ features = self.conv_projection(features)
+ features = self.fusion(torch.cat((residual, features), dim=1))
+ return features
+
+
+class MobileViTEncoder(nn.Module):
+ def __init__(self, config: MobileViTConfig) -> None:
+ super().__init__()
+ self.config = config
+
+ self.layer = nn.ModuleList()
+ self.gradient_checkpointing = False
+
+ # segmentation architectures like DeepLab and PSPNet modify the strides
+ # of the classification backbones
+ dilate_layer_4 = dilate_layer_5 = False
+ if config.output_stride == 8:
+ dilate_layer_4 = True
+ dilate_layer_5 = True
+ elif config.output_stride == 16:
+ dilate_layer_5 = True
+
+ dilation = 1
+
+ layer_1 = MobileViTMobileNetLayer(
+ config,
+ in_channels=config.neck_hidden_sizes[0],
+ out_channels=config.neck_hidden_sizes[1],
+ stride=1,
+ num_stages=1,
+ )
+ self.layer.append(layer_1)
+
+ layer_2 = MobileViTMobileNetLayer(
+ config,
+ in_channels=config.neck_hidden_sizes[1],
+ out_channels=config.neck_hidden_sizes[2],
+ stride=2,
+ num_stages=3,
+ )
+ self.layer.append(layer_2)
+
+ layer_3 = MobileViTLayer(
+ config,
+ in_channels=config.neck_hidden_sizes[2],
+ out_channels=config.neck_hidden_sizes[3],
+ stride=2,
+ hidden_size=config.hidden_sizes[0],
+ num_stages=2,
+ )
+ self.layer.append(layer_3)
+
+ if dilate_layer_4:
+ dilation *= 2
+
+ layer_4 = MobileViTLayer(
+ config,
+ in_channels=config.neck_hidden_sizes[3],
+ out_channels=config.neck_hidden_sizes[4],
+ stride=2,
+ hidden_size=config.hidden_sizes[1],
+ num_stages=4,
+ dilation=dilation,
+ )
+ self.layer.append(layer_4)
+
+ if dilate_layer_5:
+ dilation *= 2
+
+ layer_5 = MobileViTLayer(
+ config,
+ in_channels=config.neck_hidden_sizes[4],
+ out_channels=config.neck_hidden_sizes[5],
+ stride=2,
+ hidden_size=config.hidden_sizes[2],
+ num_stages=3,
+ dilation=dilation,
+ )
+ self.layer.append(layer_5)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ output_hidden_states: bool = False,
+ return_dict: bool = True,
+ ) -> tuple | BaseModelOutputWithNoAttention:
+ all_hidden_states = () if output_hidden_states else None
+
+ for i, layer_module in enumerate(self.layer):
+ hidden_states = layer_module(hidden_states)
+
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ if not return_dict:
+ return tuple(v for v in [hidden_states, all_hidden_states] if v is not None)
+
+ return BaseModelOutputWithNoAttention(last_hidden_state=hidden_states, hidden_states=all_hidden_states)
+
+
+@auto_docstring
+class MobileViTPreTrainedModel(PreTrainedModel):
+ config: MobileViTConfig
+ base_model_prefix = "mobilevit"
+ main_input_name = "pixel_values"
+ input_modalities = ("image",)
+ supports_gradient_checkpointing = True
+ _no_split_modules = ["MobileViTLayer"]
+
+ @torch.no_grad()
+ def _init_weights(self, module: nn.Module) -> None:
+ """Initialize the weights"""
+ if isinstance(module, (nn.Linear, nn.Conv2d, nn.BatchNorm2d)):
+ init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
+ if module.bias is not None:
+ init.zeros_(module.bias)
+ if getattr(module, "running_mean", None) is not None:
+ init.zeros_(module.running_mean)
+ init.ones_(module.running_var)
+ init.zeros_(module.num_batches_tracked)
+ elif isinstance(module, nn.LayerNorm):
+ init.zeros_(module.bias)
+ init.ones_(module.weight)
+
+
+@auto_docstring
+class MobileViTModel(MobileViTPreTrainedModel):
+ def __init__(self, config: MobileViTConfig, expand_output: bool = True):
+ r"""
+ expand_output (`bool`, *optional*, defaults to `True`):
+ Whether to expand the output of the model using a 1x1 convolution. If `True`, the model will apply an additional
+ 1x1 convolution to expand the output channels from `config.neck_hidden_sizes[5]` to `config.neck_hidden_sizes[6]`.
+ """
+ super().__init__(config)
+ self.config = config
+ self.expand_output = expand_output
+
+ self.conv_stem = MobileViTConvLayer(
+ config,
+ in_channels=config.num_channels,
+ out_channels=config.neck_hidden_sizes[0],
+ kernel_size=3,
+ stride=2,
+ )
+
+ self.encoder = MobileViTEncoder(config)
+
+ if self.expand_output:
+ self.conv_1x1_exp = MobileViTConvLayer(
+ config,
+ in_channels=config.neck_hidden_sizes[5],
+ out_channels=config.neck_hidden_sizes[6],
+ kernel_size=1,
+ )
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: torch.Tensor | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple | BaseModelOutputWithPoolingAndNoAttention:
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ if pixel_values is None:
+ raise ValueError("You have to specify pixel_values")
+
+ embedding_output = self.conv_stem(pixel_values)
+
+ encoder_outputs = self.encoder(
+ embedding_output,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ if self.expand_output:
+ last_hidden_state = self.conv_1x1_exp(encoder_outputs[0])
+
+ # global average pooling: (batch_size, channels, height, width) -> (batch_size, channels)
+ pooled_output = torch.mean(last_hidden_state, dim=[-2, -1], keepdim=False)
+ else:
+ last_hidden_state = encoder_outputs[0]
+ pooled_output = None
+
+ if not return_dict:
+ output = (last_hidden_state, pooled_output) if pooled_output is not None else (last_hidden_state,)
+ return output + encoder_outputs[1:]
+
+ return BaseModelOutputWithPoolingAndNoAttention(
+ last_hidden_state=last_hidden_state,
+ pooler_output=pooled_output,
+ hidden_states=encoder_outputs.hidden_states,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ MobileViT model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
+ ImageNet.
+ """
+)
+class MobileViTForImageClassification(MobileViTPreTrainedModel):
+ def __init__(self, config: MobileViTConfig) -> None:
+ super().__init__(config)
+
+ self.num_labels = config.num_labels
+ self.mobilevit = MobileViTModel(config)
+
+ # Classifier head
+ self.dropout = nn.Dropout(config.classifier_dropout_prob, inplace=True)
+ self.classifier = (
+ nn.Linear(config.neck_hidden_sizes[-1], config.num_labels) if config.num_labels > 0 else nn.Identity()
+ )
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: torch.Tensor | None = None,
+ output_hidden_states: bool | None = None,
+ labels: torch.Tensor | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple | ImageClassifierOutputWithNoAttention:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss). If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ outputs = self.mobilevit(pixel_values, output_hidden_states=output_hidden_states, return_dict=return_dict)
+
+ pooled_output = outputs.pooler_output if return_dict else outputs[1]
+
+ logits = self.classifier(self.dropout(pooled_output))
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(labels, logits, self.config)
+
+ if not return_dict:
+ output = (logits,) + outputs[2:]
+ return ((loss,) + output) if loss is not None else output
+
+ return ImageClassifierOutputWithNoAttention(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ )
+
+
+class MobileViTASPPPooling(nn.Module):
+ def __init__(self, config: MobileViTConfig, in_channels: int, out_channels: int) -> None:
+ super().__init__()
+
+ self.global_pool = nn.AdaptiveAvgPool2d(output_size=1)
+
+ self.conv_1x1 = MobileViTConvLayer(
+ config,
+ in_channels=in_channels,
+ out_channels=out_channels,
+ kernel_size=1,
+ stride=1,
+ use_normalization=True,
+ use_activation="relu",
+ )
+
+ def forward(self, features: torch.Tensor) -> torch.Tensor:
+ spatial_size = features.shape[-2:]
+ features = self.global_pool(features)
+ features = self.conv_1x1(features)
+ features = nn.functional.interpolate(features, size=spatial_size, mode="bilinear", align_corners=False)
+ return features
+
+
+class MobileViTASPP(nn.Module):
+ """
+ ASPP module defined in DeepLab papers: https://huggingface.co/papers/1606.00915, https://huggingface.co/papers/1706.05587
+ """
+
+ def __init__(self, config: MobileViTConfig) -> None:
+ super().__init__()
+
+ in_channels = config.neck_hidden_sizes[-2]
+ out_channels = config.aspp_out_channels
+
+ if len(config.atrous_rates) != 3:
+ raise ValueError("Expected 3 values for atrous_rates")
+
+ self.convs = nn.ModuleList()
+
+ in_projection = MobileViTConvLayer(
+ config,
+ in_channels=in_channels,
+ out_channels=out_channels,
+ kernel_size=1,
+ use_activation="relu",
+ )
+ self.convs.append(in_projection)
+
+ self.convs.extend(
+ [
+ MobileViTConvLayer(
+ config,
+ in_channels=in_channels,
+ out_channels=out_channels,
+ kernel_size=3,
+ dilation=rate,
+ use_activation="relu",
+ )
+ for rate in config.atrous_rates
+ ]
+ )
+
+ pool_layer = MobileViTASPPPooling(config, in_channels, out_channels)
+ self.convs.append(pool_layer)
+
+ self.project = MobileViTConvLayer(
+ config, in_channels=5 * out_channels, out_channels=out_channels, kernel_size=1, use_activation="relu"
+ )
+
+ self.dropout = nn.Dropout(p=config.aspp_dropout_prob)
+
+ def forward(self, features: torch.Tensor) -> torch.Tensor:
+ pyramid = []
+ for conv in self.convs:
+ pyramid.append(conv(features))
+ pyramid = torch.cat(pyramid, dim=1)
+
+ pooled_features = self.project(pyramid)
+ pooled_features = self.dropout(pooled_features)
+ return pooled_features
+
+
+class MobileViTDeepLabV3(nn.Module):
+ """
+ DeepLabv3 architecture: https://huggingface.co/papers/1706.05587
+ """
+
+ def __init__(self, config: MobileViTConfig) -> None:
+ super().__init__()
+ self.aspp = MobileViTASPP(config)
+
+ self.dropout = nn.Dropout2d(config.classifier_dropout_prob)
+
+ self.classifier = MobileViTConvLayer(
+ config,
+ in_channels=config.aspp_out_channels,
+ out_channels=config.num_labels,
+ kernel_size=1,
+ use_normalization=False,
+ use_activation=False,
+ bias=True,
+ )
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ features = self.aspp(hidden_states[-1])
+ features = self.dropout(features)
+ features = self.classifier(features)
+ return features
+
+
+@auto_docstring(
+ custom_intro="""
+ MobileViT model with a semantic segmentation head on top, e.g. for Pascal VOC.
+ """
+)
+class MobileViTForSemanticSegmentation(MobileViTPreTrainedModel):
+ def __init__(self, config: MobileViTConfig) -> None:
+ super().__init__(config)
+
+ self.num_labels = config.num_labels
+ self.mobilevit = MobileViTModel(config, expand_output=False)
+ self.segmentation_head = MobileViTDeepLabV3(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: torch.Tensor | None = None,
+ labels: torch.Tensor | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple | SemanticSegmenterOutput:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, height, width)`, *optional*):
+ Ground truth semantic segmentation maps for computing the loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels > 1`, a classification loss is computed (Cross-Entropy).
+
+ Examples:
+
+ ```python
+ >>> import httpx
+ >>> from io import BytesIO
+ >>> import torch
+ >>> from PIL import Image
+ >>> from transformers import AutoImageProcessor, MobileViTForSemanticSegmentation
+
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
+ >>> with httpx.stream("GET", url) as response:
+ ... image = Image.open(BytesIO(response.read()))
+
+ >>> image_processor = AutoImageProcessor.from_pretrained("apple/deeplabv3-mobilevit-small")
+ >>> model = MobileViTForSemanticSegmentation.from_pretrained("apple/deeplabv3-mobilevit-small")
+
+ >>> inputs = image_processor(images=image, return_tensors="pt")
+
+ >>> with torch.no_grad():
+ ... outputs = model(**inputs)
+
+ >>> # logits are of shape (batch_size, num_labels, height, width)
+ >>> logits = outputs.logits
+ ```"""
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ if labels is not None and self.config.num_labels == 1:
+ raise ValueError("The number of labels should be greater than one")
+
+ outputs = self.mobilevit(
+ pixel_values,
+ output_hidden_states=True, # we need the intermediate hidden states
+ return_dict=return_dict,
+ )
+
+ encoder_hidden_states = outputs.hidden_states if return_dict else outputs[1]
+
+ logits = self.segmentation_head(encoder_hidden_states)
+
+ loss = None
+ if labels is not None:
+ # upsample logits to the images' original size
+ upsampled_logits = nn.functional.interpolate(
+ logits, size=labels.shape[-2:], mode="bilinear", align_corners=False
+ )
+ loss_fct = CrossEntropyLoss(ignore_index=self.config.semantic_loss_ignore_index)
+ loss = loss_fct(upsampled_logits, labels)
+
+ if not return_dict:
+ if output_hidden_states:
+ output = (logits,) + outputs[1:]
+ else:
+ output = (logits,) + outputs[2:]
+ return ((loss,) + output) if loss is not None else output
+
+ return SemanticSegmenterOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states if output_hidden_states else None,
+ attentions=None,
+ )
+
+
+__all__ = [
+ "MobileViTForImageClassification",
+ "MobileViTForSemanticSegmentation",
+ "MobileViTModel",
+ "MobileViTPreTrainedModel",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/moonshine/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/moonshine/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..fa3c1870c2a1d6f5d089df5a396d4b049e4a9d4e
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/moonshine/__init__.py
@@ -0,0 +1,27 @@
+# Copyright 2025 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_moonshine import *
+ from .modeling_moonshine import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/moonshine/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/moonshine/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..37b53d176b49f2fb0969e6b0145f2f5279a7d30f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/moonshine/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/moonshine/__pycache__/configuration_moonshine.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/moonshine/__pycache__/configuration_moonshine.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..64d34a39765c16e1ac4226cbcd9b23e9e7d4257d
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/moonshine/__pycache__/configuration_moonshine.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/moonshine/__pycache__/modeling_moonshine.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/moonshine/__pycache__/modeling_moonshine.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..034bcd90395cea8afe7d9768c58fbba55d9f206f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/moonshine/__pycache__/modeling_moonshine.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/moonshine/__pycache__/modular_moonshine.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/moonshine/__pycache__/modular_moonshine.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dc82d3e92be1699172c2a5f2c4598970104e0e5e
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/moonshine/__pycache__/modular_moonshine.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/moonshine/configuration_moonshine.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/moonshine/configuration_moonshine.py
new file mode 100644
index 0000000000000000000000000000000000000000..9cb7adbfe59428b92e2ee66282159f1bdd492640
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/moonshine/configuration_moonshine.py
@@ -0,0 +1,116 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/moonshine/modular_moonshine.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_moonshine.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2025 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...modeling_rope_utils import RopeParameters
+from ...utils import auto_docstring
+
+
+@auto_docstring(checkpoint="UsefulSensors/moonshine-tiny")
+@strict
+class MoonshineConfig(PreTrainedConfig):
+ r"""
+ encoder_num_key_value_heads (`int`, *optional*):
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
+ `encoder_num_key_value_heads=encoder_num_attention_heads`, the model will use Multi Head Attention (MHA), if
+ `encoder_num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
+ by meanpooling all the original heads within that group. For more details, check out [this
+ paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to
+ `num_attention_heads`.
+ decoder_num_key_value_heads (`int`, *optional*):
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
+ `decoder_num_key_value_heads=decoder_num_attention_heads`, the model will use Multi Head Attention (MHA), if
+ `decoder_num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
+ by meanpooling all the original heads within that group. For more details, check out [this
+ paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to
+ `decoder_num_attention_heads`.
+ pad_head_dim_to_multiple_of (`int`, *optional*):
+ Pad head dimension in encoder and decoder to the next multiple of this value. Necessary for using certain
+ optimized attention implementations.
+ encoder_hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
+ The non-linear activation function (function or string) in the encoder.
+ decoder_hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
+ The non-linear activation function (function or string) in the decoder.
+
+ Example:
+
+ ```python
+ >>> from transformers import MoonshineModel, MoonshineConfig
+
+ >>> # Initializing a Moonshine style configuration
+ >>> configuration = MoonshineConfig().from_pretrained("UsefulSensors/moonshine-tiny")
+
+ >>> # Initializing a model from the configuration
+ >>> model = MoonshineModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "moonshine"
+ keys_to_ignore_at_inference = ["past_key_values"]
+ attribute_map = {
+ "num_key_value_heads": "decoder_num_key_value_heads",
+ "num_attention_heads": "decoder_num_attention_heads",
+ "num_hidden_layers": "decoder_num_hidden_layers",
+ "hidden_act": "decoder_hidden_act",
+ }
+
+ vocab_size: int = 32768
+ hidden_size: int = 288
+ intermediate_size: int = 1152
+ encoder_num_hidden_layers: int = 6
+ decoder_num_hidden_layers: int = 6
+ encoder_num_attention_heads: int = 8
+ decoder_num_attention_heads: int = 8
+ encoder_num_key_value_heads: int | None = None
+ decoder_num_key_value_heads: int | None = None
+ pad_head_dim_to_multiple_of: int | None = None
+ encoder_hidden_act: str = "gelu"
+ decoder_hidden_act: str = "silu"
+ max_position_embeddings: int = 512
+ initializer_range: float = 0.02
+ decoder_start_token_id: int = 1
+ use_cache: bool = True
+ rope_parameters: RopeParameters | dict | None = None
+ is_encoder_decoder: bool = True
+ attention_bias: bool = False
+ attention_dropout: float | int = 0.0
+ bos_token_id: int | None = 1
+ eos_token_id: int | list[int] | None = 2
+ pad_token_id: int | None = None
+ tie_word_embeddings: bool = True
+
+ def __post_init__(self, **kwargs):
+ if self.encoder_num_key_value_heads is None:
+ self.encoder_num_key_value_heads = self.encoder_num_attention_heads
+
+ if self.decoder_num_key_value_heads is None:
+ self.decoder_num_key_value_heads = self.decoder_num_attention_heads
+
+ kwargs.setdefault("partial_rotary_factor", 0.9) # assign default for BC
+ super().__post_init__(**kwargs)
+
+
+__all__ = ["MoonshineConfig"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/moonshine/modeling_moonshine.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/moonshine/modeling_moonshine.py
new file mode 100644
index 0000000000000000000000000000000000000000..c19a3f19b5745e7f9c337f0c76f45af0b2eaf0a7
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/moonshine/modeling_moonshine.py
@@ -0,0 +1,953 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/moonshine/modular_moonshine.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_moonshine.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2025 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from collections.abc import Callable
+from dataclasses import dataclass
+from typing import Optional
+
+import torch
+import torch.nn as nn
+
+from ...activations import ACT2FN
+from ...cache_utils import Cache, DynamicCache, EncoderDecoderCache
+from ...generation import GenerationMixin
+from ...integrations import use_kernelized_func
+from ...masking_utils import create_bidirectional_mask, create_causal_mask
+from ...modeling_flash_attention_utils import FlashAttentionKwargs
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import (
+ BaseModelOutput,
+ BaseModelOutputWithPast,
+ BaseModelOutputWithPastAndCrossAttentions,
+ Seq2SeqLMOutput,
+ Seq2SeqModelOutput,
+)
+from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import TransformersKwargs, auto_docstring, can_return_tuple
+from ...utils.generic import maybe_autocast, merge_with_config_defaults
+from ...utils.output_capturing import OutputRecorder, capture_outputs
+from .configuration_moonshine import MoonshineConfig
+
+
+@auto_docstring(
+ custom_intro="""
+ Extends [~modeling_outputs.BaseModelOutput] to include the output attention mask since sequence length is not preserved in the model's forward.
+ """
+)
+@dataclass
+class MoonshineEncoderModelOutput(BaseModelOutput):
+ r"""
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Mask to avoid performing attention on padding token indices after sequence compression. Returned because the
+ sequence length may differ from the input sequence length. Mask values selected in `[0, 1]`:
+
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+ """
+
+ attention_mask: torch.Tensor | None = None
+
+
+class MoonshineEncoderMLP(nn.Module):
+ def __init__(self, config, hidden_act):
+ super().__init__()
+ self.config = config
+ self.activation_fn = ACT2FN[hidden_act]
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.fc1(hidden_states)
+ hidden_states = self.activation_fn(hidden_states)
+ hidden_states = self.fc2(hidden_states)
+ return hidden_states
+
+
+class MoonshineDecoderMLP(nn.Module):
+ def __init__(self, config, hidden_act):
+ super().__init__()
+ self.config = config
+ self.activation_fn = ACT2FN[hidden_act]
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size * 2)
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.fc1(hidden_states)
+ hidden_states, gate = hidden_states.chunk(2, dim=-1)
+ hidden_states = self.activation_fn(gate) * hidden_states
+ hidden_states = self.fc2(hidden_states)
+ return hidden_states
+
+
+class MoonshineRotaryEmbedding(nn.Module):
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
+
+ def __init__(self, config: MoonshineConfig, device=None):
+ super().__init__()
+ self.max_seq_len_cached = config.max_position_embeddings
+ self.original_max_seq_len = config.max_position_embeddings
+
+ self.config = config
+
+ self.rope_type = self.config.rope_parameters["rope_type"]
+ rope_init_fn: Callable = self.compute_default_rope_parameters
+ if self.rope_type != "default":
+ rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
+ inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
+
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
+ self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
+
+ @staticmethod
+ def compute_default_rope_parameters(
+ config: MoonshineConfig | None = None,
+ device: Optional["torch.device"] = None,
+ seq_len: int | None = None,
+ ) -> tuple["torch.Tensor", float]:
+ """
+ Computes the inverse frequencies according to the original RoPE implementation
+ Args:
+ config ([`~transformers.PreTrainedConfig`]):
+ The model configuration.
+ device (`torch.device`):
+ The device to use for initialization of the inverse frequencies.
+ seq_len (`int`, *optional*):
+ The current sequence length. Unused for this type of RoPE.
+ Returns:
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
+ """
+ base = config.rope_parameters["rope_theta"]
+ partial_rotary_factor = config.rope_parameters.get("partial_rotary_factor", 1.0)
+ head_dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
+ dim = int(head_dim * partial_rotary_factor)
+
+ attention_factor = 1.0 # Unused in this type of RoPE
+
+ # Compute the inverse frequencies
+ inv_freq = 1.0 / (
+ base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
+ )
+ return inv_freq, attention_factor
+
+ @torch.no_grad()
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
+ def forward(self, x, position_ids):
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
+ position_ids_expanded = position_ids[:, None, :].float()
+
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
+ with maybe_autocast(device_type=device_type, enabled=False): # Force float32
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
+ emb = torch.cat((freqs, freqs), dim=-1)
+ cos = emb.cos() * self.attention_scaling
+ sin = emb.sin() * self.attention_scaling
+
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
+
+
+def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
+ """
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
+ """
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
+ if n_rep == 1:
+ return hidden_states
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
+
+
+def eager_attention_forward(
+ module: nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: torch.Tensor | None,
+ scaling: float,
+ dropout: float = 0.0,
+ **kwargs: Unpack[TransformersKwargs],
+):
+ key_states = repeat_kv(key, module.num_key_value_groups)
+ value_states = repeat_kv(value, module.num_key_value_groups)
+
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
+ if attention_mask is not None:
+ attn_weights = attn_weights + attention_mask
+
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
+ attn_output = torch.matmul(attn_weights, value_states)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+
+ return attn_output, attn_weights
+
+
+def rotate_half(x):
+ """Rotates half the hidden dims of the input."""
+ x1 = x[..., 0::2]
+ x2 = x[..., 1::2]
+ return torch.stack((-x2, x1), dim=-1).flatten(-2)
+
+
+def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
+ """Applies Rotary Position Embedding to the query and key tensors.
+
+ Args:
+ q (`torch.Tensor`): The query tensor.
+ k (`torch.Tensor`): The key tensor.
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
+ Returns:
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
+ """
+ cos = cos.unsqueeze(unsqueeze_dim)
+ sin = sin.unsqueeze(unsqueeze_dim)
+
+ # Interleave them instead of usual shape
+ cos = cos[..., : cos.shape[-1] // 2].repeat_interleave(2, dim=-1)
+ sin = sin[..., : sin.shape[-1] // 2].repeat_interleave(2, dim=-1)
+
+ # Keep half or full tensor for later concatenation
+ rotary_dim = cos.shape[-1]
+ q_rot, q_pass = q[..., :rotary_dim], q[..., rotary_dim:]
+ k_rot, k_pass = k[..., :rotary_dim], k[..., rotary_dim:]
+
+ # Apply rotary embeddings on the first half or full tensor
+ q_embed = (q_rot * cos) + (rotate_half(q_rot) * sin)
+ k_embed = (k_rot * cos) + (rotate_half(k_rot) * sin)
+
+ # Concatenate back to full shape
+ q_embed = torch.cat([q_embed, q_pass], dim=-1)
+ k_embed = torch.cat([k_embed, k_pass], dim=-1)
+ return q_embed, k_embed
+
+
+@use_kernelized_func(apply_rotary_pos_emb)
+class MoonshineAttention(nn.Module):
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
+
+ def __init__(
+ self,
+ config: MoonshineConfig,
+ layer_idx: int,
+ is_causal: bool,
+ num_attention_heads: int,
+ num_key_value_heads: int,
+ ):
+ super().__init__()
+ config.update({"num_attention_heads": num_attention_heads, "num_key_value_heads": num_key_value_heads})
+ self.config = config
+ self.layer_idx = layer_idx
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
+ self.scaling = self.head_dim**-0.5
+ self.attention_dropout = config.attention_dropout
+ self.is_causal = is_causal
+
+ self.q_proj = nn.Linear(
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
+ )
+ self.k_proj = nn.Linear(
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
+ )
+ self.v_proj = nn.Linear(
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
+ )
+ self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
+
+ # Pad head dimension to the next specified multiple.
+ if self.config.pad_head_dim_to_multiple_of is not None:
+ target_multiple = self.config.pad_head_dim_to_multiple_of
+ target_head_dim = target_multiple * ((self.head_dim + target_multiple - 1) // target_multiple)
+ self.head_dim_padding = target_head_dim - self.head_dim
+ else:
+ self.head_dim_padding = 0
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
+ attention_mask: torch.Tensor | None = None,
+ past_key_values: Cache | None = None,
+ key_value_states: torch.Tensor | None = None,
+ **kwargs: Unpack[FlashAttentionKwargs],
+ ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
+ bsz, q_len = hidden_states.shape[:-1]
+
+ query_states = (
+ self.q_proj(hidden_states).view(bsz, q_len, self.config.num_key_value_heads, self.head_dim).transpose(1, 2)
+ )
+
+ is_cross_attention = key_value_states is not None
+ if past_key_values is not None:
+ is_updated = past_key_values.is_updated.get(self.layer_idx)
+ if is_cross_attention:
+ # after the first generated id, we can subsequently re-use all key/value_states from cache
+ past_key_values.is_updated[self.layer_idx] = True
+ past_key_values = past_key_values.cross_attention_cache
+ else:
+ past_key_values = past_key_values.self_attention_cache
+
+ # use key_value_states if cross attention
+ current_states = key_value_states if key_value_states is not None else hidden_states
+ if is_cross_attention and past_key_values and is_updated:
+ key_states = past_key_values.layers[self.layer_idx].keys
+ value_states = past_key_values.layers[self.layer_idx].values
+ else:
+ key_states = (
+ self.k_proj(current_states)
+ .view(bsz, -1, self.config.num_key_value_heads, self.head_dim)
+ .transpose(1, 2)
+ )
+ value_states = (
+ self.v_proj(current_states)
+ .view(bsz, -1, self.config.num_key_value_heads, self.head_dim)
+ .transpose(1, 2)
+ )
+ if is_cross_attention and past_key_values is not None:
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
+
+ if not is_cross_attention:
+ cos, sin = position_embeddings
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
+
+ if past_key_values is not None:
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ is_causal = self.is_causal and attention_mask is None and q_len > 1
+
+ if self.head_dim_padding > 0:
+ query_states = torch.nn.functional.pad(query_states, (0, self.head_dim_padding))
+ key_states = torch.nn.functional.pad(key_states, (0, self.head_dim_padding))
+ value_states = torch.nn.functional.pad(value_states, (0, self.head_dim_padding))
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_states,
+ key_states,
+ value_states,
+ attention_mask,
+ dropout=0.0 if not self.training else self.attention_dropout,
+ scaling=self.scaling,
+ is_causal=is_causal,
+ **kwargs,
+ )
+
+ if self.head_dim_padding > 0:
+ attn_output = attn_output[..., : -self.head_dim_padding]
+
+ attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()
+ attn_output = self.o_proj(attn_output)
+ return attn_output, attn_weights
+
+
+class MoonshineEncoderLayer(GradientCheckpointingLayer):
+ def __init__(self, config: MoonshineConfig, layer_idx: int):
+ super().__init__()
+ self.hidden_size = config.hidden_size
+
+ self.self_attn = MoonshineAttention(
+ config=config,
+ layer_idx=layer_idx,
+ is_causal=False,
+ num_attention_heads=config.encoder_num_attention_heads,
+ num_key_value_heads=config.encoder_num_key_value_heads,
+ )
+
+ self.mlp = MoonshineEncoderMLP(config, config.encoder_hidden_act)
+ self.input_layernorm = nn.LayerNorm(config.hidden_size, bias=False)
+ self.post_attention_layernorm = nn.LayerNorm(config.hidden_size, bias=False)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ use_cache: bool | None = False,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.Tensor:
+ residual = hidden_states
+ hidden_states = self.input_layernorm(hidden_states)
+ # Self Attention
+ hidden_states, _ = self.self_attn(
+ hidden_states=hidden_states,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ position_embeddings=position_embeddings,
+ **kwargs,
+ )
+ hidden_states = residual + hidden_states
+
+ # Fully Connected
+ residual = hidden_states
+ hidden_states = self.post_attention_layernorm(hidden_states)
+ hidden_states = self.mlp(hidden_states)
+ hidden_states = residual + hidden_states
+ return hidden_states
+
+
+class MoonshineDecoderLayer(GradientCheckpointingLayer):
+ def __init__(self, config: MoonshineConfig, layer_idx: int | None = None):
+ super().__init__()
+ self.hidden_size = config.hidden_size
+
+ self.self_attn = MoonshineAttention(
+ config=config,
+ layer_idx=layer_idx,
+ is_causal=True,
+ num_attention_heads=config.num_attention_heads,
+ num_key_value_heads=config.num_key_value_heads,
+ )
+ self.encoder_attn = MoonshineAttention(
+ config=config,
+ layer_idx=layer_idx,
+ is_causal=False,
+ num_attention_heads=config.num_attention_heads,
+ num_key_value_heads=config.num_key_value_heads,
+ )
+
+ self.mlp = MoonshineDecoderMLP(config, config.hidden_act)
+ self.input_layernorm = nn.LayerNorm(config.hidden_size, bias=False)
+ self.post_attention_layernorm = nn.LayerNorm(config.hidden_size, bias=False)
+ self.final_layernorm = nn.LayerNorm(config.hidden_size, bias=False)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor | None = None,
+ encoder_hidden_states: torch.Tensor | None = None,
+ encoder_attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ encoder_position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ use_cache: bool | None = False,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
+ encoder_position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.FloatTensor, tuple[torch.FloatTensor, torch.FloatTensor] | None]:
+ residual = hidden_states
+ hidden_states = self.input_layernorm(hidden_states)
+
+ hidden_states, _ = self.self_attn(
+ hidden_states=hidden_states,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ position_embeddings=position_embeddings,
+ **kwargs,
+ )
+ hidden_states = residual + hidden_states
+
+ if encoder_hidden_states is not None:
+ residual = hidden_states
+ hidden_states = self.post_attention_layernorm(hidden_states)
+ hidden_states, _ = self.encoder_attn(
+ hidden_states=hidden_states,
+ key_value_states=encoder_hidden_states,
+ attention_mask=encoder_attention_mask,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ )
+ hidden_states = residual + hidden_states
+
+ residual = hidden_states
+ hidden_states = self.final_layernorm(hidden_states)
+ hidden_states = self.mlp(hidden_states)
+ hidden_states = residual + hidden_states
+ return hidden_states
+
+
+@auto_docstring
+class MoonshinePreTrainedModel(PreTrainedModel):
+ config: MoonshineConfig
+ base_model_prefix = "model"
+ main_input_name = "input_values"
+ input_modalities = "audio"
+ supports_gradient_checkpointing = True
+ _no_split_modules = ["MoonshineEncoderLayer", "MoonshineDecoderLayer"]
+ _supports_flash_attn = True
+ _supports_sdpa = True
+
+ _can_compile_fullgraph = True
+ # TODO arthur, how do we separate when it cross / self coming from different layer?
+
+ def _get_feat_extract_output_lengths(self, input_lengths: torch.LongTensor):
+ """
+ Computes the output length of the convolutional layers
+ """
+ output_conv1_length = int((input_lengths - 127) / 64 + 1)
+ output_conv2_length = int((output_conv1_length - 7) / 3 + 1)
+ output_conv3_length = int((output_conv2_length - 3) / 2 + 1)
+
+ return output_conv3_length
+
+
+class MoonshineEncoder(MoonshinePreTrainedModel):
+ """
+ Transformer encoder consisting of *config.num_hidden_layers* layers. Each layer is a [`MoonshineEncoderLayer`]
+
+ Args:
+ config: MoonshineConfig
+ """
+
+ main_input_name = "input_values"
+ _can_record_outputs = {
+ "attentions": MoonshineAttention,
+ "hidden_states": MoonshineEncoderLayer,
+ }
+
+ def __init__(self, config: MoonshineConfig):
+ super().__init__(config)
+ self.config = config
+ embed_dim = config.hidden_size
+
+ self.conv1 = nn.Conv1d(1, embed_dim, kernel_size=127, stride=64, bias=False)
+ self.conv2 = nn.Conv1d(embed_dim, 2 * embed_dim, kernel_size=7, stride=3)
+ self.conv3 = nn.Conv1d(2 * embed_dim, embed_dim, kernel_size=3, stride=2)
+ self.groupnorm = nn.GroupNorm(num_groups=1, num_channels=embed_dim, eps=1e-5)
+
+ self.layers = nn.ModuleList(
+ [MoonshineEncoderLayer(config, idx) for idx in range(config.encoder_num_hidden_layers)]
+ )
+ self.layer_norm = nn.LayerNorm(embed_dim, bias=False)
+ self.rotary_emb = MoonshineRotaryEmbedding(config=config)
+ self.gradient_checkpointing = False
+ self.post_init()
+
+ def get_input_embeddings(self) -> nn.Module:
+ return self.conv1
+
+ def set_input_embeddings(self, value: nn.Module):
+ self.conv1 = value
+
+ @merge_with_config_defaults
+ @capture_outputs
+ def forward(
+ self,
+ input_values: torch.FloatTensor,
+ attention_mask: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutputWithPast:
+ r"""
+ Args:
+ input_values (`torch.FloatTensor` of shape `(batch_size, audio_length)`):
+ Float values of the raw speech waveform. Raw speech waveform can be
+ obtained by loading a `.flac` or `.wav` audio file into an array of type `list[float]`, a
+ `numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library (`pip install torchcodec`) or
+ the soundfile library (`pip install soundfile`). To prepare the array into
+ `input_values`, the [`AutoFeatureExtractor`] should be used for padding
+ and conversion into a tensor of type `torch.FloatTensor`.
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Mask to avoid performing attention on padding indices in `input_values`. Mask values selected in `[0, 1]`:
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+ [What are attention masks?](../glossary#attention-mask)
+ """
+ input_values = input_values.unsqueeze(1)
+ hidden_states = nn.functional.tanh(self.conv1(input_values))
+ hidden_states = self.groupnorm(hidden_states)
+ hidden_states = nn.functional.gelu(self.conv2(hidden_states))
+ hidden_states = nn.functional.gelu(self.conv3(hidden_states))
+ hidden_states = hidden_states.permute(0, 2, 1)
+
+ # attention mask downsampling
+ output_attention_mask = None
+ if attention_mask is not None:
+ mask_len = self._get_feat_extract_output_lengths(attention_mask.shape[-1])
+ downsample_stride = 64 * 3 * 2 # conv strides
+ attention_mask = attention_mask[..., ::downsample_stride][..., :mask_len]
+ output_attention_mask = attention_mask
+
+ attention_mask = create_bidirectional_mask(
+ config=self.config,
+ inputs_embeds=hidden_states,
+ attention_mask=attention_mask,
+ encoder_hidden_states=hidden_states,
+ )
+
+ position_ids = torch.arange(0, hidden_states.shape[1], device=hidden_states.device).unsqueeze(0)
+ position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
+
+ for encoder_layer in self.layers:
+ hidden_states = encoder_layer(
+ hidden_states,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ position_embeddings=position_embeddings,
+ **kwargs,
+ )
+
+ hidden_states = self.layer_norm(hidden_states)
+
+ return MoonshineEncoderModelOutput(
+ last_hidden_state=hidden_states,
+ attention_mask=output_attention_mask.int() if output_attention_mask is not None else None,
+ )
+
+
+@auto_docstring
+class MoonshineDecoder(MoonshinePreTrainedModel):
+ main_input_name = "input_ids"
+ _can_record_outputs = {
+ "attentions": OutputRecorder(MoonshineAttention, index=1, layer_name="self_attn"),
+ "hidden_states": MoonshineDecoderLayer,
+ "cross_attentions": OutputRecorder(MoonshineAttention, index=1, layer_name="encoder_attn"),
+ }
+
+ def __init__(self, config: MoonshineConfig):
+ super().__init__(config)
+ self.padding_idx = config.pad_token_id
+ self.vocab_size = config.vocab_size
+
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
+ self.layers = nn.ModuleList([MoonshineDecoderLayer(config, idx) for idx in range(config.num_hidden_layers)])
+ self.norm = nn.LayerNorm(config.hidden_size, bias=False)
+ self.rotary_emb = MoonshineRotaryEmbedding(config=config)
+ self.gradient_checkpointing = False
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @merge_with_config_defaults
+ @capture_outputs
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ use_cache: bool | None = None,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ encoder_attention_mask: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutputWithPast:
+ r"""
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
+ of the decoder.
+ encoder_attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Mask to avoid performing attention on padding indices in `encoder_hidden_states`. Mask values selected in `[0, 1]`:
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+ [What are attention masks?](../glossary#attention-mask)
+ """
+ if (input_ids is None) ^ (inputs_embeds is not None):
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
+
+ if inputs_embeds is None:
+ inputs_embeds = self.embed_tokens(input_ids)
+
+ if use_cache and past_key_values is None:
+ past_key_values = EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache(config=self.config))
+
+ if position_ids is None:
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
+ position_ids = position_ids.unsqueeze(0)
+
+ causal_mask = create_causal_mask(
+ config=self.config,
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ position_ids=position_ids,
+ )
+ encoder_attention_mask = create_bidirectional_mask(
+ config=self.config,
+ inputs_embeds=inputs_embeds,
+ attention_mask=encoder_attention_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ )
+
+ hidden_states = inputs_embeds
+ position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
+
+ for decoder_layer in self.layers:
+ hidden_states = decoder_layer(
+ hidden_states,
+ causal_mask,
+ encoder_hidden_states, # as a positional argument for gradient checkpointing
+ encoder_attention_mask=encoder_attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ position_embeddings=position_embeddings,
+ **kwargs,
+ )
+
+ hidden_states = self.norm(hidden_states)
+
+ return BaseModelOutputWithPastAndCrossAttentions(
+ last_hidden_state=hidden_states,
+ past_key_values=past_key_values if use_cache else None,
+ )
+
+
+@auto_docstring
+class MoonshineModel(MoonshinePreTrainedModel):
+ def __init__(self, config: MoonshineConfig):
+ super().__init__(config)
+
+ self.encoder = MoonshineEncoder(config)
+ self.decoder = MoonshineDecoder(config)
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.decoder.embed_tokens
+
+ def set_input_embeddings(self, value):
+ self.decoder.embed_tokens = value
+
+ def freeze_encoder(self):
+ """
+ Calling this function will disable the gradient computation for the Moonshine encoder so that its parameters will
+ not be updated during training.
+ """
+ self.encoder._freeze_parameters()
+
+ def _mask_input_features(self):
+ """
+ Masks extracted features along time axis and/or along feature axis according to
+ [SpecAugment](https://huggingface.co/papers/1904.08779).
+ """
+ raise AttributeError("Not needed for Moonshine")
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_values: torch.FloatTensor | None = None,
+ attention_mask: torch.LongTensor | None = None,
+ decoder_input_ids: torch.LongTensor | None = None,
+ decoder_attention_mask: torch.LongTensor | None = None,
+ encoder_outputs: tuple[tuple[torch.FloatTensor]] | None = None,
+ past_key_values: EncoderDecoderCache | None = None,
+ decoder_inputs_embeds: tuple[torch.FloatTensor] | None = None,
+ decoder_position_ids: tuple[torch.LongTensor] | None = None,
+ use_cache: bool | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> Seq2SeqModelOutput:
+ r"""
+ input_values (`torch.FloatTensor` of shape `(batch_size, audio_length)`):
+ Float values of the raw speech waveform. Raw speech waveform can be
+ obtained by loading a `.flac` or `.wav` audio file into an array of type `list[float]`, a
+ `numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library (`pip install torchcodec`) or
+ the soundfile library (`pip install soundfile`). To prepare the array into
+ `input_values`, the [`AutoFeatureExtractor`] should be used for padding
+ and conversion into a tensor of type `torch.FloatTensor`.
+ decoder_position_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`):
+ Indices of positions of each input sequence tokens in the position embeddings.
+ Used to calculate the position embeddings up to `config.decoder_config.max_position_embeddings`
+
+ Example:
+
+ ```python
+ >>> import torch
+ >>> from transformers import AutoFeatureExtractor, MoonshineModel
+ >>> from datasets import load_dataset
+
+ >>> model = MoonshineModel.from_pretrained("UsefulSensors/moonshine-tiny")
+ >>> feature_extractor = AutoFeatureExtractor.from_pretrained("UsefulSensors/moonshine-tiny")
+ >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
+ >>> inputs = feature_extractor(ds[0]["audio"]["array"], return_tensors="pt")
+ >>> input_values = inputs.input_values
+ >>> decoder_input_ids = torch.tensor([[1, 1]]) * model.config.decoder_start_token_id
+ >>> last_hidden_state = model(input_values, decoder_input_ids=decoder_input_ids).last_hidden_state
+ >>> list(last_hidden_state.shape)
+ [1, 2, 288]
+ ```
+ """
+ if encoder_outputs is None:
+ encoder_outputs: BaseModelOutput = self.encoder(input_values, attention_mask=attention_mask, **kwargs)
+
+ decoder_outputs: BaseModelOutputWithPastAndCrossAttentions = self.decoder(
+ input_ids=decoder_input_ids,
+ attention_mask=decoder_attention_mask,
+ encoder_hidden_states=encoder_outputs.last_hidden_state,
+ encoder_attention_mask=encoder_outputs.attention_mask,
+ past_key_values=past_key_values,
+ inputs_embeds=decoder_inputs_embeds,
+ position_ids=decoder_position_ids,
+ use_cache=use_cache,
+ **kwargs,
+ )
+
+ return Seq2SeqModelOutput(
+ last_hidden_state=decoder_outputs.last_hidden_state,
+ past_key_values=decoder_outputs.past_key_values,
+ decoder_hidden_states=decoder_outputs.hidden_states,
+ decoder_attentions=decoder_outputs.attentions,
+ cross_attentions=decoder_outputs.cross_attentions,
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
+ encoder_hidden_states=encoder_outputs.hidden_states,
+ encoder_attentions=encoder_outputs.attentions,
+ )
+
+
+def shift_tokens_right(input_ids: torch.Tensor, pad_token_id: int, decoder_start_token_id: int):
+ """
+ Shift input ids one token to the right.
+ """
+ shifted_input_ids = input_ids.new_zeros(input_ids.shape)
+ shifted_input_ids[:, 1:] = input_ids[:, :-1].clone()
+ shifted_input_ids[:, 0] = decoder_start_token_id
+
+ if pad_token_id is None:
+ raise ValueError("self.model.config.pad_token_id has to be defined.")
+ # replace possible -100 values in labels by `pad_token_id`
+ shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id)
+
+ return shifted_input_ids
+
+
+@auto_docstring(
+ custom_intro="""
+ The Moonshine Model with a language modeling head. Can be used for automatic speech recognition.
+ """
+)
+class MoonshineForConditionalGeneration(MoonshinePreTrainedModel, GenerationMixin):
+ _tied_weights_keys = {"proj_out.weight": "model.decoder.embed_tokens.weight"}
+
+ def __init__(self, config: MoonshineConfig):
+ super().__init__(config)
+ self.model = MoonshineModel(config)
+ self.proj_out = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_output_embeddings(self):
+ return self.proj_out
+
+ def set_output_embeddings(self, new_embeddings):
+ self.proj_out = new_embeddings
+
+ def get_input_embeddings(self) -> nn.Module:
+ return self.model.get_input_embeddings()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_values: torch.FloatTensor | None = None,
+ attention_mask: torch.LongTensor | None = None,
+ decoder_input_ids: torch.LongTensor | None = None,
+ decoder_attention_mask: torch.LongTensor | None = None,
+ encoder_outputs: tuple[tuple[torch.FloatTensor]] | None = None,
+ past_key_values: EncoderDecoderCache | None = None,
+ decoder_inputs_embeds: tuple[torch.FloatTensor] | None = None,
+ decoder_position_ids: tuple[torch.LongTensor] | None = None,
+ use_cache: bool | None = None,
+ labels: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> Seq2SeqLMOutput:
+ r"""
+ input_values (`torch.FloatTensor` of shape `(batch_size, audio_length)`):
+ Float values of the raw speech waveform. Raw speech waveform can be
+ obtained by loading a `.flac` or `.wav` audio file into an array of type `list[float]`, a
+ `numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library (`pip install torchcodec`) or
+ the soundfile library (`pip install soundfile`). To prepare the array into
+ `input_values`, the [`AutoFeatureExtractor`] should be used for padding
+ and conversion into a tensor of type `torch.FloatTensor`.
+ decoder_position_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`):
+ Indices of positions of each input sequence tokens in the position embeddings.
+ Used to calculate the position embeddings up to `config.decoder_config.max_position_embeddings`
+
+ Example:
+
+ ```python
+ >>> import torch
+ >>> from transformers import AutoProcessor, MoonshineForConditionalGeneration
+ >>> from datasets import load_dataset
+
+ >>> processor = AutoProcessor.from_pretrained("UsefulSensors/moonshine-tiny")
+ >>> model = MoonshineForConditionalGeneration.from_pretrained("UsefulSensors/moonshine-tiny")
+
+ >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
+
+ >>> inputs = processor(ds[0]["audio"]["array"], return_tensors="pt")
+ >>> input_values = inputs.input_values
+
+ >>> generated_ids = model.generate(input_values, max_new_tokens=100)
+
+ >>> transcription = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
+ >>> transcription
+ 'Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel.'
+ ```"""
+
+ if labels is not None:
+ if decoder_input_ids is None and decoder_inputs_embeds is None:
+ decoder_input_ids = shift_tokens_right(
+ labels, self.config.pad_token_id, self.config.decoder_start_token_id
+ )
+
+ outputs: Seq2SeqModelOutput = self.model(
+ input_values,
+ attention_mask=attention_mask,
+ decoder_input_ids=decoder_input_ids,
+ encoder_outputs=encoder_outputs,
+ decoder_attention_mask=decoder_attention_mask,
+ past_key_values=past_key_values,
+ decoder_inputs_embeds=decoder_inputs_embeds,
+ decoder_position_ids=decoder_position_ids,
+ use_cache=use_cache,
+ **kwargs,
+ )
+ logits = self.proj_out(outputs.last_hidden_state)
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size)
+
+ return Seq2SeqLMOutput(
+ loss=loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ decoder_hidden_states=outputs.decoder_hidden_states,
+ decoder_attentions=outputs.decoder_attentions,
+ cross_attentions=outputs.cross_attentions,
+ encoder_last_hidden_state=outputs.encoder_last_hidden_state,
+ encoder_hidden_states=outputs.encoder_hidden_states,
+ encoder_attentions=outputs.encoder_attentions,
+ )
+
+
+__all__ = ["MoonshineModel", "MoonshinePreTrainedModel", "MoonshineForConditionalGeneration"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/moonshine/modular_moonshine.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/moonshine/modular_moonshine.py
new file mode 100644
index 0000000000000000000000000000000000000000..2f2a6bcdaa424fdc2d0d11dea253cbe402d7298d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/moonshine/modular_moonshine.py
@@ -0,0 +1,795 @@
+# Copyright 2025 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from collections.abc import Callable
+from dataclasses import dataclass
+
+import torch
+import torch.nn as nn
+from huggingface_hub.dataclasses import strict
+
+from ...activations import ACT2FN
+from ...cache_utils import Cache, DynamicCache, EncoderDecoderCache
+from ...configuration_utils import PreTrainedConfig
+from ...generation import GenerationMixin
+from ...masking_utils import create_bidirectional_mask, create_causal_mask
+from ...modeling_flash_attention_utils import FlashAttentionKwargs
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import (
+ BaseModelOutput,
+ BaseModelOutputWithPast,
+ BaseModelOutputWithPastAndCrossAttentions,
+ Seq2SeqLMOutput,
+ Seq2SeqModelOutput,
+)
+from ...modeling_rope_utils import RopeParameters
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, logging
+from ...utils.generic import merge_with_config_defaults
+from ...utils.output_capturing import OutputRecorder, capture_outputs
+from ..glm.modeling_glm import GlmAttention, GlmRotaryEmbedding, apply_rotary_pos_emb
+from ..llama.modeling_llama import LlamaDecoderLayer, LlamaModel, eager_attention_forward
+from ..whisper.modeling_whisper import WhisperModel, shift_tokens_right
+
+
+logger = logging.get_logger(__name__)
+
+
+@auto_docstring(checkpoint="UsefulSensors/moonshine-tiny")
+@strict
+class MoonshineConfig(PreTrainedConfig):
+ r"""
+ encoder_num_key_value_heads (`int`, *optional*):
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
+ `encoder_num_key_value_heads=encoder_num_attention_heads`, the model will use Multi Head Attention (MHA), if
+ `encoder_num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
+ by meanpooling all the original heads within that group. For more details, check out [this
+ paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to
+ `num_attention_heads`.
+ decoder_num_key_value_heads (`int`, *optional*):
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
+ `decoder_num_key_value_heads=decoder_num_attention_heads`, the model will use Multi Head Attention (MHA), if
+ `decoder_num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
+ by meanpooling all the original heads within that group. For more details, check out [this
+ paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to
+ `decoder_num_attention_heads`.
+ pad_head_dim_to_multiple_of (`int`, *optional*):
+ Pad head dimension in encoder and decoder to the next multiple of this value. Necessary for using certain
+ optimized attention implementations.
+ encoder_hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
+ The non-linear activation function (function or string) in the encoder.
+ decoder_hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
+ The non-linear activation function (function or string) in the decoder.
+
+ Example:
+
+ ```python
+ >>> from transformers import MoonshineModel, MoonshineConfig
+
+ >>> # Initializing a Moonshine style configuration
+ >>> configuration = MoonshineConfig().from_pretrained("UsefulSensors/moonshine-tiny")
+
+ >>> # Initializing a model from the configuration
+ >>> model = MoonshineModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "moonshine"
+ keys_to_ignore_at_inference = ["past_key_values"]
+ attribute_map = {
+ "num_key_value_heads": "decoder_num_key_value_heads",
+ "num_attention_heads": "decoder_num_attention_heads",
+ "num_hidden_layers": "decoder_num_hidden_layers",
+ "hidden_act": "decoder_hidden_act",
+ }
+
+ vocab_size: int = 32768
+ hidden_size: int = 288
+ intermediate_size: int = 1152
+ encoder_num_hidden_layers: int = 6
+ decoder_num_hidden_layers: int = 6
+ encoder_num_attention_heads: int = 8
+ decoder_num_attention_heads: int = 8
+ encoder_num_key_value_heads: int | None = None
+ decoder_num_key_value_heads: int | None = None
+ pad_head_dim_to_multiple_of: int | None = None
+ encoder_hidden_act: str = "gelu"
+ decoder_hidden_act: str = "silu"
+ max_position_embeddings: int = 512
+ initializer_range: float = 0.02
+ decoder_start_token_id: int = 1
+ use_cache: bool = True
+ rope_parameters: RopeParameters | dict | None = None
+ is_encoder_decoder: bool = True
+ attention_bias: bool = False
+ attention_dropout: float | int = 0.0
+ bos_token_id: int | None = 1
+ eos_token_id: int | list[int] | None = 2
+ pad_token_id: int | None = None
+ tie_word_embeddings: bool = True
+
+ def __post_init__(self, **kwargs):
+ if self.encoder_num_key_value_heads is None:
+ self.encoder_num_key_value_heads = self.encoder_num_attention_heads
+
+ if self.decoder_num_key_value_heads is None:
+ self.decoder_num_key_value_heads = self.decoder_num_attention_heads
+
+ kwargs.setdefault("partial_rotary_factor", 0.9) # assign default for BC
+ super().__post_init__(**kwargs)
+
+
+@auto_docstring(
+ custom_intro="""
+ Extends [~modeling_outputs.BaseModelOutput] to include the output attention mask since sequence length is not preserved in the model's forward.
+ """
+)
+@dataclass
+class MoonshineEncoderModelOutput(BaseModelOutput):
+ r"""
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Mask to avoid performing attention on padding token indices after sequence compression. Returned because the
+ sequence length may differ from the input sequence length. Mask values selected in `[0, 1]`:
+
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+ """
+
+ attention_mask: torch.Tensor | None = None
+
+
+class MoonshineEncoderMLP(nn.Module):
+ def __init__(self, config, hidden_act):
+ super().__init__()
+ self.config = config
+ self.activation_fn = ACT2FN[hidden_act]
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.fc1(hidden_states)
+ hidden_states = self.activation_fn(hidden_states)
+ hidden_states = self.fc2(hidden_states)
+ return hidden_states
+
+
+class MoonshineDecoderMLP(nn.Module):
+ def __init__(self, config, hidden_act):
+ super().__init__()
+ self.config = config
+ self.activation_fn = ACT2FN[hidden_act]
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size * 2)
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.fc1(hidden_states)
+ hidden_states, gate = hidden_states.chunk(2, dim=-1)
+ hidden_states = self.activation_fn(gate) * hidden_states
+ hidden_states = self.fc2(hidden_states)
+ return hidden_states
+
+
+class MoonshineRotaryEmbedding(GlmRotaryEmbedding):
+ pass
+
+
+class MoonshineAttention(GlmAttention):
+ def __init__(
+ self,
+ config: MoonshineConfig,
+ layer_idx: int,
+ is_causal: bool,
+ num_attention_heads: int,
+ num_key_value_heads: int,
+ ):
+ config.update({"num_attention_heads": num_attention_heads, "num_key_value_heads": num_key_value_heads})
+ super().__init__(config, layer_idx)
+ self.is_causal = is_causal
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
+
+ # Pad head dimension to the next specified multiple.
+ if self.config.pad_head_dim_to_multiple_of is not None:
+ target_multiple = self.config.pad_head_dim_to_multiple_of
+ target_head_dim = target_multiple * ((self.head_dim + target_multiple - 1) // target_multiple)
+ self.head_dim_padding = target_head_dim - self.head_dim
+ else:
+ self.head_dim_padding = 0
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
+ attention_mask: torch.Tensor | None = None,
+ past_key_values: Cache | None = None,
+ key_value_states: torch.Tensor | None = None,
+ **kwargs: Unpack[FlashAttentionKwargs],
+ ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
+ bsz, q_len = hidden_states.shape[:-1]
+
+ query_states = (
+ self.q_proj(hidden_states).view(bsz, q_len, self.config.num_key_value_heads, self.head_dim).transpose(1, 2)
+ )
+
+ is_cross_attention = key_value_states is not None
+ if past_key_values is not None:
+ is_updated = past_key_values.is_updated.get(self.layer_idx)
+ if is_cross_attention:
+ # after the first generated id, we can subsequently re-use all key/value_states from cache
+ past_key_values.is_updated[self.layer_idx] = True
+ past_key_values = past_key_values.cross_attention_cache
+ else:
+ past_key_values = past_key_values.self_attention_cache
+
+ # use key_value_states if cross attention
+ current_states = key_value_states if key_value_states is not None else hidden_states
+ if is_cross_attention and past_key_values and is_updated:
+ key_states = past_key_values.layers[self.layer_idx].keys
+ value_states = past_key_values.layers[self.layer_idx].values
+ else:
+ key_states = (
+ self.k_proj(current_states)
+ .view(bsz, -1, self.config.num_key_value_heads, self.head_dim)
+ .transpose(1, 2)
+ )
+ value_states = (
+ self.v_proj(current_states)
+ .view(bsz, -1, self.config.num_key_value_heads, self.head_dim)
+ .transpose(1, 2)
+ )
+ if is_cross_attention and past_key_values is not None:
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
+
+ if not is_cross_attention:
+ cos, sin = position_embeddings
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
+
+ if past_key_values is not None:
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ is_causal = self.is_causal and attention_mask is None and q_len > 1
+
+ if self.head_dim_padding > 0:
+ query_states = torch.nn.functional.pad(query_states, (0, self.head_dim_padding))
+ key_states = torch.nn.functional.pad(key_states, (0, self.head_dim_padding))
+ value_states = torch.nn.functional.pad(value_states, (0, self.head_dim_padding))
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_states,
+ key_states,
+ value_states,
+ attention_mask,
+ dropout=0.0 if not self.training else self.attention_dropout,
+ scaling=self.scaling,
+ is_causal=is_causal,
+ **kwargs,
+ )
+
+ if self.head_dim_padding > 0:
+ attn_output = attn_output[..., : -self.head_dim_padding]
+
+ attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()
+ attn_output = self.o_proj(attn_output)
+ return attn_output, attn_weights
+
+
+class MoonshineEncoderLayer(LlamaDecoderLayer):
+ def __init__(self, config: MoonshineConfig, layer_idx: int):
+ super().__init__(config, layer_idx)
+
+ self.self_attn = MoonshineAttention(
+ config=config,
+ layer_idx=layer_idx,
+ is_causal=False,
+ num_attention_heads=config.encoder_num_attention_heads,
+ num_key_value_heads=config.encoder_num_key_value_heads,
+ )
+
+ self.mlp = MoonshineEncoderMLP(config, config.encoder_hidden_act)
+ self.input_layernorm = nn.LayerNorm(config.hidden_size, bias=False)
+ self.post_attention_layernorm = nn.LayerNorm(config.hidden_size, bias=False)
+
+
+class MoonshineDecoderLayer(GradientCheckpointingLayer):
+ def __init__(self, config: MoonshineConfig, layer_idx: int | None = None):
+ super().__init__()
+ self.hidden_size = config.hidden_size
+
+ self.self_attn = MoonshineAttention(
+ config=config,
+ layer_idx=layer_idx,
+ is_causal=True,
+ num_attention_heads=config.num_attention_heads,
+ num_key_value_heads=config.num_key_value_heads,
+ )
+ self.encoder_attn = MoonshineAttention(
+ config=config,
+ layer_idx=layer_idx,
+ is_causal=False,
+ num_attention_heads=config.num_attention_heads,
+ num_key_value_heads=config.num_key_value_heads,
+ )
+
+ self.mlp = MoonshineDecoderMLP(config, config.hidden_act)
+ self.input_layernorm = nn.LayerNorm(config.hidden_size, bias=False)
+ self.post_attention_layernorm = nn.LayerNorm(config.hidden_size, bias=False)
+ self.final_layernorm = nn.LayerNorm(config.hidden_size, bias=False)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor | None = None,
+ encoder_hidden_states: torch.Tensor | None = None,
+ encoder_attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ encoder_position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ use_cache: bool | None = False,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
+ encoder_position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.FloatTensor, tuple[torch.FloatTensor, torch.FloatTensor] | None]:
+ residual = hidden_states
+ hidden_states = self.input_layernorm(hidden_states)
+
+ hidden_states, _ = self.self_attn(
+ hidden_states=hidden_states,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ position_embeddings=position_embeddings,
+ **kwargs,
+ )
+ hidden_states = residual + hidden_states
+
+ if encoder_hidden_states is not None:
+ residual = hidden_states
+ hidden_states = self.post_attention_layernorm(hidden_states)
+ hidden_states, _ = self.encoder_attn(
+ hidden_states=hidden_states,
+ key_value_states=encoder_hidden_states,
+ attention_mask=encoder_attention_mask,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ )
+ hidden_states = residual + hidden_states
+
+ residual = hidden_states
+ hidden_states = self.final_layernorm(hidden_states)
+ hidden_states = self.mlp(hidden_states)
+ hidden_states = residual + hidden_states
+ return hidden_states
+
+
+@auto_docstring
+class MoonshinePreTrainedModel(PreTrainedModel):
+ config: MoonshineConfig
+ base_model_prefix = "model"
+ main_input_name = "input_values"
+ input_modalities = "audio"
+ supports_gradient_checkpointing = True
+ _no_split_modules = ["MoonshineEncoderLayer", "MoonshineDecoderLayer"]
+ _supports_flash_attn = True
+ _supports_sdpa = True
+
+ _can_compile_fullgraph = True
+ # TODO arthur, how do we separate when it cross / self coming from different layer?
+
+ def _get_feat_extract_output_lengths(self, input_lengths: torch.LongTensor):
+ """
+ Computes the output length of the convolutional layers
+ """
+ output_conv1_length = int((input_lengths - 127) / 64 + 1)
+ output_conv2_length = int((output_conv1_length - 7) / 3 + 1)
+ output_conv3_length = int((output_conv2_length - 3) / 2 + 1)
+
+ return output_conv3_length
+
+
+class MoonshineEncoder(MoonshinePreTrainedModel):
+ """
+ Transformer encoder consisting of *config.num_hidden_layers* layers. Each layer is a [`MoonshineEncoderLayer`]
+
+ Args:
+ config: MoonshineConfig
+ """
+
+ main_input_name = "input_values"
+ _can_record_outputs = {
+ "attentions": MoonshineAttention,
+ "hidden_states": MoonshineEncoderLayer,
+ }
+
+ def __init__(self, config: MoonshineConfig):
+ super().__init__(config)
+ self.config = config
+ embed_dim = config.hidden_size
+
+ self.conv1 = nn.Conv1d(1, embed_dim, kernel_size=127, stride=64, bias=False)
+ self.conv2 = nn.Conv1d(embed_dim, 2 * embed_dim, kernel_size=7, stride=3)
+ self.conv3 = nn.Conv1d(2 * embed_dim, embed_dim, kernel_size=3, stride=2)
+ self.groupnorm = nn.GroupNorm(num_groups=1, num_channels=embed_dim, eps=1e-5)
+
+ self.layers = nn.ModuleList(
+ [MoonshineEncoderLayer(config, idx) for idx in range(config.encoder_num_hidden_layers)]
+ )
+ self.layer_norm = nn.LayerNorm(embed_dim, bias=False)
+ self.rotary_emb = MoonshineRotaryEmbedding(config=config)
+ self.gradient_checkpointing = False
+ self.post_init()
+
+ def get_input_embeddings(self) -> nn.Module:
+ return self.conv1
+
+ def set_input_embeddings(self, value: nn.Module):
+ self.conv1 = value
+
+ @merge_with_config_defaults
+ @capture_outputs
+ def forward(
+ self,
+ input_values: torch.FloatTensor,
+ attention_mask: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutputWithPast:
+ r"""
+ Args:
+ input_values (`torch.FloatTensor` of shape `(batch_size, audio_length)`):
+ Float values of the raw speech waveform. Raw speech waveform can be
+ obtained by loading a `.flac` or `.wav` audio file into an array of type `list[float]`, a
+ `numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library (`pip install torchcodec`) or
+ the soundfile library (`pip install soundfile`). To prepare the array into
+ `input_values`, the [`AutoFeatureExtractor`] should be used for padding
+ and conversion into a tensor of type `torch.FloatTensor`.
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Mask to avoid performing attention on padding indices in `input_values`. Mask values selected in `[0, 1]`:
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+ [What are attention masks?](../glossary#attention-mask)
+ """
+ input_values = input_values.unsqueeze(1)
+ hidden_states = nn.functional.tanh(self.conv1(input_values))
+ hidden_states = self.groupnorm(hidden_states)
+ hidden_states = nn.functional.gelu(self.conv2(hidden_states))
+ hidden_states = nn.functional.gelu(self.conv3(hidden_states))
+ hidden_states = hidden_states.permute(0, 2, 1)
+
+ # attention mask downsampling
+ output_attention_mask = None
+ if attention_mask is not None:
+ mask_len = self._get_feat_extract_output_lengths(attention_mask.shape[-1])
+ downsample_stride = 64 * 3 * 2 # conv strides
+ attention_mask = attention_mask[..., ::downsample_stride][..., :mask_len]
+ output_attention_mask = attention_mask
+
+ attention_mask = create_bidirectional_mask(
+ config=self.config,
+ inputs_embeds=hidden_states,
+ attention_mask=attention_mask,
+ encoder_hidden_states=hidden_states,
+ )
+
+ position_ids = torch.arange(0, hidden_states.shape[1], device=hidden_states.device).unsqueeze(0)
+ position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
+
+ for encoder_layer in self.layers:
+ hidden_states = encoder_layer(
+ hidden_states,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ position_embeddings=position_embeddings,
+ **kwargs,
+ )
+
+ hidden_states = self.layer_norm(hidden_states)
+
+ return MoonshineEncoderModelOutput(
+ last_hidden_state=hidden_states,
+ attention_mask=output_attention_mask.int() if output_attention_mask is not None else None,
+ )
+
+
+class MoonshineDecoder(LlamaModel):
+ main_input_name = "input_ids"
+ _can_record_outputs = {
+ "attentions": OutputRecorder(MoonshineAttention, index=1, layer_name="self_attn"),
+ "hidden_states": MoonshineDecoderLayer,
+ "cross_attentions": OutputRecorder(MoonshineAttention, index=1, layer_name="encoder_attn"),
+ }
+
+ def __init__(self, config: MoonshineConfig):
+ super().__init__(config)
+ self.norm = nn.LayerNorm(config.hidden_size, bias=False)
+ self.layers = nn.ModuleList([MoonshineDecoderLayer(config, idx) for idx in range(config.num_hidden_layers)])
+
+ @merge_with_config_defaults
+ @capture_outputs
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ use_cache: bool | None = None,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ encoder_attention_mask: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutputWithPast:
+ r"""
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
+ of the decoder.
+ encoder_attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Mask to avoid performing attention on padding indices in `encoder_hidden_states`. Mask values selected in `[0, 1]`:
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+ [What are attention masks?](../glossary#attention-mask)
+ """
+ if (input_ids is None) ^ (inputs_embeds is not None):
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
+
+ if inputs_embeds is None:
+ inputs_embeds = self.embed_tokens(input_ids)
+
+ if use_cache and past_key_values is None:
+ past_key_values = EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache(config=self.config))
+
+ if position_ids is None:
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
+ position_ids = position_ids.unsqueeze(0)
+
+ causal_mask = create_causal_mask(
+ config=self.config,
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ position_ids=position_ids,
+ )
+ encoder_attention_mask = create_bidirectional_mask(
+ config=self.config,
+ inputs_embeds=inputs_embeds,
+ attention_mask=encoder_attention_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ )
+
+ hidden_states = inputs_embeds
+ position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
+
+ for decoder_layer in self.layers:
+ hidden_states = decoder_layer(
+ hidden_states,
+ causal_mask,
+ encoder_hidden_states, # as a positional argument for gradient checkpointing
+ encoder_attention_mask=encoder_attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ position_embeddings=position_embeddings,
+ **kwargs,
+ )
+
+ hidden_states = self.norm(hidden_states)
+
+ return BaseModelOutputWithPastAndCrossAttentions(
+ last_hidden_state=hidden_states,
+ past_key_values=past_key_values if use_cache else None,
+ )
+
+
+class MoonshineModel(WhisperModel):
+ def _mask_input_features(self):
+ raise AttributeError("Not needed for Moonshine")
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_values: torch.FloatTensor | None = None,
+ attention_mask: torch.LongTensor | None = None,
+ decoder_input_ids: torch.LongTensor | None = None,
+ decoder_attention_mask: torch.LongTensor | None = None,
+ encoder_outputs: tuple[tuple[torch.FloatTensor]] | None = None,
+ past_key_values: EncoderDecoderCache | None = None,
+ decoder_inputs_embeds: tuple[torch.FloatTensor] | None = None,
+ decoder_position_ids: tuple[torch.LongTensor] | None = None,
+ use_cache: bool | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> Seq2SeqModelOutput:
+ r"""
+ input_values (`torch.FloatTensor` of shape `(batch_size, audio_length)`):
+ Float values of the raw speech waveform. Raw speech waveform can be
+ obtained by loading a `.flac` or `.wav` audio file into an array of type `list[float]`, a
+ `numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library (`pip install torchcodec`) or
+ the soundfile library (`pip install soundfile`). To prepare the array into
+ `input_values`, the [`AutoFeatureExtractor`] should be used for padding
+ and conversion into a tensor of type `torch.FloatTensor`.
+ decoder_position_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`):
+ Indices of positions of each input sequence tokens in the position embeddings.
+ Used to calculate the position embeddings up to `config.decoder_config.max_position_embeddings`
+
+ Example:
+
+ ```python
+ >>> import torch
+ >>> from transformers import AutoFeatureExtractor, MoonshineModel
+ >>> from datasets import load_dataset
+
+ >>> model = MoonshineModel.from_pretrained("UsefulSensors/moonshine-tiny")
+ >>> feature_extractor = AutoFeatureExtractor.from_pretrained("UsefulSensors/moonshine-tiny")
+ >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
+ >>> inputs = feature_extractor(ds[0]["audio"]["array"], return_tensors="pt")
+ >>> input_values = inputs.input_values
+ >>> decoder_input_ids = torch.tensor([[1, 1]]) * model.config.decoder_start_token_id
+ >>> last_hidden_state = model(input_values, decoder_input_ids=decoder_input_ids).last_hidden_state
+ >>> list(last_hidden_state.shape)
+ [1, 2, 288]
+ ```
+ """
+ if encoder_outputs is None:
+ encoder_outputs: BaseModelOutput = self.encoder(input_values, attention_mask=attention_mask, **kwargs)
+
+ decoder_outputs: BaseModelOutputWithPastAndCrossAttentions = self.decoder(
+ input_ids=decoder_input_ids,
+ attention_mask=decoder_attention_mask,
+ encoder_hidden_states=encoder_outputs.last_hidden_state,
+ encoder_attention_mask=encoder_outputs.attention_mask,
+ past_key_values=past_key_values,
+ inputs_embeds=decoder_inputs_embeds,
+ position_ids=decoder_position_ids,
+ use_cache=use_cache,
+ **kwargs,
+ )
+
+ return Seq2SeqModelOutput(
+ last_hidden_state=decoder_outputs.last_hidden_state,
+ past_key_values=decoder_outputs.past_key_values,
+ decoder_hidden_states=decoder_outputs.hidden_states,
+ decoder_attentions=decoder_outputs.attentions,
+ cross_attentions=decoder_outputs.cross_attentions,
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
+ encoder_hidden_states=encoder_outputs.hidden_states,
+ encoder_attentions=encoder_outputs.attentions,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ The Moonshine Model with a language modeling head. Can be used for automatic speech recognition.
+ """
+)
+class MoonshineForConditionalGeneration(MoonshinePreTrainedModel, GenerationMixin):
+ _tied_weights_keys = {"proj_out.weight": "model.decoder.embed_tokens.weight"}
+
+ def __init__(self, config: MoonshineConfig):
+ super().__init__(config)
+ self.model = MoonshineModel(config)
+ self.proj_out = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_output_embeddings(self):
+ return self.proj_out
+
+ def set_output_embeddings(self, new_embeddings):
+ self.proj_out = new_embeddings
+
+ def get_input_embeddings(self) -> nn.Module:
+ return self.model.get_input_embeddings()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_values: torch.FloatTensor | None = None,
+ attention_mask: torch.LongTensor | None = None,
+ decoder_input_ids: torch.LongTensor | None = None,
+ decoder_attention_mask: torch.LongTensor | None = None,
+ encoder_outputs: tuple[tuple[torch.FloatTensor]] | None = None,
+ past_key_values: EncoderDecoderCache | None = None,
+ decoder_inputs_embeds: tuple[torch.FloatTensor] | None = None,
+ decoder_position_ids: tuple[torch.LongTensor] | None = None,
+ use_cache: bool | None = None,
+ labels: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> Seq2SeqLMOutput:
+ r"""
+ input_values (`torch.FloatTensor` of shape `(batch_size, audio_length)`):
+ Float values of the raw speech waveform. Raw speech waveform can be
+ obtained by loading a `.flac` or `.wav` audio file into an array of type `list[float]`, a
+ `numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library (`pip install torchcodec`) or
+ the soundfile library (`pip install soundfile`). To prepare the array into
+ `input_values`, the [`AutoFeatureExtractor`] should be used for padding
+ and conversion into a tensor of type `torch.FloatTensor`.
+ decoder_position_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`):
+ Indices of positions of each input sequence tokens in the position embeddings.
+ Used to calculate the position embeddings up to `config.decoder_config.max_position_embeddings`
+
+ Example:
+
+ ```python
+ >>> import torch
+ >>> from transformers import AutoProcessor, MoonshineForConditionalGeneration
+ >>> from datasets import load_dataset
+
+ >>> processor = AutoProcessor.from_pretrained("UsefulSensors/moonshine-tiny")
+ >>> model = MoonshineForConditionalGeneration.from_pretrained("UsefulSensors/moonshine-tiny")
+
+ >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
+
+ >>> inputs = processor(ds[0]["audio"]["array"], return_tensors="pt")
+ >>> input_values = inputs.input_values
+
+ >>> generated_ids = model.generate(input_values, max_new_tokens=100)
+
+ >>> transcription = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
+ >>> transcription
+ 'Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel.'
+ ```"""
+
+ if labels is not None:
+ if decoder_input_ids is None and decoder_inputs_embeds is None:
+ decoder_input_ids = shift_tokens_right(
+ labels, self.config.pad_token_id, self.config.decoder_start_token_id
+ )
+
+ outputs: Seq2SeqModelOutput = self.model(
+ input_values,
+ attention_mask=attention_mask,
+ decoder_input_ids=decoder_input_ids,
+ encoder_outputs=encoder_outputs,
+ decoder_attention_mask=decoder_attention_mask,
+ past_key_values=past_key_values,
+ decoder_inputs_embeds=decoder_inputs_embeds,
+ decoder_position_ids=decoder_position_ids,
+ use_cache=use_cache,
+ **kwargs,
+ )
+ logits = self.proj_out(outputs.last_hidden_state)
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size)
+
+ return Seq2SeqLMOutput(
+ loss=loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ decoder_hidden_states=outputs.decoder_hidden_states,
+ decoder_attentions=outputs.decoder_attentions,
+ cross_attentions=outputs.cross_attentions,
+ encoder_last_hidden_state=outputs.encoder_last_hidden_state,
+ encoder_hidden_states=outputs.encoder_hidden_states,
+ encoder_attentions=outputs.encoder_attentions,
+ )
+
+
+__all__ = [
+ "MoonshineConfig",
+ "MoonshineModel",
+ "MoonshinePreTrainedModel",
+ "MoonshineForConditionalGeneration",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mpnet/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mpnet/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dc31c2e12335c281e951d7e214bf300320e4b418
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mpnet/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mpnet/__pycache__/configuration_mpnet.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mpnet/__pycache__/configuration_mpnet.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..49875489768844e46ed6ec15b280824dd69ac7ed
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mpnet/__pycache__/configuration_mpnet.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mpnet/__pycache__/modeling_mpnet.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mpnet/__pycache__/modeling_mpnet.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ccb9dfe90dcda068fb842fbc51a7ecbd3a9389e7
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mpnet/__pycache__/modeling_mpnet.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mpnet/__pycache__/tokenization_mpnet.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mpnet/__pycache__/tokenization_mpnet.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..de20b83284843d54984417f2db6c6255777e02fd
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/mpnet/__pycache__/tokenization_mpnet.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/musicflamingo/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/musicflamingo/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..8d136b00e0ad85c2bcefcb21cd6ff7c9ffdf4e47
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/musicflamingo/__init__.py
@@ -0,0 +1,30 @@
+# Copyright 2026 NVIDIA CORPORATION and the HuggingFace Inc. team. All rights
+# reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_musicflamingo import *
+ from .modeling_musicflamingo import *
+ from .processing_musicflamingo import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/musicflamingo/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/musicflamingo/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8a9ab433550ad253542da27cb820d31b56005e51
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/musicflamingo/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/musicflamingo/__pycache__/configuration_musicflamingo.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/musicflamingo/__pycache__/configuration_musicflamingo.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ae12d9c41b67a13cdd6358942d7409f2cb5b077c
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/musicflamingo/__pycache__/configuration_musicflamingo.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/musicflamingo/__pycache__/modeling_musicflamingo.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/musicflamingo/__pycache__/modeling_musicflamingo.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..645bd072867ed1fe2edd4d9ffd5e519b961de2ce
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/musicflamingo/__pycache__/modeling_musicflamingo.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/musicflamingo/__pycache__/modular_musicflamingo.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/musicflamingo/__pycache__/modular_musicflamingo.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..57aa74c33074420f960b63b20ecd91b340f657e7
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/musicflamingo/__pycache__/modular_musicflamingo.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/musicflamingo/__pycache__/processing_musicflamingo.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/musicflamingo/__pycache__/processing_musicflamingo.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..28c622224e1d0cdd988f2bcb8350f864925779ed
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/musicflamingo/__pycache__/processing_musicflamingo.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/musicflamingo/configuration_musicflamingo.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/musicflamingo/configuration_musicflamingo.py
new file mode 100644
index 0000000000000000000000000000000000000000..825039a0eb4eddf8b32066328b539f613206cfce
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/musicflamingo/configuration_musicflamingo.py
@@ -0,0 +1,101 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/musicflamingo/modular_musicflamingo.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_musicflamingo.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2026 NVIDIA CORPORATION and the HuggingFace Inc. team. All rights
+# reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring
+from ..auto import CONFIG_MAPPING, AutoConfig
+
+
+@auto_docstring(checkpoint="nvidia/music-flamingo-2601-hf")
+@strict
+class MusicFlamingoConfig(PreTrainedConfig):
+ r"""
+ audio_bos_token_id (`int`, *optional*, defaults to 151670):
+ The beginning-of-audio token index used to mark the start of audio spans.
+ audio_eos_token_id (`int`, *optional*, defaults to 151671):
+ The end-of-audio token index used to mark the end of audio spans.
+ audio_frame_step (`float`, *optional*, defaults to 0.01):
+ Duration in seconds of one input mel frame (trained with hop_length 160 at sampling_rate 16000).
+
+ Example:
+
+ ```python
+ >>> from transformers import MusicFlamingoForConditionalGeneration, MusicFlamingoConfig, AudioFlamingo3EncoderConfig, Qwen2Config
+
+ >>> # Initializing an MusicFlamingoEncoder config
+ >>> audio_config = AudioFlamingo3EncoderConfig()
+
+ >>> # Initializing a Qwen2 config
+ >>> text_config = Qwen2Config()
+
+ >>> # Initializing an MusicFlamingo configuration
+ >>> configuration = MusicFlamingoConfig(audio_config, text_config)
+
+ >>> # Initializing a model from the musicflamingo style configuration
+ >>> model = MusicFlamingoForConditionalGeneration(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "musicflamingo"
+ sub_configs = {"audio_config": AutoConfig, "text_config": AutoConfig}
+ audio_config: dict | PreTrainedConfig | None = None
+ text_config: dict | PreTrainedConfig | None = None
+ audio_token_id: int = 151669
+ projector_hidden_act: str = "gelu"
+ projector_bias: bool = True
+
+ audio_bos_token_id: int = 151670
+ audio_eos_token_id: int = 151671
+ audio_frame_step: float = 0.01
+ rope_parameters: dict | None = None
+
+ def __post_init__(self, **kwargs):
+ if self.rope_parameters is None:
+ self.rope_parameters = {
+ "rope_type": "default",
+ "rope_theta": 1200.0,
+ "partial_rotary_factor": 0.2,
+ }
+ if isinstance(self.audio_config, dict):
+ if self.audio_config["model_type"] in [None, "musicflamingo_encoder"]:
+ self.audio_config["model_type"] = "audioflamingo3_encoder"
+
+ self.audio_config = CONFIG_MAPPING[self.audio_config["model_type"]](**self.audio_config)
+ elif self.audio_config is None:
+ self.audio_config = CONFIG_MAPPING["audioflamingo3_encoder"]()
+
+ if isinstance(self.text_config, dict):
+ self.text_config["model_type"] = self.text_config.get("model_type", "qwen2")
+ self.text_config = CONFIG_MAPPING[self.text_config["model_type"]](**self.text_config)
+ elif self.text_config is None:
+ self.text_config = CONFIG_MAPPING["qwen2"]()
+
+ self.max_position_embeddings = self.rope_parameters["rope_theta"]
+ self.head_dim = self.audio_config.hidden_size
+ super().__post_init__(**kwargs)
+
+
+__all__ = ["MusicFlamingoConfig"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/musicflamingo/modeling_musicflamingo.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/musicflamingo/modeling_musicflamingo.py
new file mode 100644
index 0000000000000000000000000000000000000000..bea73283f8af2f4df3c9a594c955ecd28e519b72
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/musicflamingo/modeling_musicflamingo.py
@@ -0,0 +1,439 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/musicflamingo/modular_musicflamingo.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_musicflamingo.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2026 NVIDIA CORPORATION and the HuggingFace Inc. team. All rights
+# reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from collections.abc import Callable
+from math import pi
+from typing import Optional
+
+from torch import Tensor, broadcast_tensors, nn
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...cache_utils import Cache
+from ...generation import GenerationMixin
+from ...modeling_outputs import BaseModelOutputWithPooling, CausalLMOutputWithPast
+from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS
+from ...modeling_utils import PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, is_torch_available, torch_compilable_check
+from ..auto import AutoModel, AutoModelForCausalLM
+from .configuration_musicflamingo import MusicFlamingoConfig
+
+
+if is_torch_available():
+ import torch
+
+
+class MusicFlamingoRotaryEmbedding(nn.Module):
+ """Rotary time embedding module used by MusicFlamingo checkpoints.
+
+ This is a checkpoint-faithful integration, not a direct implementation of the RoTE formulation described in
+ (Goel et al., 2024): https://arxiv.org/abs/2410.12109. It applies axial rotary embeddings over the window index
+ within each audio sample and the encoder time index within each window, then modulates both axes with absolute
+ timestamps in seconds.
+ """
+
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
+
+ def __init__(self, config: MusicFlamingoConfig, device=None):
+ super().__init__()
+ self.max_seq_len_cached = config.max_position_embeddings
+ self.original_max_seq_len = config.max_position_embeddings
+
+ self.config = config
+
+ self.rope_type = self.config.rope_parameters["rope_type"]
+ rope_init_fn: Callable = self.compute_default_rope_parameters
+ if self.rope_type != "default":
+ rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
+ inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
+
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
+ self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
+ position_angles = self._compute_position_angles(self.inv_freq)
+ self.register_buffer("position_angles", position_angles, persistent=False)
+
+ @staticmethod
+ def compute_default_rope_parameters(
+ config: MusicFlamingoConfig | None = None,
+ device: Optional["torch.device"] = None,
+ seq_len: int | None = None,
+ ) -> tuple["torch.Tensor", float]:
+ """
+ Computes the inverse frequencies according to the original RoPE implementation
+ Args:
+ config ([`~transformers.PreTrainedConfig`]):
+ The model configuration.
+ device (`torch.device`):
+ The device to use for initialization of the inverse frequencies.
+ seq_len (`int`, *optional*):
+ The current sequence length. Unused for this type of RoPE.
+ Returns:
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
+ """
+ base = config.rope_parameters["rope_theta"]
+ partial_rotary_factor = config.rope_parameters.get("partial_rotary_factor", 1.0)
+ head_dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
+ dim = int(head_dim * partial_rotary_factor)
+
+ attention_factor = 1.0 # Unused in this type of RoPE
+
+ # Compute the inverse frequencies
+ inv_freq = 1.0 / (
+ base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
+ )
+ return inv_freq, attention_factor
+
+ @torch.no_grad()
+ def forward(self, timestamps: Tensor, seq_len: int) -> tuple[Tensor, Tensor]:
+ """Compute 2D axial rotary embeddings for window and time dimensions."""
+
+ # Compute frequencies for the window axis, accounting for x4 due to the downsampling in the audio encoder (conv2 and avg pooling)
+ window_starts = timestamps[:, 0].to(device=self.inv_freq.device, dtype=self.inv_freq.dtype)
+ window_duration = self.config.audio_frame_step * 4 * seq_len
+ window_positions = torch.round(window_starts / window_duration) / self.max_seq_len_cached
+ window_freqs = window_positions.unsqueeze(-1) * self.inv_freq
+ window_freqs = torch.repeat_interleave(window_freqs, 2, dim=-1)
+
+ # Broadcasting and apply time-based angle modulation
+ window_freqs = window_freqs[:, None, :]
+ time_freqs = self.position_angles[:seq_len][None, :, :]
+ window_freqs, time_freqs = broadcast_tensors(window_freqs, time_freqs)
+ freqs = torch.cat((window_freqs, time_freqs), dim=-1)
+ angle = (-timestamps * 2 * pi).to(freqs)
+ freqs = freqs * angle.unsqueeze(-1)
+ return freqs.cos(), freqs.sin()
+
+ def _compute_position_angles(self, inv_freq):
+ positions = torch.arange(int(self.max_seq_len_cached), device=inv_freq.device, dtype=inv_freq.dtype)
+ positions = positions / self.max_seq_len_cached * (2 * pi)
+ position_angles = positions.unsqueeze(-1) * inv_freq
+ position_angles = torch.repeat_interleave(position_angles, 2, dim=-1)
+ return position_angles.to(dtype=inv_freq.dtype)
+
+
+@auto_docstring
+class MusicFlamingoPreTrainedModel(PreTrainedModel):
+ config: MusicFlamingoConfig
+ base_model_prefix = "model"
+ input_modalities = ("audio", "text")
+ supports_gradient_checkpointing = True
+ _no_split_modules = None
+ _skip_keys_device_placement = ["past_key_values"]
+ _supports_flash_attn = True
+ _supports_sdpa = True
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ super()._init_weights(module)
+ if isinstance(module, MusicFlamingoRotaryEmbedding):
+ buffer_value = module._compute_position_angles(module.inv_freq)
+ init.copy_(module.position_angles, buffer_value)
+
+
+class MusicFlamingoMultiModalProjector(nn.Module):
+ """
+ Audio adaptor (small MLP) that projects MusicFlamingoEncoder features
+ to the LLM embedding space so they can replace `` tokens.
+ """
+
+ def __init__(self, config: MusicFlamingoConfig):
+ super().__init__()
+ self.linear_1 = nn.Linear(
+ config.audio_config.hidden_size, config.text_config.hidden_size, bias=config.projector_bias
+ )
+ self.act = ACT2FN[config.projector_hidden_act]
+ self.linear_2 = nn.Linear(
+ config.text_config.hidden_size, config.text_config.hidden_size, bias=config.projector_bias
+ )
+
+ def forward(self, audio_features):
+ hidden_states = self.linear_1(audio_features)
+ hidden_states = self.act(hidden_states)
+ hidden_states = self.linear_2(hidden_states)
+ return hidden_states
+
+
+def rotate_half(x):
+ x = x.reshape(*x.shape[:-1], -1, 2)
+ x1, x2 = x.unbind(dim=-1)
+ x = torch.stack((-x2, x1), dim=-1)
+ return x.flatten(-2)
+
+
+def apply_rotary_time_emb(hidden_states, cos, sin):
+ original_dtype = hidden_states.dtype
+ hidden_states = hidden_states.to(torch.float64)
+ cos = cos.to(hidden_states)
+ sin = sin.to(hidden_states)
+ rot_dim = cos.shape[-1]
+
+ passthrough = hidden_states[..., rot_dim:]
+ rotated = hidden_states[..., :rot_dim]
+ rotated = (rotated * cos) + (rotate_half(rotated) * sin)
+ return torch.cat((rotated, passthrough), dim=-1).to(original_dtype)
+
+
+@auto_docstring(
+ custom_intro="""
+ The MusicFlamingo model which consists of a fine-tuned Whisper encoder, rotary time embedding, a multi-modal projector, and a Qwen2 language model.
+ """
+)
+class MusicFlamingoForConditionalGeneration(MusicFlamingoPreTrainedModel, GenerationMixin):
+ _keep_in_fp32_modules_strict = None
+ _supports_attention_backend = True
+ _tp_plan = None
+ _pp_plan = None
+
+ def __init__(self, config: MusicFlamingoConfig):
+ super().__init__(config)
+ self.vocab_size = config.text_config.vocab_size
+ self.audio_tower = AutoModel.from_config(config.audio_config)
+ self.language_model = AutoModelForCausalLM.from_config(config.text_config)
+ self.multi_modal_projector = MusicFlamingoMultiModalProjector(config)
+ self.pos_emb = MusicFlamingoRotaryEmbedding(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_output_embeddings(self):
+ return self.language_model.get_output_embeddings()
+
+ def set_output_embeddings(self, new_embeddings):
+ self.language_model.set_output_embeddings(new_embeddings)
+
+ def set_decoder(self, decoder):
+ self.language_model.set_decoder(decoder)
+
+ def get_decoder(self):
+ return self.language_model.get_decoder()
+
+ @can_return_tuple
+ @auto_docstring(
+ custom_intro="This method is used to get the audio embeddings from input features (a log mel spectrogram), meaning inferring the audio encoder and the multi-modal projector."
+ )
+ def get_audio_features(
+ self,
+ input_features: torch.FloatTensor,
+ input_features_mask: torch.Tensor,
+ input_ids: torch.LongTensor,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutputWithPooling:
+ r"""
+ input_features_mask (`torch.Tensor` of shape `(batch_size, feature_sequence_length)`):
+ Mask to avoid performing attention on padded feature indices.
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ Token ids containing the audio token ID placeholders, for reconstructing rotary time embedding timestamps.
+ """
+ audio_output = self.audio_tower(
+ input_features,
+ input_features_mask=input_features_mask,
+ return_dict=True,
+ **kwargs,
+ )
+ hidden_states = audio_output.last_hidden_state
+ _, post_lengths = self.audio_tower._get_feat_extract_output_lengths(input_features_mask.sum(-1).to(torch.long))
+ audio_timestamps = self._build_audio_timestamps(input_ids, post_lengths, hidden_states.shape[-2])
+ cos, sin = self.pos_emb(audio_timestamps.to(hidden_states.device), seq_len=hidden_states.shape[-2])
+ hidden_states = apply_rotary_time_emb(hidden_states, cos, sin)
+ audio_embeds = self.multi_modal_projector(hidden_states)
+
+ # Mask according to the audio tower output lengths, accounting for both conv downsampling and final avg pooling
+ valid_mask = torch.arange(audio_embeds.shape[1], device=post_lengths.device)[None, :] < post_lengths[:, None]
+ audio_output.pooler_output = audio_embeds[valid_mask.to(audio_embeds.device)]
+
+ return audio_output
+
+ def get_placeholder_mask(
+ self, input_ids: torch.LongTensor, inputs_embeds: torch.FloatTensor, audio_features: torch.FloatTensor
+ ):
+ """
+ Obtains multimodal placeholder mask from `input_ids` or `inputs_embeds`, and checks that the placeholder token count is
+ equal to the length of multimodal features. If the lengths are different, an error is raised.
+ """
+ if input_ids is None:
+ special_audio_mask = inputs_embeds == self.get_input_embeddings()(
+ torch.tensor(self.config.audio_token_id, dtype=torch.long, device=inputs_embeds.device)
+ )
+ special_audio_mask = special_audio_mask.all(-1)
+ else:
+ special_audio_mask = input_ids == self.config.audio_token_id
+
+ n_audio_tokens = special_audio_mask.sum()
+ n_audio_features = audio_features.shape[0]
+ special_audio_mask = special_audio_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
+ torch_compilable_check(
+ inputs_embeds[special_audio_mask].numel() == audio_features.numel(),
+ f"Audio features and audio tokens do not match, tokens: {n_audio_tokens}, features: {n_audio_features}",
+ )
+ return special_audio_mask
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ input_features: torch.FloatTensor | None = None,
+ input_features_mask: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ use_cache: bool | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> CausalLMOutputWithPast:
+ r"""
+ input_features_mask (`torch.Tensor` of shape `(batch_size, feature_sequence_length)`, *optional*):
+ Mask to avoid performing attention on padding feature indices. Mask values selected in `[0, 1]`:
+
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
+
+ Example:
+
+ ```python
+ >>> from transformers import MusicFlamingoForConditionalGeneration, AutoProcessor
+
+ >>> model_id = "nvidia/music-flamingo-2601-hf"
+ >>> processor = AutoProcessor.from_pretrained(model_id)
+ >>> model = MusicFlamingoForConditionalGeneration.from_pretrained(model_id, device_map="auto")
+
+ >>> conversation = [
+ >>> {
+ >>> "role": "user",
+ >>> "content": [
+ >>> {
+ >>> "type": "text",
+ >>> "text": "Describe this track in full detail - tell me the genre, tempo, and key, then dive into the instruments, production style, and overall mood it creates.",
+ >>> },
+ >>> {
+ >>> "type": "audio",
+ >>> "path": "https://huggingface.co/datasets/nvidia/AudioSkills/resolve/main/assets/song_1.mp3",
+ >>> },
+ >>> ],
+ >>> }
+ >>> ]
+
+ >>> inputs = processor.apply_chat_template(
+ >>> conversation,
+ >>> tokenize=True,
+ >>> add_generation_prompt=True,
+ >>> return_dict=True,
+ >>> ).to(model.device, model.dtype)
+
+ >>> outputs = model.generate(**inputs, max_new_tokens=100)
+
+ >>> decoded_outputs = processor.batch_decode(
+ >>> outputs[:, inputs.input_ids.shape[1]:], skip_special_tokens=True
+ >>> )
+ >>> print(decoded_outputs)
+ ["This track is an uplifting Eurodance-style Trance-Pop anthem..."]
+ ```"""
+ if inputs_embeds is None:
+ inputs_embeds = self.get_input_embeddings()(input_ids)
+
+ if input_features is not None and input_ids is not None:
+ audio_embeds = self.get_audio_features(
+ input_features, input_features_mask, input_ids=input_ids, return_dict=True
+ ).pooler_output
+
+ # replace text-audio token placeholders with audio embeddings
+ special_audio_mask = self.get_placeholder_mask(
+ input_ids, inputs_embeds=inputs_embeds, audio_features=audio_embeds
+ )
+ inputs_embeds = inputs_embeds.masked_scatter(special_audio_mask, audio_embeds.to(inputs_embeds.device))
+
+ outputs: CausalLMOutputWithPast = self.language_model(
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ labels=labels,
+ use_cache=use_cache,
+ logits_to_keep=logits_to_keep,
+ **kwargs,
+ )
+ return outputs
+
+ def prepare_inputs_for_generation(self, *args, is_first_iteration: bool = False, **kwargs):
+ input_features = kwargs.pop("input_features", None)
+ input_features_mask = kwargs.pop("input_features_mask", None)
+
+ model_inputs = super().prepare_inputs_for_generation(*args, **kwargs)
+
+ if is_first_iteration or not model_inputs.get("use_cache", False):
+ if input_features is not None:
+ model_inputs["input_features"] = input_features
+ if input_features_mask is not None:
+ model_inputs["input_features_mask"] = input_features_mask
+
+ return model_inputs
+
+ def _build_audio_timestamps(
+ self,
+ input_ids: torch.LongTensor,
+ post_lengths: torch.LongTensor,
+ max_post_length: int,
+ ) -> torch.FloatTensor:
+ audio_token_mask = input_ids == self.config.audio_token_id
+ diff = torch.diff(torch.nn.functional.pad(audio_token_mask.int(), (1, 1), value=0), dim=1)
+ _, starts = torch.where(diff == 1)
+ _, ends = torch.where(diff == -1)
+ sample_lengths = (ends - starts).to(torch.long)
+
+ n_audio_tokens = audio_token_mask.sum()
+ n_audio_features = post_lengths.sum()
+ torch_compilable_check(
+ n_audio_tokens == n_audio_features,
+ f"Audio features and audio tokens do not match, tokens: {n_audio_tokens}, features: {n_audio_features}",
+ )
+
+ # Account for 4x downsampling in audio encoder (conv2 and avg pooling)
+ audio_embed_frame_step = self.config.audio_frame_step * 4
+ frame_offsets = (
+ torch.arange(max_post_length, device=post_lengths.device, dtype=torch.float32) * audio_embed_frame_step
+ )
+
+ # Map each encoder output row to its audio sample using token counts
+ cumsum_post = torch.cat([torch.zeros(1, device=post_lengths.device), torch.cumsum(post_lengths, dim=0)[:-1]])
+ cumsum_samples = torch.cumsum(sample_lengths, dim=0)
+ sample_indices = torch.searchsorted(cumsum_samples, cumsum_post, right=True)
+
+ # Compute window index within each sample (0, 1, 2, ... then reset for next sample)
+ sample_start_rows = torch.searchsorted(
+ sample_indices, torch.arange(sample_lengths.shape[0], device=post_lengths.device)
+ )
+ window_indices = (
+ torch.arange(post_lengths.shape[0], device=post_lengths.device) - sample_start_rows[sample_indices]
+ )
+
+ # Compute timestamps
+ return window_indices.unsqueeze(1) * max_post_length * audio_embed_frame_step + frame_offsets
+
+
+__all__ = ["MusicFlamingoForConditionalGeneration", "MusicFlamingoPreTrainedModel"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/musicflamingo/modular_musicflamingo.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/musicflamingo/modular_musicflamingo.py
new file mode 100644
index 0000000000000000000000000000000000000000..6c2286046c455ef6f055350d3acf92d713acd330
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/musicflamingo/modular_musicflamingo.py
@@ -0,0 +1,445 @@
+# Copyright 2026 NVIDIA CORPORATION and the HuggingFace Inc. team. All rights
+# reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import re
+from math import pi
+
+from huggingface_hub.dataclasses import strict
+from torch import Tensor, broadcast_tensors
+
+from ... import initialization as init
+from ...cache_utils import Cache
+from ...configuration_utils import PreTrainedConfig
+from ...modeling_outputs import BaseModelOutputWithPooling, CausalLMOutputWithPast
+from ...modeling_utils import PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, is_torch_available, torch_compilable_check
+from ..audioflamingo3.configuration_audioflamingo3 import AudioFlamingo3Config
+from ..audioflamingo3.modeling_audioflamingo3 import (
+ AudioFlamingo3ForConditionalGeneration,
+ AudioFlamingo3PreTrainedModel,
+)
+from ..audioflamingo3.processing_audioflamingo3 import AudioFlamingo3Processor
+from ..auto import CONFIG_MAPPING
+from ..moonshine.modeling_moonshine import MoonshineRotaryEmbedding
+
+
+if is_torch_available():
+ import torch
+
+
+@auto_docstring(checkpoint="nvidia/music-flamingo-2601-hf")
+@strict
+class MusicFlamingoConfig(AudioFlamingo3Config):
+ r"""
+ audio_bos_token_id (`int`, *optional*, defaults to 151670):
+ The beginning-of-audio token index used to mark the start of audio spans.
+ audio_eos_token_id (`int`, *optional*, defaults to 151671):
+ The end-of-audio token index used to mark the end of audio spans.
+ audio_frame_step (`float`, *optional*, defaults to 0.01):
+ Duration in seconds of one input mel frame (trained with hop_length 160 at sampling_rate 16000).
+
+ Example:
+
+ ```python
+ >>> from transformers import MusicFlamingoForConditionalGeneration, MusicFlamingoConfig, AudioFlamingo3EncoderConfig, Qwen2Config
+
+ >>> # Initializing an MusicFlamingoEncoder config
+ >>> audio_config = AudioFlamingo3EncoderConfig()
+
+ >>> # Initializing a Qwen2 config
+ >>> text_config = Qwen2Config()
+
+ >>> # Initializing an MusicFlamingo configuration
+ >>> configuration = MusicFlamingoConfig(audio_config, text_config)
+
+ >>> # Initializing a model from the musicflamingo style configuration
+ >>> model = MusicFlamingoForConditionalGeneration(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ audio_bos_token_id: int = 151670
+ audio_eos_token_id: int = 151671
+ audio_frame_step: float = 0.01
+ rope_parameters: dict | None = None
+
+ def __post_init__(self, **kwargs):
+ if self.rope_parameters is None:
+ self.rope_parameters = {
+ "rope_type": "default",
+ "rope_theta": 1200.0,
+ "partial_rotary_factor": 0.2,
+ }
+ if isinstance(self.audio_config, dict):
+ if self.audio_config["model_type"] in [None, "musicflamingo_encoder"]:
+ self.audio_config["model_type"] = "audioflamingo3_encoder"
+
+ self.audio_config = CONFIG_MAPPING[self.audio_config["model_type"]](**self.audio_config)
+ elif self.audio_config is None:
+ self.audio_config = CONFIG_MAPPING["audioflamingo3_encoder"]()
+
+ if isinstance(self.text_config, dict):
+ self.text_config["model_type"] = self.text_config.get("model_type", "qwen2")
+ self.text_config = CONFIG_MAPPING[self.text_config["model_type"]](**self.text_config)
+ elif self.text_config is None:
+ self.text_config = CONFIG_MAPPING["qwen2"]()
+
+ self.max_position_embeddings = self.rope_parameters["rope_theta"]
+ self.head_dim = self.audio_config.hidden_size
+ PreTrainedConfig.__post_init__(self, **kwargs)
+
+
+class MusicFlamingoProcessor(AudioFlamingo3Processor):
+ r"""
+ Constructs an MusicFlamingo processor which wraps an MusicFlamingo feature extractor and an MusicFlamingo
+ tokenizer into a single processor.
+
+ [`MusicFlamingoProcessor`] offers all the functionalities of [`WhisperFeatureExtractor`] and
+ [`Qwen2TokenizerFast`]. See the [`~MusicFlamingoProcessor.__call__`] for more information.
+
+ Args:
+ feature_extractor ([`WhisperFeatureExtractor`]):
+ The feature extractor is a required input.
+ tokenizer ([`Qwen2TokenizerFast`]):
+ The tokenizer is a required input.
+ chat_template (`Optional[str]`, *optional*):
+ The Jinja template to use for formatting the conversation. If not provided, the tokenizer's default chat
+ template will be used.
+ audio_token (`Optional[str]`, *optional*, defaults to `""`):
+ Special token used to represent audio inputs in the chat template.
+ audio_bos_token (`Optional[str]`, *optional*, defaults to `"<|sound_bos|>"`):
+ Special token used to represent the beginning of audio.
+ audio_eos_token (`Optional[str]`, *optional*, defaults to `"<|sound_eos|>"`):
+ Special token used to represent the end of audio.
+ max_audio_len (`int`, *optional*, defaults to 1200):
+ Maximum length of audio sequences in seconds. Audio longer than this will be truncated.
+ """
+
+ def __init__(
+ self,
+ feature_extractor,
+ tokenizer,
+ chat_template=None,
+ audio_token="",
+ audio_bos_token="<|sound_bos|>",
+ audio_eos_token="<|sound_eos|>",
+ max_audio_len=1200,
+ ):
+ super().__init__(
+ feature_extractor,
+ tokenizer,
+ chat_template=chat_template,
+ audio_token=audio_token,
+ max_audio_len=max_audio_len,
+ )
+ del self.default_transcription_prompt
+ self.audio_bos_token = audio_bos_token
+ self.audio_eos_token = audio_eos_token
+ self.audio_bos_token_id = tokenizer.convert_tokens_to_ids(audio_bos_token)
+ self.audio_eos_token_id = tokenizer.convert_tokens_to_ids(audio_eos_token)
+
+ def _expand_audio_tokens(self, text, padding_mask, per_sample_windows):
+ audio_lengths = torch.stack([s.sum() for s in torch.split(padding_mask.sum(-1), per_sample_windows)])
+ audio_tokens_lengths = self._get_audio_token_length(audio_lengths)
+ audio_token_pattern = re.compile(re.escape(self.audio_token))
+ for i, audio_length in enumerate(audio_tokens_lengths):
+ text[i] = audio_token_pattern.sub(
+ self.audio_bos_token + self.audio_token * audio_length + self.audio_eos_token,
+ text[i],
+ )
+ return text
+
+ def _get_audio_tokens_mask(self, input_ids):
+ return (
+ (input_ids == self.audio_token_id)
+ | (input_ids == self.audio_bos_token_id)
+ | (input_ids == self.audio_eos_token_id)
+ )
+
+ def apply_transcription_request(self, *args, **kwargs):
+ raise NotImplementedError("This method is not supported for MusicFlamingo.")
+
+ def decode(self, *args, **kwargs):
+ raise NotImplementedError("MusicFlamingo does not need to overwrite this method.")
+
+ def batch_decode(self, *args, **kwargs):
+ raise NotImplementedError("MusicFlamingo does not need to overwrite this method.")
+
+ def _strip_assistant_prefix_and_quotes(self, *args, **kwargs):
+ raise NotImplementedError("This method is not supported for MusicFlamingo.")
+
+
+def rotate_half(x):
+ x = x.reshape(*x.shape[:-1], -1, 2)
+ x1, x2 = x.unbind(dim=-1)
+ x = torch.stack((-x2, x1), dim=-1)
+ return x.flatten(-2)
+
+
+def apply_rotary_time_emb(hidden_states, cos, sin):
+ original_dtype = hidden_states.dtype
+ hidden_states = hidden_states.to(torch.float64)
+ cos = cos.to(hidden_states)
+ sin = sin.to(hidden_states)
+ rot_dim = cos.shape[-1]
+
+ passthrough = hidden_states[..., rot_dim:]
+ rotated = hidden_states[..., :rot_dim]
+ rotated = (rotated * cos) + (rotate_half(rotated) * sin)
+ return torch.cat((rotated, passthrough), dim=-1).to(original_dtype)
+
+
+class MusicFlamingoRotaryEmbedding(MoonshineRotaryEmbedding):
+ """Rotary time embedding module used by MusicFlamingo checkpoints.
+
+ This is a checkpoint-faithful integration, not a direct implementation of the RoTE formulation described in
+ (Goel et al., 2024): https://arxiv.org/abs/2410.12109. It applies axial rotary embeddings over the window index
+ within each audio sample and the encoder time index within each window, then modulates both axes with absolute
+ timestamps in seconds.
+ """
+
+ def __init__(self, config: MusicFlamingoConfig, device=None):
+ super().__init__(config, device=device)
+ position_angles = self._compute_position_angles(self.inv_freq)
+ self.register_buffer("position_angles", position_angles, persistent=False)
+
+ def _compute_position_angles(self, inv_freq):
+ positions = torch.arange(int(self.max_seq_len_cached), device=inv_freq.device, dtype=inv_freq.dtype)
+ positions = positions / self.max_seq_len_cached * (2 * pi)
+ position_angles = positions.unsqueeze(-1) * inv_freq
+ position_angles = torch.repeat_interleave(position_angles, 2, dim=-1)
+ return position_angles.to(dtype=inv_freq.dtype)
+
+ @torch.no_grad()
+ def forward(self, timestamps: Tensor, seq_len: int) -> tuple[Tensor, Tensor]:
+ """Compute 2D axial rotary embeddings for window and time dimensions."""
+
+ # Compute frequencies for the window axis, accounting for x4 due to the downsampling in the audio encoder (conv2 and avg pooling)
+ window_starts = timestamps[:, 0].to(device=self.inv_freq.device, dtype=self.inv_freq.dtype)
+ window_duration = self.config.audio_frame_step * 4 * seq_len
+ window_positions = torch.round(window_starts / window_duration) / self.max_seq_len_cached
+ window_freqs = window_positions.unsqueeze(-1) * self.inv_freq
+ window_freqs = torch.repeat_interleave(window_freqs, 2, dim=-1)
+
+ # Broadcasting and apply time-based angle modulation
+ window_freqs = window_freqs[:, None, :]
+ time_freqs = self.position_angles[:seq_len][None, :, :]
+ window_freqs, time_freqs = broadcast_tensors(window_freqs, time_freqs)
+ freqs = torch.cat((window_freqs, time_freqs), dim=-1)
+ angle = (-timestamps * 2 * pi).to(freqs)
+ freqs = freqs * angle.unsqueeze(-1)
+ return freqs.cos(), freqs.sin()
+
+
+class MusicFlamingoPreTrainedModel(AudioFlamingo3PreTrainedModel):
+ _no_split_modules = None
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ PreTrainedModel._init_weights(self, module)
+ if isinstance(module, MusicFlamingoRotaryEmbedding):
+ buffer_value = module._compute_position_angles(module.inv_freq)
+ init.copy_(module.position_angles, buffer_value)
+
+
+@auto_docstring(
+ custom_intro="""
+ The MusicFlamingo model which consists of a fine-tuned Whisper encoder, rotary time embedding, a multi-modal projector, and a Qwen2 language model.
+ """
+)
+class MusicFlamingoForConditionalGeneration(AudioFlamingo3ForConditionalGeneration):
+ def __init__(self, config: MusicFlamingoConfig):
+ super().__init__(config)
+ self.pos_emb = MusicFlamingoRotaryEmbedding(config)
+
+ def _build_audio_timestamps(
+ self,
+ input_ids: torch.LongTensor,
+ post_lengths: torch.LongTensor,
+ max_post_length: int,
+ ) -> torch.FloatTensor:
+ audio_token_mask = input_ids == self.config.audio_token_id
+ diff = torch.diff(torch.nn.functional.pad(audio_token_mask.int(), (1, 1), value=0), dim=1)
+ _, starts = torch.where(diff == 1)
+ _, ends = torch.where(diff == -1)
+ sample_lengths = (ends - starts).to(torch.long)
+
+ n_audio_tokens = audio_token_mask.sum()
+ n_audio_features = post_lengths.sum()
+ torch_compilable_check(
+ n_audio_tokens == n_audio_features,
+ f"Audio features and audio tokens do not match, tokens: {n_audio_tokens}, features: {n_audio_features}",
+ )
+
+ # Account for 4x downsampling in audio encoder (conv2 and avg pooling)
+ audio_embed_frame_step = self.config.audio_frame_step * 4
+ frame_offsets = (
+ torch.arange(max_post_length, device=post_lengths.device, dtype=torch.float32) * audio_embed_frame_step
+ )
+
+ # Map each encoder output row to its audio sample using token counts
+ cumsum_post = torch.cat([torch.zeros(1, device=post_lengths.device), torch.cumsum(post_lengths, dim=0)[:-1]])
+ cumsum_samples = torch.cumsum(sample_lengths, dim=0)
+ sample_indices = torch.searchsorted(cumsum_samples, cumsum_post, right=True)
+
+ # Compute window index within each sample (0, 1, 2, ... then reset for next sample)
+ sample_start_rows = torch.searchsorted(
+ sample_indices, torch.arange(sample_lengths.shape[0], device=post_lengths.device)
+ )
+ window_indices = (
+ torch.arange(post_lengths.shape[0], device=post_lengths.device) - sample_start_rows[sample_indices]
+ )
+
+ # Compute timestamps
+ return window_indices.unsqueeze(1) * max_post_length * audio_embed_frame_step + frame_offsets
+
+ @can_return_tuple
+ @auto_docstring(
+ custom_intro="This method is used to get the audio embeddings from input features (a log mel spectrogram), meaning inferring the audio encoder and the multi-modal projector."
+ )
+ def get_audio_features(
+ self,
+ input_features: torch.FloatTensor,
+ input_features_mask: torch.Tensor,
+ input_ids: torch.LongTensor,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutputWithPooling:
+ r"""
+ input_features_mask (`torch.Tensor` of shape `(batch_size, feature_sequence_length)`):
+ Mask to avoid performing attention on padded feature indices.
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ Token ids containing the audio token ID placeholders, for reconstructing rotary time embedding timestamps.
+ """
+ audio_output = self.audio_tower(
+ input_features,
+ input_features_mask=input_features_mask,
+ return_dict=True,
+ **kwargs,
+ )
+ hidden_states = audio_output.last_hidden_state
+ _, post_lengths = self.audio_tower._get_feat_extract_output_lengths(input_features_mask.sum(-1).to(torch.long))
+ audio_timestamps = self._build_audio_timestamps(input_ids, post_lengths, hidden_states.shape[-2])
+ cos, sin = self.pos_emb(audio_timestamps.to(hidden_states.device), seq_len=hidden_states.shape[-2])
+ hidden_states = apply_rotary_time_emb(hidden_states, cos, sin)
+ audio_embeds = self.multi_modal_projector(hidden_states)
+
+ # Mask according to the audio tower output lengths, accounting for both conv downsampling and final avg pooling
+ valid_mask = torch.arange(audio_embeds.shape[1], device=post_lengths.device)[None, :] < post_lengths[:, None]
+ audio_output.pooler_output = audio_embeds[valid_mask.to(audio_embeds.device)]
+
+ return audio_output
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ input_features: torch.FloatTensor | None = None,
+ input_features_mask: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ use_cache: bool | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> CausalLMOutputWithPast:
+ r"""
+ input_features_mask (`torch.Tensor` of shape `(batch_size, feature_sequence_length)`, *optional*):
+ Mask to avoid performing attention on padding feature indices. Mask values selected in `[0, 1]`:
+
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
+
+ Example:
+
+ ```python
+ >>> from transformers import MusicFlamingoForConditionalGeneration, AutoProcessor
+
+ >>> model_id = "nvidia/music-flamingo-2601-hf"
+ >>> processor = AutoProcessor.from_pretrained(model_id)
+ >>> model = MusicFlamingoForConditionalGeneration.from_pretrained(model_id, device_map="auto")
+
+ >>> conversation = [
+ >>> {
+ >>> "role": "user",
+ >>> "content": [
+ >>> {
+ >>> "type": "text",
+ >>> "text": "Describe this track in full detail - tell me the genre, tempo, and key, then dive into the instruments, production style, and overall mood it creates.",
+ >>> },
+ >>> {
+ >>> "type": "audio",
+ >>> "path": "https://huggingface.co/datasets/nvidia/AudioSkills/resolve/main/assets/song_1.mp3",
+ >>> },
+ >>> ],
+ >>> }
+ >>> ]
+
+ >>> inputs = processor.apply_chat_template(
+ >>> conversation,
+ >>> tokenize=True,
+ >>> add_generation_prompt=True,
+ >>> return_dict=True,
+ >>> ).to(model.device, model.dtype)
+
+ >>> outputs = model.generate(**inputs, max_new_tokens=100)
+
+ >>> decoded_outputs = processor.batch_decode(
+ >>> outputs[:, inputs.input_ids.shape[1]:], skip_special_tokens=True
+ >>> )
+ >>> print(decoded_outputs)
+ ["This track is an uplifting Eurodance-style Trance-Pop anthem..."]
+ ```"""
+ if inputs_embeds is None:
+ inputs_embeds = self.get_input_embeddings()(input_ids)
+
+ if input_features is not None and input_ids is not None:
+ audio_embeds = self.get_audio_features(
+ input_features, input_features_mask, input_ids=input_ids, return_dict=True
+ ).pooler_output
+
+ # replace text-audio token placeholders with audio embeddings
+ special_audio_mask = self.get_placeholder_mask(
+ input_ids, inputs_embeds=inputs_embeds, audio_features=audio_embeds
+ )
+ inputs_embeds = inputs_embeds.masked_scatter(special_audio_mask, audio_embeds.to(inputs_embeds.device))
+
+ outputs: CausalLMOutputWithPast = self.language_model(
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ labels=labels,
+ use_cache=use_cache,
+ logits_to_keep=logits_to_keep,
+ **kwargs,
+ )
+ return outputs
+
+
+__all__ = [
+ "MusicFlamingoConfig",
+ "MusicFlamingoProcessor",
+ "MusicFlamingoForConditionalGeneration",
+ "MusicFlamingoPreTrainedModel",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/musicflamingo/processing_musicflamingo.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/musicflamingo/processing_musicflamingo.py
new file mode 100644
index 0000000000000000000000000000000000000000..8e8fe5e5b438f55c7b8a3694d5dac9dbfce8568b
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/musicflamingo/processing_musicflamingo.py
@@ -0,0 +1,227 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/musicflamingo/modular_musicflamingo.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_musicflamingo.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2026 NVIDIA CORPORATION and the HuggingFace Inc. team. All rights
+# reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import re
+
+import numpy as np
+
+from ...audio_utils import AudioInput, make_list_of_audio
+from ...feature_extraction_utils import BatchFeature
+from ...processing_utils import ProcessingKwargs, ProcessorMixin, Unpack
+from ...tokenization_utils_base import TextInput
+from ...utils import is_torch_available, logging
+
+
+if is_torch_available():
+ import torch
+
+
+logger = logging.get_logger(__name__)
+
+
+class MusicFlamingoProcessorKwargs(ProcessingKwargs, total=False):
+ _defaults = {
+ "text_kwargs": {
+ "padding": True,
+ },
+ "audio_kwargs": {
+ "sampling_rate": 16000,
+ "return_attention_mask": True,
+ "padding": "max_length",
+ },
+ "common_kwargs": {
+ "return_tensors": "pt",
+ "padding_side": "left",
+ },
+ }
+
+
+class MusicFlamingoProcessor(ProcessorMixin):
+ r"""
+ Constructs an MusicFlamingo processor which wraps an MusicFlamingo feature extractor and an MusicFlamingo
+ tokenizer into a single processor.
+
+ [`MusicFlamingoProcessor`] offers all the functionalities of [`WhisperFeatureExtractor`] and
+ [`Qwen2TokenizerFast`]. See the [`~MusicFlamingoProcessor.__call__`] for more information.
+
+ Args:
+ feature_extractor ([`WhisperFeatureExtractor`]):
+ The feature extractor is a required input.
+ tokenizer ([`Qwen2TokenizerFast`]):
+ The tokenizer is a required input.
+ chat_template (`Optional[str]`, *optional*):
+ The Jinja template to use for formatting the conversation. If not provided, the tokenizer's default chat
+ template will be used.
+ audio_token (`Optional[str]`, *optional*, defaults to `""`):
+ Special token used to represent audio inputs in the chat template.
+ audio_bos_token (`Optional[str]`, *optional*, defaults to `"<|sound_bos|>"`):
+ Special token used to represent the beginning of audio.
+ audio_eos_token (`Optional[str]`, *optional*, defaults to `"<|sound_eos|>"`):
+ Special token used to represent the end of audio.
+ max_audio_len (`int`, *optional*, defaults to 1200):
+ Maximum length of audio sequences in seconds. Audio longer than this will be truncated.
+ """
+
+ def __init__(
+ self,
+ feature_extractor,
+ tokenizer,
+ chat_template=None,
+ audio_token="",
+ audio_bos_token="<|sound_bos|>",
+ audio_eos_token="<|sound_eos|>",
+ max_audio_len=1200,
+ ):
+ self.audio_token = audio_token
+ self.audio_token_id = tokenizer.convert_tokens_to_ids(audio_token)
+ self.max_audio_len = max_audio_len
+ super().__init__(feature_extractor, tokenizer, chat_template=chat_template)
+ self.audio_bos_token = audio_bos_token
+ self.audio_eos_token = audio_eos_token
+ self.audio_bos_token_id = tokenizer.convert_tokens_to_ids(audio_bos_token)
+ self.audio_eos_token_id = tokenizer.convert_tokens_to_ids(audio_eos_token)
+
+ def _get_audio_token_length(self, audio_lengths):
+ conv_output_lengths = (audio_lengths - 1) // 2 + 1 # After conv2 downsampling
+ audio_tokens_lengths = (conv_output_lengths - 2) // 2 + 1 # After avg pooling
+ return audio_tokens_lengths
+
+ def _expand_audio_tokens(self, text, padding_mask, per_sample_windows):
+ audio_lengths = torch.stack([s.sum() for s in torch.split(padding_mask.sum(-1), per_sample_windows)])
+ audio_tokens_lengths = self._get_audio_token_length(audio_lengths)
+ audio_token_pattern = re.compile(re.escape(self.audio_token))
+ for i, audio_length in enumerate(audio_tokens_lengths):
+ text[i] = audio_token_pattern.sub(
+ self.audio_bos_token + self.audio_token * audio_length + self.audio_eos_token,
+ text[i],
+ )
+ return text
+
+ def _get_audio_tokens_mask(self, input_ids):
+ return (
+ (input_ids == self.audio_token_id)
+ | (input_ids == self.audio_bos_token_id)
+ | (input_ids == self.audio_eos_token_id)
+ )
+
+ def __call__(
+ self,
+ text: TextInput | list[TextInput],
+ audio: AudioInput | None = None,
+ output_labels: bool | None = False,
+ **kwargs: Unpack[MusicFlamingoProcessorKwargs],
+ ) -> BatchFeature:
+ r"""
+ Main method to prepare one or several text sequence(s) and audio waveform(s) for the model. This
+ method expands `` placeholders in the text based on the post-pool frame counts of the
+ audio windows, then tokenizes the provided strings as-is, and extracts log-mel features
+ with [`WhisperFeatureExtractor`]. If `audio` is `None`, no audio processing is performed and
+ the text is tokenized as-is (LM-only behavior).
+
+ Args:
+ text (`str` or `list[str]`):
+ Input sequence or batch of sequences.
+ audio (`np.ndarray` or `list[np.ndarray]`):
+ Input audio or batch of audios as NumPy arrays. If provided, there must be as many `text` inputs as
+ `audio` inputs.
+ output_labels (bool, *optional*, default=False):
+ Whether to return labels for training.
+
+ Returns:
+ [`BatchFeature`]: A dictionary with tokenized text (`input_ids`, `attention_mask`) and
+ audio features (`input_features`, `input_features_mask`).
+ """
+
+ # Merge defaults with user kwargs
+ call_kwargs = self._merge_kwargs(
+ MusicFlamingoProcessorKwargs,
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
+ **kwargs,
+ )
+
+ text_kwargs = call_kwargs["text_kwargs"]
+ audio_kwargs = call_kwargs["audio_kwargs"]
+ return_tensors = text_kwargs.get("return_tensors")
+ if return_tensors != "pt":
+ raise ValueError(f"{self.__class__.__name__} only supports `return_tensors='pt'`.")
+
+ if isinstance(text, str):
+ text = [text]
+ elif not (isinstance(text, (list, tuple)) and all(isinstance(t, str) for t in text)):
+ raise ValueError("Invalid input text. Please provide a string, or a list of strings")
+
+ audio_inputs = {}
+ if audio is not None:
+ audio = make_list_of_audio(audio)
+ if len(text) != len(audio):
+ raise ValueError(f"Got {len(text)} text but {len(audio)} audios; they must match 1:1.")
+
+ # Determine number of chunks per sample, and flatten
+ window_size = int(audio_kwargs["sampling_rate"] * self.feature_extractor.chunk_length)
+ max_windows = int(self.max_audio_len // self.feature_extractor.chunk_length)
+
+ per_sample_windows: list[int] = []
+ flat_chunks: list[np.ndarray] = []
+
+ for audio_el in audio:
+ n_samples = int(audio_el.shape[0])
+ n_win = max(1, (n_samples + window_size - 1) // window_size)
+ if n_win > max_windows:
+ logger.warning(
+ f"Audio duration ({n_samples / audio_kwargs['sampling_rate']:.1f}s) exceeds {self.max_audio_len}s; truncating to first {self.max_audio_len}s."
+ )
+ n_win = max_windows
+ per_sample_windows.append(n_win)
+
+ time_cap = min(n_samples, n_win * window_size)
+ for i in range(n_win):
+ start = i * window_size
+ end = min((i + 1) * window_size, time_cap)
+ flat_chunks.append(audio_el[start:end])
+
+ # Feature extraction
+ audio_inputs = self.feature_extractor(flat_chunks, **audio_kwargs)
+ padding_mask = audio_inputs.pop("attention_mask")
+ audio_inputs["input_features_mask"] = padding_mask
+
+ # Expand audio tokens in text
+ text = self._expand_audio_tokens(text, padding_mask, per_sample_windows)
+
+ # Tokenize
+ text_inputs = self.tokenizer(text, **text_kwargs)
+
+ data = {**text_inputs, **audio_inputs}
+ if output_labels:
+ labels = data["input_ids"].clone()
+ labels[self._get_audio_tokens_mask(labels)] = -100
+ labels[labels == self.tokenizer.pad_token_id] = -100
+ data["labels"] = labels
+
+ return BatchFeature(data=data, tensor_type=return_tensors)
+
+ @property
+ def model_input_names(self) -> list[str]:
+ tok_names = self.tokenizer.model_input_names
+ fea_names = self.feature_extractor.model_input_names
+ return list(dict.fromkeys(tok_names + fea_names + ["input_features_mask"]))
+
+
+__all__ = ["MusicFlamingoProcessor"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/musicgen_melody/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/musicgen_melody/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2c308969a98c226ceb1923a4870954a097271a96
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/musicgen_melody/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/musicgen_melody/__pycache__/configuration_musicgen_melody.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/musicgen_melody/__pycache__/configuration_musicgen_melody.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..99041e086f07d8c08eb9e6def0f6516d5cd2f454
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/musicgen_melody/__pycache__/configuration_musicgen_melody.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/musicgen_melody/__pycache__/feature_extraction_musicgen_melody.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/musicgen_melody/__pycache__/feature_extraction_musicgen_melody.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..baf874658436633ac28b52ef03e39f7ab9462646
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/musicgen_melody/__pycache__/feature_extraction_musicgen_melody.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/musicgen_melody/__pycache__/modeling_musicgen_melody.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/musicgen_melody/__pycache__/modeling_musicgen_melody.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7e335ba3d4943b048738ab566547bb059f0ecda4
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/musicgen_melody/__pycache__/modeling_musicgen_melody.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/musicgen_melody/__pycache__/processing_musicgen_melody.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/musicgen_melody/__pycache__/processing_musicgen_melody.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8f6c9158283d840f30cefceb5e6dcc34e2101e49
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/musicgen_melody/__pycache__/processing_musicgen_melody.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/nemotron_h/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/nemotron_h/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..bf5b9326beeae718ed8a95cb1a3bac078075f94e
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/nemotron_h/__init__.py
@@ -0,0 +1,27 @@
+# Copyright 2026 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_nemotron_h import *
+ from .modeling_nemotron_h import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/nemotron_h/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/nemotron_h/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..54825ec74ea223da3c250bc870d1258d4157de54
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/nemotron_h/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/nemotron_h/__pycache__/configuration_nemotron_h.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/nemotron_h/__pycache__/configuration_nemotron_h.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..61c463a426ba0d69b3a286fb8c156f91c1c9702d
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/nemotron_h/__pycache__/configuration_nemotron_h.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/nemotron_h/__pycache__/modeling_nemotron_h.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/nemotron_h/__pycache__/modeling_nemotron_h.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d733a2d7855bb7c0a6694eab1a1f57e0202e316b
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/nemotron_h/__pycache__/modeling_nemotron_h.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/nemotron_h/__pycache__/modular_nemotron_h.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/nemotron_h/__pycache__/modular_nemotron_h.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..551d040e0450429c74c37772e5f391b2502743e6
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/nemotron_h/__pycache__/modular_nemotron_h.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/nemotron_h/configuration_nemotron_h.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/nemotron_h/configuration_nemotron_h.py
new file mode 100644
index 0000000000000000000000000000000000000000..1c39584c45ac6a208723e765aac74db374257196
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/nemotron_h/configuration_nemotron_h.py
@@ -0,0 +1,271 @@
+# Copyright 2024-2025 NVIDIA Corporation and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""NemotronH model configuration"""
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring, logging
+
+
+logger = logging.get_logger(__name__)
+
+
+@auto_docstring(checkpoint="nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16")
+@strict
+class NemotronHConfig(PreTrainedConfig):
+ r"""
+ layers_block_type (`list`, *optional*):
+ Explicit list of layer types for each layer. Each element must be one of: "mlp", "mamba", "attention", or "moe".
+ The number of layers is determined by the length of this list.
+ num_logits_to_keep (`int`, *optional*, defaults to 1):
+ Number of prompt logits to calculate during generation. If `None`, all logits will be calculated.
+ use_mamba_kernels (`bool`, *optional*, defaults to `True`):
+ Flag indicating whether or not to use the fast mamba kernels.
+ ssm_state_size (`int`, *optional*, defaults to 128):
+ The dimension of the mamba state space latents.
+ mamba_hidden_act (`str`, *optional*, defaults to `"silu"`):
+ The non-linear activation function in the Mamba layers.
+ n_groups (`int`, *optional*, defaults to 8):
+ Number of groups for the evolution matrices of the Mamba layers.
+ expand (`int`, *optional*, defaults to 2):
+ Expanding factor used to determine the intermediate size in the Mamba layers.
+ use_conv_bias (`bool`, *optional*, defaults to `True`):
+ Whether or not to use bias in the convolution layer of the Mamba mixer block.
+ chunk_size (`int`, *optional*, defaults to 128):
+ Size of the chunks that will comprise the sequence in the Mamba layers.
+ mamba_ssm_cache_dtype (`str`, *optional*, defaults to `"float32"`):
+ Data type for Mamba SSM cache states.
+ moe_shared_expert_intermediate_size (`int`, *optional*, defaults to 7688):
+ Dimension of the MLP representations in shared experts.
+ moe_latent_size (`int`, *optional*):
+ Latent size for MoE expert projections. If `None`, uses `hidden_size`.
+ moe_shared_expert_overlap (`bool`, *optional*, defaults to `True`):
+ Whether shared experts overlap with routed experts.
+ n_group (`int`, *optional*, defaults to 1):
+ Number of groups for expert routing.
+ num_nextn_predict_layers (`int`, *optional*, defaults to 0):
+ Number of additional layers for multi-token prediction. If 0, multi-token prediction is disabled.
+ mtp_layers_block_type (`list`, *optional*, defaults to `['attention', 'moe']`):
+ Explicit list of layer types for multi-token prediction layers when `num_nextn_predict_layers` > 0.
+ use_bias (`bool`, *optional*, defaults to `False`):
+ Whether to use bias in the model.
+ residual_in_fp32 (`bool`, *optional*, defaults to `False`):
+ Whether or not residuals should be in `float32`.
+ rescale_prenorm_residual (`bool`, *optional*, defaults to `True`):
+ Whether to rescale the pre-normalization residual connections.
+
+ ```python
+ >>> from transformers import NemotronHModel, NemotronHConfig
+
+ >>> # Initializing a NemotronH configuration
+ >>> configuration = NemotronHConfig()
+
+ >>> # Initializing a model (with random weights) from the configuration
+ >>> model = NemotronHModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```
+ """
+
+ model_type = "nemotron_h"
+ attribute_map = {"layer_types": "layers_block_type"}
+ keys_to_ignore_at_inference = ["past_key_values"]
+
+ vocab_size: int = 131072
+ hidden_size: int = 4096
+ layers_block_type: list[str] | None = None
+ tie_word_embeddings: bool = False
+ use_cache: bool = True
+ num_logits_to_keep: int = 1
+ pad_token_id: int | None = 0
+ bos_token_id: int | None = 1
+ eos_token_id: int | list[int] | None = 2
+ num_attention_heads: int = 32
+ num_key_value_heads: int = 8
+ head_dim: int = 128
+ max_position_embeddings: int = 4096
+ attention_bias: bool = False
+ attention_dropout: float | int = 0.0
+ sliding_window: int | None = None
+ intermediate_size: int = 21504
+ mlp_hidden_act: str = "relu2"
+ mlp_bias: bool = False
+ use_mamba_kernels: bool = True
+ ssm_state_size: int = 128
+ mamba_num_heads: int = 128
+ mamba_head_dim: int = 64
+ mamba_hidden_act: str = "silu"
+ n_groups: int = 8
+ conv_kernel: int = 4
+ expand: int = 2
+ time_step_min: float = 0.001
+ time_step_max: float = 0.1
+ time_step_limit: list[float] | tuple[float, ...] = (0.0, float("inf"))
+ time_step_floor: float = 1e-4
+ use_conv_bias: bool = True
+ chunk_size: int = 128
+ mamba_proj_bias: bool = False
+ mamba_ssm_cache_dtype: str = "float32"
+ n_routed_experts: int = 8
+ n_shared_experts: int = 1
+ moe_intermediate_size: int = 7688
+ moe_shared_expert_intermediate_size: int = 7688
+ moe_latent_size: int | None = None
+ moe_shared_expert_overlap: bool = True
+ num_experts_per_tok: int = 2
+ routed_scaling_factor: float | int = 1.0
+ n_group: int = 1
+ topk_group: int = 1
+ norm_topk_prob: bool = True
+ num_nextn_predict_layers: int = 0
+ mtp_layers_block_type: list[str] | None = None
+ use_bias: bool = False
+ initializer_range: float = 0.02
+ layer_norm_epsilon: float = 1e-5
+ residual_in_fp32: bool = False
+ hidden_dropout: float | int = 0.0
+ rescale_prenorm_residual: bool = True
+
+ def __post_init__(self, **kwargs):
+ # Backward compatibility; configs expect different names for these fields when init
+ # but they have to be re-names when creating/saving the config.
+ self.n_groups = kwargs.pop("mamba_n_groups") if "mamba_n_groups" in kwargs else self.n_groups
+ self.conv_kernel = kwargs.pop("mamba_d_conv") if "mamba_d_conv" in kwargs else self.conv_kernel
+ self.expand = kwargs.pop("mamba_expand") if "mamba_expand" in kwargs else self.expand
+ self.time_step_min = kwargs.pop("mamba_dt_min") if "mamba_dt_min" in kwargs else self.time_step_min
+ self.time_step_max = kwargs.pop("mamba_dt_max") if "mamba_dt_max" in kwargs else self.time_step_max
+ self.time_step_limit = kwargs.pop("mamba_dt_limit") if "mamba_dt_limit" in kwargs else self.time_step_limit
+ self.time_step_floor = (
+ kwargs.pop("mamba_dt_init_floor") if "mamba_dt_init_floor" in kwargs else self.time_step_floor
+ )
+ self.use_conv_bias = kwargs.pop("mamba_conv_bias") if "mamba_conv_bias" in kwargs else self.use_conv_bias
+ self.chunk_size = kwargs.pop("mamba_chunk_size") if "mamba_chunk_size" in kwargs else self.chunk_size
+
+ # Backward compatibility: convert hybrid_override_pattern to layers_block_type
+ # Always pop hybrid_override_pattern from kwargs to prevent it from being set as an attribute
+ if "hybrid_override_pattern" in kwargs:
+ pattern = kwargs.pop("hybrid_override_pattern")
+ if self.layer_types is None:
+ self.layer_types = self._pattern_to_list(pattern)
+ elif self.layer_types is None:
+ # Default layers_block_type if not provided
+ self.layer_types = ["mamba", "moe", "attention", "mlp"]
+
+ # Note: num_hidden_layers is deprecated and ignored if layers_block_type is explicitly provided
+ # It's only kept for backward compatibility when loading old configs
+ if self.num_hidden_layers is not None:
+ # Warn if num_hidden_layers is provided but doesn't match layers_block_type
+ if len(self.layer_types) != self.num_hidden_layers:
+ logger.warning(
+ f"num_hidden_layers ({self.num_hidden_layers}) is deprecated and doesn't match "
+ f"layer_types length ({len(self.layer_types)}). Using layers_block_type length."
+ )
+
+ # Backward compatibility: convert mtp_hybrid_override_pattern to mtp_layers_block_type
+ # Always pop mtp_hybrid_override_pattern from kwargs to prevent it from being set as an attribute
+ if self.mtp_layers_block_type is None:
+ self.mtp_layers_block_type = ["attention", "moe"]
+
+ if "mtp_hybrid_override_pattern" in kwargs:
+ pattern = kwargs.pop("mtp_hybrid_override_pattern")
+ if self.mtp_layers_block_type == ["attention", "moe"]:
+ self.mtp_layers_block_type = self._pattern_to_list(pattern)
+
+ # for backward compatibility
+ if self.num_key_value_heads is None:
+ self.num_key_value_heads = self.num_attention_heads
+
+ super().__post_init__(**kwargs)
+
+ @staticmethod
+ def validate_layer_type(self):
+ """
+ Validate layers_block_type list.
+ """
+ if not isinstance(self.layer_types, list):
+ raise ValueError(f"`layers_block_type` must be a list of strings. Got type: {type(self.layer_types)}")
+
+ valid_types = {"mamba", "attention", "moe", "mlp"}
+ if not all(block_type in valid_types for block_type in self.layer_types):
+ invalid = set(self.layer_types) - valid_types
+ raise ValueError(f"`layers_block_type` contains invalid types: {invalid}. Must be one of: {valid_types}")
+
+ if self.num_nextn_predict_layers > 0:
+ if self.mtp_layers_block_type is None:
+ raise ValueError(
+ "mtp_layers_block_type is required when num_nextn_predict_layers > 0. "
+ "Please provide an explicit list of layer types for MTP layers. "
+ "Example: mtp_layers_block_type=['attention', 'moe']"
+ )
+
+ if not isinstance(self.mtp_layers_block_type, list):
+ raise ValueError(
+ f"`mtp_layers_block_type` must be a list of strings. Got type: {type(self.mtp_layers_block_type)}"
+ )
+
+ if not all(block_type in valid_types for block_type in self.mtp_layers_block_type):
+ invalid = set(self.mtp_layers_block_type) - valid_types
+ raise ValueError(
+ f"`mtp_layers_block_type` contains invalid types: {invalid}. Must be one of: {valid_types}"
+ )
+
+ @property
+ def num_hidden_layers(self) -> int:
+ """
+ Number of hidden layers derived from the length of layers_block_type.
+ This property replaces the deprecated num_hidden_layers parameter.
+ """
+ return len(self.layers_block_type)
+
+ @num_hidden_layers.setter
+ def num_hidden_layers(self, value):
+ """
+ Setter for backward compatibility when loading configs.
+ The value is ignored since num_hidden_layers is computed from layers_block_type.
+ """
+ # Ignore the value - num_hidden_layers is always derived from layers_block_type
+ pass
+
+ @property
+ def hybrid_override_pattern(self) -> str:
+ """
+ Backward compatibility property.
+ Returns the pattern string representation of layers_block_type.
+ """
+ return self._list_to_pattern(self.layers_block_type)
+
+ @property
+ def mtp_hybrid_override_pattern(self) -> str:
+ """
+ Backward compatibility property.
+ Returns the pattern string representation of mtp_layers_block_type.
+ """
+ return self._list_to_pattern(self.mtp_layers_block_type)
+
+ @staticmethod
+ def _list_to_pattern(layers_list: list) -> str:
+ """Convert list of layer types back to pattern string (for backward compatibility)."""
+ reverse_mapping = {"mamba": "M", "moe": "E", "attention": "*", "mlp": "-"}
+ return "".join(reverse_mapping[layer_type] for layer_type in layers_list)
+
+ @staticmethod
+ def _pattern_to_list(pattern: str) -> list:
+ """Convert pattern string to list of layer types (for backward compatibility)."""
+ pattern_mapping = {"M": "mamba", "E": "moe", "*": "attention", "-": "mlp"}
+ return [pattern_mapping[char] for char in pattern]
+
+
+__all__ = ["NemotronHConfig"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/nemotron_h/modeling_nemotron_h.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/nemotron_h/modeling_nemotron_h.py
new file mode 100644
index 0000000000000000000000000000000000000000..937e2c302c59c4838889b3221d8ab0618b2eb0c1
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/nemotron_h/modeling_nemotron_h.py
@@ -0,0 +1,1231 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/nemotron_h/modular_nemotron_h.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_nemotron_h.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
+# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+import math
+from collections.abc import Callable
+
+import torch
+import torch.nn.functional as F
+from torch import nn
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...cache_utils import Cache, DynamicCache
+from ...generation import GenerationMixin
+from ...integrations import (
+ lazy_load_kernel,
+ use_experts_implementation,
+ use_kernel_forward_from_hub,
+ use_kernel_func_from_hub,
+ use_kernelized_func,
+)
+from ...masking_utils import create_causal_mask
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
+from ...models.zamba2.modeling_zamba2 import Zamba2RMSNormGated
+from ...processing_utils import Unpack
+from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, is_torchdynamo_compiling, logging
+from ...utils.generic import merge_with_config_defaults
+from ...utils.import_utils import resolve_internal_import
+from ...utils.output_capturing import capture_outputs
+from .configuration_nemotron_h import NemotronHConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+# Helper methods for segment sum computation
+
+
+def pad_tensor_by_size(input_tensor: torch.Tensor, pad_size: int):
+ """
+ Padding x tensor with `pad_size` on the seq_len dim (dim=1)
+
+ Assumes that we only have tensors of either size 4 or 3
+ """
+ pad_shape = (0, 0, 0, 0, 0, pad_size, 0, 0) if len(input_tensor.shape) == 4 else (0, 0, 0, pad_size, 0, 0)
+
+ return torch.nn.functional.pad(input_tensor, pad_shape, mode="constant", value=0)
+
+
+def reshape_into_chunks(input_tensor, pad_size, chunk_size):
+ """
+ Padding input_tensor with `pad_size` on the seq_len dim (dim=1) and
+ simultaneously splitting it into chunk sequences.
+
+ Assumes that we only have tensors of either size 4 or 3
+ """
+ # [bsz, seq_len, ...] -> [bsz, seq_len multiple of chunk_size, ...]
+ input_tensor = pad_tensor_by_size(input_tensor, pad_size)
+
+ if len(input_tensor.shape) == 3:
+ # [bsz, seq_len multiple of chunk_size, num_heads] -> [bsz, -1, chunk_size, num_heads]
+ return input_tensor.reshape(input_tensor.shape[0], -1, chunk_size, input_tensor.shape[2])
+ else:
+ # [bsz, seq_len multiple of chunk_size, num_heads, head_dim or state_size] -> [bsz, -1, chunk_size, num_heads, head_dim or state_size]
+ return input_tensor.reshape(
+ input_tensor.shape[0], -1, chunk_size, input_tensor.shape[2], input_tensor.shape[3]
+ )
+
+
+def segment_sum(input_tensor):
+ """
+ More stable segment sum calculation. Uses cumulative sums and masking instead of direct subtractions.
+ """
+ chunk_size = input_tensor.size(-1)
+ # 1. expand input tensor to have an additional dimension and repeat along that dimension
+ # [..., chunk_size] -> [..., chunk_size, chunk_size]
+ input_tensor = input_tensor[..., None].expand(*input_tensor.size(), chunk_size)
+ # 2. create a lower triangular mask with the diagonal set to 0 to 0 out elements above diag
+ mask = torch.tril(torch.ones(chunk_size, chunk_size, device=input_tensor.device, dtype=torch.bool), diagonal=-1)
+ input_tensor = input_tensor.masked_fill(~mask, 0)
+ # 3. compute actual cumsum
+ tensor_segsum = torch.cumsum(input_tensor, dim=-2)
+
+ # 4. apply mask to keep only the lower triangular part of the cumulative sum result (incl diagonal this time)
+ mask = torch.tril(torch.ones(chunk_size, chunk_size, device=input_tensor.device, dtype=torch.bool), diagonal=0)
+ tensor_segsum = tensor_segsum.masked_fill(~mask, -torch.inf)
+ return tensor_segsum
+
+
+is_fast_path_available = False
+
+
+class NemotronHMamba2Mixer(nn.Module):
+ """
+ Compute ∆, A, B, C, and D the state space parameters and compute the `contextualized_states`.
+ A, D are input independent (see Mamba paper [1] Section 3.5.2 "Interpretation of A" for why A isn't selective)
+ ∆, B, C are input-dependent (this is a key difference between Mamba and the linear time invariant S4,
+ and is why Mamba is called **selective** state spaces)
+ """
+
+ def __init__(self, config: NemotronHConfig, layer_idx: int | None = None):
+ super().__init__()
+ self.config = config
+ self.hidden_size = config.hidden_size
+ self.ssm_state_size = config.ssm_state_size
+ self.conv_kernel_size = config.conv_kernel
+ self.intermediate_size = config.mamba_num_heads * config.mamba_head_dim
+ self.layer_idx = layer_idx
+ self.use_conv_bias = config.use_conv_bias
+ self.activation = config.mamba_hidden_act
+ self.act = ACT2FN[config.mamba_hidden_act]
+ self.use_mem_eff_path = True
+
+ self.n_groups = config.n_groups
+ self.head_dim = config.mamba_head_dim
+ self.num_heads = config.mamba_num_heads
+ self.chunk_size = config.chunk_size
+
+ self.time_step_limit = config.time_step_limit
+ self.time_step_min = config.time_step_min
+ self.time_step_max = config.time_step_max
+
+ self.conv_dim = self.intermediate_size + 2 * self.n_groups * self.ssm_state_size
+
+ self.conv1d = nn.Conv1d(
+ in_channels=self.conv_dim,
+ out_channels=self.conv_dim,
+ bias=config.use_conv_bias,
+ kernel_size=self.conv_kernel_size,
+ groups=self.conv_dim,
+ padding=self.conv_kernel_size - 1,
+ )
+
+ # projection of the input hidden states
+ projection_size = self.intermediate_size + self.conv_dim + self.num_heads
+
+ self.in_proj = nn.Linear(
+ self.hidden_size,
+ projection_size,
+ bias=config.use_bias,
+ )
+ # selective projection used to make dt, B and C input dependent
+
+ # time step projection (discretization)
+ # instantiate once and copy inv_dt in init_weights of PretrainedModel
+ self.dt_bias = nn.Parameter(torch.ones(self.num_heads))
+
+ # S4D real initialization. These are not discretized!
+ # The core is to load them, compute the discrete states, then write the updated state. Keeps the memory bounded
+ A = torch.arange(1, self.num_heads + 1)
+ self.A_log = nn.Parameter(torch.log(A))
+
+ self.norm = Zamba2RMSNormGated(
+ self.intermediate_size, group_size=self.intermediate_size // self.n_groups, eps=config.layer_norm_epsilon
+ )
+ self.D = nn.Parameter(torch.ones(self.num_heads))
+
+ self.out_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.use_bias)
+
+ global causal_conv1d_update, causal_conv1d_fn
+ global selective_state_update, mamba_chunk_scan_combined, mamba_split_conv1d_scan_combined
+ global is_fast_path_available
+
+ if config.use_mamba_kernels:
+ causal_conv1d = lazy_load_kernel("causal-conv1d")
+ causal_conv1d_update = getattr(causal_conv1d, "causal_conv1d_update", None)
+ causal_conv1d_fn = getattr(causal_conv1d, "causal_conv1d_fn", None)
+
+ mamba_ssm = lazy_load_kernel("mamba-ssm")
+ selective_state_update = resolve_internal_import(
+ mamba_ssm, chained_path="ops.triton.selective_state_update.selective_state_update"
+ )
+ mamba_chunk_scan_combined = resolve_internal_import(
+ mamba_ssm, chained_path="ops.triton.ssd_combined.mamba_chunk_scan_combined"
+ )
+ mamba_split_conv1d_scan_combined = resolve_internal_import(
+ mamba_ssm, chained_path="ops.triton.ssd_combined.mamba_split_conv1d_scan_combined"
+ )
+
+ is_fast_path_available = all(
+ (
+ selective_state_update,
+ mamba_chunk_scan_combined,
+ mamba_split_conv1d_scan_combined,
+ causal_conv1d_fn,
+ causal_conv1d_update,
+ )
+ )
+ else:
+ causal_conv1d_update = None
+ causal_conv1d_fn = None
+ selective_state_update = None
+ mamba_chunk_scan_combined = None
+ mamba_split_conv1d_scan_combined = None
+ is_fast_path_available = False
+
+ if getattr(config, "use_mamba_kernels", True) and not is_fast_path_available:
+ logger.warning_once(
+ "The fast path is not available because one of `(selective_state_update, causal_conv1d_fn, causal_conv1d_update)`"
+ " is None. Falling back to the naive implementation. To install follow https://github.com/state-spaces/mamba/#installation and"
+ " https://github.com/Dao-AILab/causal-conv1d"
+ )
+
+ def cuda_kernels_forward(
+ self,
+ hidden_states: torch.Tensor,
+ cache_params: Cache | None = None,
+ attention_mask: torch.Tensor | None = None,
+ ):
+ # set up dimensions for reshapes later
+
+ batch_size, seq_len, _ = hidden_states.shape
+ groups_time_state_size = self.n_groups * self.ssm_state_size
+ d_to_remove = 2 * self.intermediate_size + 2 * self.n_groups * self.ssm_state_size + self.num_heads
+
+ # getting projected states from cache if it exists
+ if cache_params is not None and cache_params.has_previous_state(self.layer_idx):
+ in_projected_states = self.in_proj(hidden_states.squeeze(1)) # (B 2D)
+ d_mlp = (in_projected_states.shape[-1] - d_to_remove) // 2
+ split_projection_dim = [d_mlp, d_mlp, self.intermediate_size, self.conv_dim, self.num_heads]
+ _, _, gate, hidden_states_B_C, dt = torch.split(in_projected_states, split_projection_dim, dim=-1)
+
+ hidden_states_B_C = causal_conv1d_update(
+ hidden_states_B_C,
+ cache_params.layers[self.layer_idx].conv_states,
+ self.conv1d.weight.squeeze(1),
+ self.conv1d.bias,
+ self.activation,
+ )
+
+ hidden_states, B, C = torch.split(
+ hidden_states_B_C,
+ [self.intermediate_size, groups_time_state_size, groups_time_state_size],
+ dim=-1,
+ )
+ A = -torch.exp(self.A_log.float()) # (nheads,)
+
+ A = A[:, None, ...][:, :, None].expand(-1, self.head_dim, self.ssm_state_size).to(dtype=torch.float32)
+ dt = dt[:, :, None].expand(-1, -1, self.head_dim)
+ dt_bias = self.dt_bias[:, None, ...].expand(-1, self.head_dim)
+ D = self.D[:, None, ...].expand(-1, self.head_dim)
+ B = B.view(batch_size, self.n_groups, B.shape[1] // self.n_groups)
+ C = C.view(batch_size, self.n_groups, C.shape[1] // self.n_groups)
+ hidden_states_reshaped = hidden_states.view(batch_size, self.num_heads, self.head_dim)
+ hidden_states = selective_state_update(
+ cache_params.layers[self.layer_idx].recurrent_states,
+ hidden_states_reshaped,
+ dt,
+ A,
+ B,
+ C,
+ D,
+ z=None,
+ dt_bias=dt_bias,
+ dt_softplus=True,
+ )
+ hidden_states = hidden_states.view(batch_size, self.num_heads * self.head_dim)
+ hidden_states = self.norm(hidden_states, gate)
+ out = self.out_proj(hidden_states)[:, None, ...]
+ # if no cache is found, calling the kernel
+ else:
+ if attention_mask is not None and not torch.all(attention_mask == 1):
+ # tune out hidden states for pad tokens, see https://github.com/state-spaces/mamba/issues/66
+ dtype = hidden_states.dtype
+ hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype)
+ # 1. Gated MLP's linear projection
+ projected_states = self.in_proj(hidden_states)
+ A = -torch.exp(self.A_log.float()) # (num_heads) or (intermediate_size, state_size)
+ dt_limit_kwargs = {} if self.time_step_limit is None else {"dt_limit": self.time_step_limit}
+ if attention_mask is not None:
+ input_not_masked = torch.all(attention_mask == 1)
+ else:
+ input_not_masked = True
+
+ if self.use_mem_eff_path and self.training and cache_params is None and input_not_masked:
+ out, ssm_state = mamba_split_conv1d_scan_combined(
+ projected_states,
+ self.conv1d.weight.squeeze(1),
+ self.conv1d.bias,
+ self.dt_bias,
+ A,
+ D=self.D,
+ chunk_size=self.chunk_size,
+ seq_idx=None,
+ activation=self.activation,
+ rmsnorm_weight=self.norm.weight,
+ rmsnorm_eps=self.norm.variance_epsilon,
+ outproj_weight=self.out_proj.weight,
+ outproj_bias=self.out_proj.bias,
+ headdim=self.head_dim,
+ ngroups=self.n_groups,
+ norm_before_gate=False,
+ return_final_states=True,
+ **dt_limit_kwargs,
+ )
+
+ else:
+ gate, hidden_states_B_C, time_step = torch.split(
+ projected_states,
+ [self.intermediate_size, self.conv_dim, self.num_heads],
+ dim=-1,
+ )
+
+ # 1D Convolution
+ if cache_params is not None:
+ hidden_states_B_C_t = hidden_states_B_C.transpose(1, 2)
+ conv_state = nn.functional.pad(
+ hidden_states_B_C_t, (self.conv_kernel_size - hidden_states_B_C_t.shape[-1], 0)
+ )
+ conv_state = cache_params.update_conv_state(conv_state, self.layer_idx)
+ if causal_conv1d_fn is None or self.activation not in ["silu", "swish"]:
+ hidden_states_B_C = self.act(
+ self.conv1d(hidden_states_B_C.transpose(1, 2)).transpose(1, 2)[:, :seq_len]
+ ) # (B, L, self.d_inner + 2 * ngroups * d_state)
+ else:
+ hidden_states_B_C = causal_conv1d_fn(
+ x=hidden_states_B_C.transpose(1, 2),
+ weight=self.conv1d.weight.squeeze(1),
+ bias=self.conv1d.bias,
+ activation=self.activation,
+ ).transpose(1, 2)[:, :seq_len]
+ hidden_states, B, C = torch.split(
+ hidden_states_B_C,
+ [self.intermediate_size, groups_time_state_size, groups_time_state_size],
+ dim=-1,
+ )
+ if attention_mask is not None and not torch.all(attention_mask == 1):
+ # tune out hidden states for pad tokens, see https://github.com/state-spaces/mamba/issues/66
+ dtype = hidden_states.dtype
+ hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype)
+ scan_output, ssm_state = mamba_chunk_scan_combined(
+ hidden_states.view(batch_size, seq_len, -1, self.head_dim),
+ time_step,
+ A,
+ B.view(batch_size, seq_len, self.n_groups, -1),
+ C.view(batch_size, seq_len, self.n_groups, -1),
+ chunk_size=self.chunk_size,
+ D=self.D,
+ z=None,
+ seq_idx=None,
+ return_final_states=True,
+ dt_bias=self.dt_bias,
+ dt_softplus=True,
+ **dt_limit_kwargs,
+ )
+ if ssm_state is not None and cache_params is not None:
+ cache_params.update_recurrent_state(ssm_state, self.layer_idx)
+ scan_output = scan_output.view(batch_size, seq_len, -1)
+ # Multiply "gate" branch and apply extra normalization layer
+ scan_output = self.norm(scan_output, gate)
+ out = self.out_proj(scan_output)
+ return out
+
+ # fmt: off
+ def torch_forward(self, input_states, cache_params: Cache | None=None, attention_mask: torch.Tensor | None = None):
+ batch_size, seq_len, _ = input_states.shape
+ dtype = input_states.dtype
+ # Gated MLP's linear projection
+ if cache_params is not None and cache_params.has_previous_state(self.layer_idx):
+ projected_states = self.in_proj(input_states)
+ else:
+ if attention_mask is not None:
+ # tune out hidden states for pad tokens, see https://github.com/state-spaces/mamba/issues/66
+ input_states = (input_states * attention_mask[:, :, None]).to(dtype)
+ projected_states = self.in_proj(input_states)
+ d_mlp = (projected_states.shape[-1] - 2 * self.intermediate_size - 2 * self.n_groups * self.ssm_state_size- self.num_heads) // 2
+ _, _, gate, hidden_states, dt = projected_states.split(
+ [d_mlp, d_mlp, self.intermediate_size, self.conv_dim, self.num_heads], dim=-1
+ )
+ hidden_states = hidden_states.transpose(1, 2)
+
+ use_precomputed_state = cache_params is not None and cache_params.has_previous_state(self.layer_idx)
+
+ # Convolution sequence transformation
+ if use_precomputed_state:
+ conv_state = cache_params.update_conv_state(hidden_states, self.layer_idx)
+ hidden_states = torch.sum(conv_state * self.conv1d.weight[:, 0, :], dim=-1)
+ if self.use_conv_bias:
+ hidden_states += self.conv1d.bias
+ hidden_states = self.act(hidden_states).to(dtype)[:, None, ...] # [batch, 1, intermediate_size] : decoding
+ else:
+ if cache_params is not None:
+ conv_state = nn.functional.pad(
+ hidden_states,
+ (self.conv_kernel_size - hidden_states.shape[-1], 0)
+ )
+ conv_state = cache_params.update_conv_state(conv_state, self.layer_idx)
+
+ hidden_states = self.act(self.conv1d(hidden_states)[..., :seq_len].transpose(1, 2))
+ if attention_mask is not None:
+ dtype = hidden_states.dtype
+ # tune out hidden states for pad tokens, see https://github.com/state-spaces/mamba/issues/66
+ hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype)
+
+ hidden_states, B, C = torch.split(hidden_states, [self.intermediate_size, self.n_groups * self.ssm_state_size, self.n_groups * self.ssm_state_size], dim=-1)
+ A = -torch.exp(self.A_log.float()) # [num_heads]
+ if use_precomputed_state:
+ # Note: there is no need to pad parameter matrices here, as there is just one new token
+ # for batched generation
+ dt = dt[:, None, ...] if dt.ndim == 2 else dt[:, 0, :][:, None, ...]
+ dt = dt.transpose(1, 2).expand(batch_size, dt.shape[-1], self.head_dim)
+ # [num_heads] -> [num_heads, head_dim]
+ dt_bias = self.dt_bias[..., None].expand(self.dt_bias.shape[0], self.head_dim)
+
+ dt = torch.nn.functional.softplus(dt + dt_bias.to(dt.dtype))
+ dt = torch.clamp(dt, self.time_step_min) #, self.time_step_max)
+ A = A[..., None, None].expand(self.num_heads, self.head_dim, self.ssm_state_size).to(dtype=torch.float32)
+ # [bsz, num_heads, head_dim, state_size]
+ dA = torch.exp(dt[..., None] * A)
+
+ # Discretize B
+ # [bsz, n_groups * state_size] -> [bsz, n_groups, 1, state_size] ->
+ # -> [bsz, n_groups, group to head repetition factor, state_size] -> [bsz, num_heads, state_size]
+ B = B.reshape(batch_size, self.n_groups, -1)[..., None, :]
+ B = B.expand(batch_size, self.n_groups, self.num_heads // self.n_groups, B.shape[-1]).contiguous()
+ B = B.reshape(batch_size, -1, B.shape[-1])
+ # [bsz, num_heads, head_dim, state_size]
+ dB = dt[..., None] * B[..., None, :]
+
+ # Discretize x into dB
+ # [bsz, intermediate_size] -> [bsz, num_heads, head_dim]
+ hidden_states = hidden_states.reshape(batch_size, -1, self.head_dim)
+ dBx = dB * hidden_states[..., None]
+
+ # State calculation
+ ssm_states = cache_params.layers[self.layer_idx].recurrent_states.clone()
+ ssm_states = ssm_states * dA + dBx
+ ssm_states = cache_params.update_recurrent_state(ssm_states, self.layer_idx)
+
+ # Subsequent output
+ # [bsz, n_groups * state_size] -> [bsz, num_heads, state_size]
+ C = C.reshape(batch_size, self.n_groups, -1)[..., None, :]
+ C = C.expand(batch_size, self.n_groups, self.num_heads // self.n_groups, C.shape[-1]).contiguous()
+ C = C.reshape(batch_size, -1, C.shape[-1])
+ # [bsz, num_heads, head_dim]
+
+ ssm_states = ssm_states.to(C.dtype) # Shape: [b, h, d, n]
+ # Reshape ssm_states to merge the first two dimensions
+ ssm_states_reshaped = ssm_states.view(batch_size * self.num_heads, self.head_dim, self.ssm_state_size) # Shape: [b*h, d, n]
+ C_reshaped = C.view(batch_size * self.num_heads, self.ssm_state_size, 1) # Shape: [b*h, n, 1]
+ y = torch.bmm(ssm_states_reshaped, C_reshaped)
+ y = y.view(batch_size, self.num_heads, self.head_dim)
+
+ # D skip connection
+ # [num_heads] -> [num_heads, head_dim]
+ D = self.D[..., None].expand(self.D.shape[0], self.head_dim)
+ y = (y + hidden_states * D).to(y.dtype)
+
+ # [bsz, num_heads, head_dim] -> [bsz, 1, intermediate_size]
+ y = y.reshape(batch_size, -1)[:, None, ...]
+ else:
+ # begin ssd naive implementation without einsums
+ dt = nn.functional.softplus(dt + self.dt_bias)
+ dt = torch.clamp(dt, self.time_step_min)
+ hidden_states = hidden_states.reshape(batch_size, seq_len, -1, self.head_dim).float()
+ B = B.reshape(batch_size, seq_len, -1, self.ssm_state_size).float()
+ C = C.reshape(batch_size, seq_len, -1, self.ssm_state_size).float()
+ B = B.repeat_interleave(self.num_heads // self.n_groups, dim=2, output_size=self.num_heads)
+ C = C.repeat_interleave(self.num_heads // self.n_groups, dim=2, output_size=self.num_heads)
+ pad_size = (self.chunk_size - seq_len % self.chunk_size) % self.chunk_size
+
+ D_residual = self.D[..., None] * pad_tensor_by_size(hidden_states, pad_size)
+
+ # Discretize x and A
+ hidden_states = hidden_states * dt[..., None]
+ A = A.to(hidden_states.dtype) * dt
+
+ # Rearrange into blocks/chunks
+ hidden_states, A, B, C = [reshape_into_chunks(t, pad_size, self.chunk_size) for t in (hidden_states, A, B, C)]
+
+
+ # [bsz, -1, chunk_size, num_heads] -> [bsz, num_heads, -1, chunk_size]
+ A = A.permute(0, 3, 1, 2)
+ A_cumsum = torch.cumsum(A, dim=-1)
+
+ # 1. Compute the output for each intra-chunk (diagonal blocks)
+ # This is the analog of a causal mask
+ L = torch.exp(segment_sum(A))
+
+ # First, contraction of C and B to get G (attention-weights like)
+ G_intermediate = C[:, :, :, None, :, :] * B[:, :, None, :, : ,:] # shape: (b, c, l, s, h, n)
+ G = G_intermediate.sum(dim=-1) # shape: (b, c, l, s, h)
+
+
+ # Step 2: Compute M, equivalent to applying attention mask to weights
+ M_intermediate = G[..., None] * L.permute(0, 2, 3, 4, 1)[..., None]
+ M = M_intermediate.sum(dim=-1)
+
+ # Step 3: Compute Y_diag (apply to values)
+ Y_diag = (M[..., None] * hidden_states[:, :, None]).sum(3)
+
+ # (right term of low-rank factorization of off-diagonal blocks; B terms)
+
+ decay_states = torch.exp(A_cumsum[:, :, :, -1:] - A_cumsum)
+ B_decay_contraction = B * decay_states.permute(0, 2, 3, 1)[..., None]
+ # permute back B * decay states
+ states = (B_decay_contraction.permute(0, 1, 3, 2, 4)[..., None] * hidden_states.permute(0, 1, 3, 2, 4)[..., None, :]).sum(dim=3).permute(0, 1, 2, 4, 3)
+ previous_states = torch.zeros_like(states[:, :1])
+ states = torch.cat([previous_states, states], dim=1)
+ decay_chunk = torch.exp(segment_sum(nn.functional.pad(A_cumsum[:, :, :, -1], (1, 0))))
+
+ states_permuted = states.permute(0, 2, 1, 3, 4)
+ result = (decay_chunk[..., None, None] * states_permuted[:, :, None, ...]).sum(dim=2)
+ new_states = result.permute(0, 2, 1, 3, 4)
+ states, ssm_state = new_states[:, :-1], new_states[:, -1]
+
+ # Compute state -> output conversion per chunk
+ # (left term of low-rank factorization of off-diagonal blocks; C terms)
+ state_decay_out = torch.exp(A_cumsum)
+ # compute Yoff
+ C_times_states = (C[..., None, :] * states[:, :, None, ...])
+ state_decay_out_permuted = state_decay_out.permute(0, 2, 3, 1)
+ Y_off = (C_times_states.sum(-1) * state_decay_out_permuted[..., None])
+ # Add output of intra-chunk and inter-chunk terms (diagonal and off-diagonal blocks)
+
+ y = Y_diag + Y_off
+ # [bsz, -1, self.chunk_size, num_heads, head_dim] -> [bsz, (padded) seq_len, num_heads, head_dim]
+ y = y.reshape(batch_size, -1, self.num_heads, self.head_dim)
+
+ y = y + D_residual
+ # Cutting off padded chunks
+ if pad_size > 0:
+ y = y[:, :seq_len, :, :]
+ y = y.reshape(batch_size, seq_len, -1)
+ if ssm_state is not None and cache_params is not None:
+ cache_params.update_recurrent_state(ssm_state, self.layer_idx)
+
+ scan_output = self.norm(y, gate)
+
+ # end ssd naive
+
+ # 4. Final linear projection
+ contextualized_states = self.out_proj(scan_output.to(dtype)) # [batch, seq_len, hidden_size]
+ return contextualized_states
+ # fmt: on
+
+ def forward(
+ self,
+ hidden_states,
+ cache_params: Cache | None = None,
+ attention_mask: torch.Tensor | None = None,
+ **kwargs,
+ ):
+ if is_fast_path_available and "cuda" in self.in_proj.weight.device.type and not is_torchdynamo_compiling():
+ # Use cuda stream to avoid NaN when using multiple GPUs, which is caused by multi-GPU synchronization issue.
+ # Mamba might launch on the default cuda stream that not strictly respect the current Pytorch cuda stream.
+ # This leads to kernel reading uninitialized memory before the data transfer is complete.
+ with torch.cuda.stream(torch.cuda.default_stream(hidden_states.device)):
+ return self.cuda_kernels_forward(hidden_states, cache_params, attention_mask)
+
+ return self.torch_forward(hidden_states, cache_params, attention_mask)
+
+
+@use_kernel_forward_from_hub("RMSNorm")
+class NemotronHRMSNorm(nn.Module):
+ def __init__(self, hidden_size, eps: float = 1e-6) -> None:
+ """
+ NemotronHRMSNorm is equivalent to T5LayerNorm
+ """
+ super().__init__()
+ self.weight = nn.Parameter(torch.ones(hidden_size))
+ self.variance_epsilon = eps
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ input_dtype = hidden_states.dtype
+ hidden_states = hidden_states.to(torch.float32)
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
+ return self.weight * hidden_states.to(input_dtype)
+
+ def extra_repr(self):
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
+
+
+class NemotronHMLP(nn.Module):
+ def __init__(self, config, intermediate_size=None, **kwargs):
+ super().__init__()
+ self.config = config
+ self.hidden_size = config.hidden_size
+ self.intermediate_size = intermediate_size or config.intermediate_size
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
+ self.act_fn = ACT2FN[config.mlp_hidden_act]
+
+ def forward(self, x):
+ return self.down_proj(self.act_fn(self.up_proj(x)))
+
+
+@use_experts_implementation(has_gate=False)
+class NemotronHExperts(nn.Module):
+ """
+ Collection of expert weights stored as 3D tensors.
+
+ **Architecture Note**: Unlike Mixtral or DeepSeek which use gated MLPs,
+ NemotronH uses a standard MLP architecture with only up_proj and down_proj
+ """
+
+ def __init__(self, config):
+ super().__init__()
+ self.num_experts = config.n_routed_experts
+ self.hidden_dim = config.hidden_size
+ self.intermediate_dim = config.moe_intermediate_size
+
+ # Determine input/output dimension based on whether latent projection is used
+ input_dim = config.moe_latent_size if config.moe_latent_size is not None else config.hidden_size
+
+ # All expert weights stored as 3D tensors: (num_experts, out_dim, in_dim)
+ # up_proj: (num_experts, intermediate_dim, input_dim)
+ self.up_proj = nn.Parameter(torch.empty(self.num_experts, self.intermediate_dim, input_dim))
+ # down_proj: (num_experts, input_dim, intermediate_dim)
+ self.down_proj = nn.Parameter(torch.empty(self.num_experts, input_dim, self.intermediate_dim))
+
+ self.act_fn = ACT2FN[config.mlp_hidden_act]
+
+ def forward(self, hidden_states: torch.Tensor, top_k_index: torch.Tensor, top_k_weights: torch.Tensor):
+ final_hidden_states = torch.zeros_like(hidden_states, dtype=top_k_weights.dtype)
+
+ # Create expert mask to identify which tokens go to which experts
+ with torch.no_grad():
+ expert_mask = torch.nn.functional.one_hot(top_k_index, num_classes=self.num_experts)
+ expert_mask = expert_mask.permute(2, 1, 0) # (num_experts, num_experts_per_tok, num_tokens)
+ # Only iterate over experts that have at least one token assigned
+ expert_hit = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero().squeeze(-1)
+
+ for expert_idx in expert_hit:
+ expert_idx = expert_idx.item()
+ # Find which tokens are routed to this expert
+ top_k_pos, token_idx = torch.where(expert_mask[expert_idx])
+
+ if token_idx.numel() == 0:
+ continue
+
+ # Get input for this expert
+ current_state = hidden_states[token_idx]
+
+ # Expert computation: down_proj(act_fn(up_proj(x)))
+ # No gating mechanism unlike Mixtral which uses: down_proj(act_fn(gate_proj(x)) * up_proj(x))
+ current_hidden_states = torch.nn.functional.linear(current_state, self.up_proj[expert_idx])
+ current_hidden_states = self.act_fn(current_hidden_states)
+ current_hidden_states = torch.nn.functional.linear(current_hidden_states, self.down_proj[expert_idx])
+
+ # Apply routing weights
+ current_hidden_states = current_hidden_states * top_k_weights[token_idx, top_k_pos, None]
+
+ # Accumulate into final output
+ final_hidden_states.index_add_(0, token_idx, current_hidden_states.to(final_hidden_states.dtype))
+
+ return final_hidden_states.to(hidden_states.dtype)
+
+
+class NemotronHMoE(nn.Module):
+ """
+ Mixture-of-Experts (MoE) module for NemotronH.
+
+ Unique architectures:
+ - Uses non-gated MLP experts (NemotronHExperts) instead of gated experts
+ - Adds optional latent projection for computational efficiency
+ """
+
+ def __init__(self, config, layer_idx: int | None = None):
+ super().__init__()
+ self.config = config
+
+ # Replace with NemotronH-specific experts (non-gated MLP architecture)
+ self.experts = NemotronHExperts(config)
+ self.gate = NemotronHTopkRouter(config)
+
+ # Override shared_experts to use NemotronHMLP with correct intermediate size
+ self.shared_experts = NemotronHMLP(config=config, intermediate_size=config.moe_shared_expert_intermediate_size)
+ self.n_routed_experts = config.n_routed_experts
+ self.n_group = config.n_group
+ self.topk_group = config.topk_group
+ self.norm_topk_prob = config.norm_topk_prob
+ self.routed_scaling_factor = config.routed_scaling_factor
+ self.top_k = config.num_experts_per_tok
+
+ # NemotronH-specific latent projection layers
+ if config.moe_latent_size is not None:
+ self.fc1_latent_proj = nn.Linear(config.hidden_size, config.moe_latent_size, bias=config.mlp_bias)
+ self.fc2_latent_proj = nn.Linear(config.moe_latent_size, config.hidden_size, bias=config.mlp_bias)
+ else:
+ self.fc1_latent_proj = nn.Identity()
+ self.fc2_latent_proj = nn.Identity()
+
+ def route_tokens_to_experts(self, router_logits):
+ router_logits = router_logits.sigmoid()
+ router_logits_for_choice = router_logits + self.gate.e_score_correction_bias
+ group_scores = (
+ router_logits_for_choice.view(-1, self.n_group, self.n_routed_experts // self.n_group)
+ .topk(2, dim=-1)[0]
+ .sum(dim=-1)
+ )
+ group_idx = torch.topk(group_scores, k=self.topk_group, dim=-1, sorted=False)[1]
+ group_mask = torch.zeros_like(group_scores)
+ group_mask.scatter_(1, group_idx, 1)
+ score_mask = (
+ group_mask.unsqueeze(-1)
+ .expand(-1, self.n_group, self.n_routed_experts // self.n_group)
+ .reshape(-1, self.n_routed_experts)
+ )
+ scores_for_choice = router_logits_for_choice.masked_fill(~score_mask.bool(), float("-inf"))
+ topk_indices = torch.topk(scores_for_choice, k=self.top_k, dim=-1, sorted=False)[1]
+ topk_weights = router_logits.gather(1, topk_indices)
+ if self.norm_topk_prob:
+ denominator = topk_weights.sum(dim=-1, keepdim=True) + 1e-20
+ topk_weights /= denominator
+ topk_weights = topk_weights * self.routed_scaling_factor
+ return topk_indices, topk_weights
+
+ def forward(self, hidden_states):
+ residuals = hidden_states
+ orig_shape = hidden_states.shape
+ router_logits = self.gate(hidden_states)
+ topk_indices, topk_weights = self.route_tokens_to_experts(router_logits)
+ hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
+
+ # NemotronH-specific: latent projection
+ hidden_states = self.fc1_latent_proj(hidden_states)
+ hidden_states = self.experts(hidden_states, topk_indices, topk_weights)
+ hidden_states = self.fc2_latent_proj(hidden_states)
+
+ hidden_states = hidden_states.view(*orig_shape)
+ hidden_states = hidden_states + self.shared_experts(residuals)
+ return hidden_states
+
+
+class NemotronHTopkRouter(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.n_routed_experts = config.n_routed_experts
+
+ self.weight = nn.Parameter(torch.empty((self.n_routed_experts, config.hidden_size)))
+ self.register_buffer("e_score_correction_bias", torch.zeros(self.n_routed_experts))
+
+ def forward(self, hidden_states):
+ hidden_states = hidden_states.view(-1, self.config.hidden_size)
+ router_logits = F.linear(hidden_states.type(torch.float32), self.weight.type(torch.float32))
+ return router_logits
+
+
+def rotate_half(x):
+ """Rotates half the hidden dims of the input."""
+ x1 = x[..., : x.shape[-1] // 2]
+ x2 = x[..., x.shape[-1] // 2 :]
+ return torch.cat((-x2, x1), dim=-1)
+
+
+@use_kernel_func_from_hub("rotary_pos_emb")
+def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
+ """Applies Rotary Position Embedding to the query and key tensors.
+
+ Args:
+ q (`torch.Tensor`): The query tensor.
+ k (`torch.Tensor`): The key tensor.
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
+ Returns:
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
+ """
+ cos = cos.unsqueeze(unsqueeze_dim)
+ sin = sin.unsqueeze(unsqueeze_dim)
+ q_embed = (q * cos) + (rotate_half(q) * sin)
+ k_embed = (k * cos) + (rotate_half(k) * sin)
+ return q_embed, k_embed
+
+
+def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
+ """
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
+ """
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
+ if n_rep == 1:
+ return hidden_states
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
+
+
+def eager_attention_forward(
+ module: nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: torch.Tensor | None,
+ scaling: float,
+ dropout: float = 0.0,
+ **kwargs: Unpack[TransformersKwargs],
+):
+ key_states = repeat_kv(key, module.num_key_value_groups)
+ value_states = repeat_kv(value, module.num_key_value_groups)
+
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
+ if attention_mask is not None:
+ attn_weights = attn_weights + attention_mask
+
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
+ attn_output = torch.matmul(attn_weights, value_states)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+
+ return attn_output, attn_weights
+
+
+@use_kernelized_func(apply_rotary_pos_emb)
+class NemotronHAttention(nn.Module):
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
+
+ def __init__(self, config: NemotronHConfig, layer_idx: int):
+ super().__init__()
+ self.config = config
+ self.layer_idx = layer_idx
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
+ self.scaling = self.head_dim**-0.5
+ self.attention_dropout = config.attention_dropout
+ self.is_causal = True
+ self.q_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=False)
+ self.k_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=False)
+ self.v_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=False)
+ self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor | None = None,
+ past_key_values: Cache | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor, torch.Tensor | None]:
+ input_shape = hidden_states.shape[:-1]
+ hidden_shape = (*input_shape, -1, self.head_dim)
+
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+
+ if past_key_values is not None:
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_states,
+ key_states,
+ value_states,
+ attention_mask,
+ dropout=0.0 if not self.training else self.attention_dropout,
+ scaling=self.scaling,
+ **kwargs,
+ )
+
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ attn_output = self.o_proj(attn_output)
+ return attn_output, attn_weights
+
+
+MIXER_TYPES = {
+ "mamba": NemotronHMamba2Mixer,
+ "attention": NemotronHAttention,
+ "moe": NemotronHMoE,
+ "mlp": NemotronHMLP,
+}
+
+
+class NemotronHBlock(GradientCheckpointingLayer):
+ """
+ A single transformer block in the NemotronH model.
+
+ This block can contain different types of mixers (Mamba, Attention, MLP, or MoE)
+ depending on the configuration. Each block applies pre-normalization followed by
+ the mixer, then adds a residual connection.
+
+ Args:
+ config (`NemotronHConfig`):
+ Model configuration specifying the block architecture.
+ layer_idx (`int`):
+ Index of this block in the model. Used to determine the block type from
+ `config.layers_block_type[layer_idx]`.
+ """
+
+ def __init__(self, config, layer_idx):
+ super().__init__()
+ self.config = config
+ self.layer_idx = layer_idx
+ self.norm = NemotronHRMSNorm(config.hidden_size, eps=config.layer_norm_epsilon)
+
+ self.block_type = config.layers_block_type[layer_idx]
+ self.mixer = MIXER_TYPES[self.block_type](config, layer_idx=layer_idx)
+
+ def forward(
+ self,
+ hidden_states,
+ past_key_values: Cache | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ use_cache: bool | None = False,
+ **kwargs: Unpack[TransformersKwargs],
+ ):
+ residual = hidden_states
+ hidden_states = self.norm(hidden_states.to(dtype=self.norm.weight.dtype))
+
+ if self.block_type == "mamba":
+ hidden_states = self.mixer(hidden_states, cache_params=past_key_values, attention_mask=attention_mask)
+ elif self.block_type == "attention":
+ hidden_states, _ = self.mixer(
+ hidden_states=hidden_states,
+ past_key_values=past_key_values,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ use_cache=use_cache,
+ **kwargs,
+ )
+ else:
+ hidden_states = self.mixer(hidden_states)
+
+ hidden_states = residual + hidden_states
+
+ return hidden_states
+
+
+class NemotronHPreTrainedModel(PreTrainedModel):
+ config: NemotronHConfig
+ base_model_prefix = "model"
+ supports_gradient_checkpointing = True
+ _no_split_modules = ["NemotronHBlock"]
+ _skip_keys_device_placement = ["past_key_values"]
+ _supports_flash_attn = True
+ _supports_flash_attn_2 = True
+ _supports_sdpa = True
+ _supports_flex_attn = True
+ _is_stateful = True
+ _can_record_outputs = {
+ "hidden_states": NemotronHBlock,
+ "attentions": NemotronHAttention,
+ }
+ _keep_in_fp32_modules_strict = [
+ "e_score_correction_bias",
+ ]
+ _keys_to_ignore_on_load_unexpected = [r"mtp.*"]
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ """Initialize the weights."""
+ super()._init_weights(module)
+ if isinstance(module, NemotronHMamba2Mixer):
+ # Only re-initialise params that were NOT loaded from a checkpoint.
+ # `_is_hf_initialized` is set by `from_pretrained` on each loaded
+ # parameter; without this guard a post-load safety pass of
+ # `_init_weights` would overwrite checkpoint values of
+ # A_log / D / dt_bias with fresh random draws.
+ if not getattr(module.A_log, "_is_hf_initialized", False):
+ A = torch.arange(1, self.config.mamba_num_heads + 1)
+ init.copy_(module.A_log, torch.log(A))
+ if not getattr(module.D, "_is_hf_initialized", False):
+ init.ones_(module.D)
+ if not getattr(module.dt_bias, "_is_hf_initialized", False):
+ dt = torch.exp(
+ torch.rand(self.config.mamba_num_heads)
+ * (math.log(self.config.time_step_max) - math.log(self.config.time_step_min))
+ + math.log(self.config.time_step_min)
+ ).clamp(min=self.config.time_step_floor)
+
+ # # Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
+ inv_dt = dt + torch.log(-torch.expm1(-dt))
+ with torch.no_grad():
+ init.copy_(module.dt_bias, inv_dt)
+ elif isinstance(module, NemotronHTopkRouter):
+ init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
+ init.zeros_(module.e_score_correction_bias)
+ elif isinstance(module, NemotronHExperts):
+ # Initialize expert weights
+ init.normal_(module.up_proj, mean=0.0, std=self.config.initializer_range)
+ init.normal_(module.down_proj, mean=0.0, std=self.config.initializer_range)
+
+ if isinstance(module, nn.Linear):
+ if module.bias is not None:
+ if not getattr(module.bias, "_is_hf_initialized", False):
+ init.zeros_(module.bias)
+ elif isinstance(module, nn.Embedding):
+ init.normal_(module.weight, std=self.config.initializer_range)
+
+ if self.config.rescale_prenorm_residual:
+ # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
+ # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
+ # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
+ # > -- GPT-2 :: https://openai.com/blog/better-language-models/
+ #
+ # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
+ for name, p in module.named_parameters():
+ if name == "out_proj.weight":
+ # Skip checkpoint-loaded weights so a post-load safety
+ # pass of `_init_weights` doesn't silently overwrite them.
+ if getattr(p, "_is_hf_initialized", False):
+ continue
+ # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
+ # Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
+ init.kaiming_uniform_(p, a=math.sqrt(5))
+ with torch.no_grad():
+ p_new = p / math.sqrt(self.config.num_hidden_layers)
+ init.copy_(p, p_new)
+
+
+class NemotronHModel(NemotronHPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size)
+ self.layers = nn.ModuleList([NemotronHBlock(config, layer_idx=idx) for idx in range(config.num_hidden_layers)])
+
+ self.norm_f = NemotronHRMSNorm(config.hidden_size, eps=config.layer_norm_epsilon)
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.embeddings
+
+ def set_input_embeddings(self, new_embeddings):
+ self.embeddings = new_embeddings
+
+ @merge_with_config_defaults
+ @capture_outputs
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ use_cache: bool | None = None,
+ attention_mask: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutputWithPast:
+ if (input_ids is None) ^ (inputs_embeds is not None): # ^ is python for xor
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
+
+ if inputs_embeds is None:
+ inputs_embeds = self.embeddings(input_ids)
+
+ if use_cache and past_key_values is None:
+ past_key_values = DynamicCache(config=self.config)
+
+ hidden_states = inputs_embeds
+
+ if position_ids is None:
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
+ position_ids = torch.arange(hidden_states.shape[1], device=hidden_states.device) + past_seen_tokens
+ position_ids = position_ids.unsqueeze(0)
+
+ causal_mask = create_causal_mask(
+ config=self.config,
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ position_ids=position_ids,
+ )
+ mamba_mask = self._update_mamba_mask(attention_mask, past_key_values)
+
+ # Map block types to their corresponding masks
+ block_type_to_mask = {
+ "mamba": mamba_mask,
+ "attention": causal_mask,
+ "moe": None,
+ "mlp": None,
+ }
+
+ for layer_idx, mixer_block in enumerate(self.layers):
+ layer_mask = block_type_to_mask[mixer_block.block_type]
+
+ hidden_states = mixer_block(
+ hidden_states,
+ attention_mask=layer_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ **kwargs,
+ )
+
+ hidden_states = self.norm_f(hidden_states)
+
+ return BaseModelOutputWithPast(
+ last_hidden_state=hidden_states,
+ past_key_values=past_key_values if use_cache else None,
+ )
+
+ def _update_mamba_mask(self, attention_mask, past_key_values):
+ """
+ No need for zeroing states when
+ 1. Cached forward
+ 2. Attending to all inputs
+ """
+ mamba_mask = attention_mask
+ if (past_key_values is not None and past_key_values.has_previous_state()) or (
+ attention_mask is not None and torch.all(attention_mask == 1)
+ ):
+ mamba_mask = None
+ return mamba_mask
+
+
+# Adapted from transformers.models.jamba.modeling_jamba.JambaForCausalLM with Jamba->NemotronH, JAMBA->NEMOTRON_H
+class NemotronHForCausalLM(NemotronHPreTrainedModel, GenerationMixin):
+ _tied_weights_keys = {}
+
+ def __init__(self, config: NemotronHConfig):
+ super().__init__(config)
+ self.model = NemotronHModel(config)
+ self.vocab_size = config.vocab_size
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ use_cache: bool | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ **kwargs,
+ ) -> tuple | CausalLMOutputWithPast:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
+
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, NemotronHForCausalLM
+
+ >>> model = NemotronHForCausalLM.from_pretrained("Zyphra/NemotronH-7B-v1")
+ >>> tokenizer = AutoTokenizer.from_pretrained("Zyphra/NemotronH-7B-v1")
+
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
+
+ >>> # Generate
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
+ ```"""
+ outputs = self.model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ **kwargs,
+ )
+
+ hidden_states = outputs[0]
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
+ logits = self.lm_head(hidden_states[:, slice_indices, :]).float()
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
+
+ return CausalLMOutputWithPast(
+ loss=loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+ def prepare_inputs_for_generation(
+ self,
+ input_ids,
+ past_key_values=None,
+ attention_mask=None,
+ inputs_embeds=None,
+ position_ids=None,
+ use_cache=True,
+ is_first_iteration=False,
+ **kwargs,
+ ):
+ kwargs["logits_to_keep"] = self.config.num_logits_to_keep
+ model_inputs = super().prepare_inputs_for_generation(
+ input_ids,
+ past_key_values=past_key_values,
+ attention_mask=attention_mask,
+ inputs_embeds=inputs_embeds,
+ position_ids=position_ids,
+ use_cache=use_cache,
+ is_first_iteration=is_first_iteration,
+ **kwargs,
+ )
+
+ return model_inputs
+
+
+__all__ = ["NemotronHPreTrainedModel", "NemotronHModel", "NemotronHForCausalLM"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/nemotron_h/modular_nemotron_h.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/nemotron_h/modular_nemotron_h.py
new file mode 100644
index 0000000000000000000000000000000000000000..c3f6f3b91acd2751c1f05375659443ec66e36a2f
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/nemotron_h/modular_nemotron_h.py
@@ -0,0 +1,531 @@
+# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
+# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from __future__ import annotations
+
+import math
+
+import torch
+from torch import nn
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...cache_utils import Cache, DynamicCache
+from ...integrations import use_experts_implementation
+from ...masking_utils import create_causal_mask
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
+from ...modeling_utils import PreTrainedModel
+from ...models.deepseek_v3.modeling_deepseek_v3 import DeepseekV3MoE, DeepseekV3TopkRouter
+from ...models.jamba.modeling_jamba import JambaAttention
+from ...models.llama.modeling_llama import LlamaRMSNorm
+from ...models.nemotron.modeling_nemotron import NemotronMLP
+from ...models.zamba.modeling_zamba import ZambaForCausalLM
+from ...models.zamba2.modeling_zamba2 import Zamba2MambaMixer, Zamba2RMSNormGated
+from ...processing_utils import Unpack
+from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, is_torchdynamo_compiling, logging
+from ...utils.generic import merge_with_config_defaults
+from ...utils.output_capturing import capture_outputs
+from .configuration_nemotron_h import NemotronHConfig
+
+
+logger = logging.get_logger(__name__)
+
+is_fast_path_available = False
+
+
+class NemotronHMamba2Mixer(Zamba2MambaMixer):
+ def __init__(self, config: NemotronHConfig, layer_idx: int | None = None):
+ super().__init__(config, layer_idx)
+ self.ssm_state_size = config.ssm_state_size
+ self.conv_kernel_size = config.conv_kernel
+ self.intermediate_size = config.mamba_num_heads * config.mamba_head_dim
+ self.use_conv_bias = config.use_conv_bias
+ self.activation = config.mamba_hidden_act
+ self.act = ACT2FN[config.mamba_hidden_act]
+ self.use_mem_eff_path = True
+
+ self.n_groups = config.n_groups
+ self.head_dim = config.mamba_head_dim
+ self.num_heads = config.mamba_num_heads
+
+ self.conv1d = nn.Conv1d(
+ in_channels=self.conv_dim,
+ out_channels=self.conv_dim,
+ bias=config.use_conv_bias,
+ kernel_size=self.conv_kernel_size,
+ groups=self.conv_dim,
+ padding=self.conv_kernel_size - 1,
+ )
+
+ # projection of the input hidden states
+ projection_size = self.intermediate_size + self.conv_dim + self.num_heads
+
+ self.in_proj = nn.Linear(
+ self.hidden_size,
+ projection_size,
+ bias=config.use_bias,
+ )
+
+ self.norm = Zamba2RMSNormGated(
+ self.intermediate_size, group_size=self.intermediate_size // self.n_groups, eps=config.layer_norm_epsilon
+ )
+
+ self.out_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.use_bias)
+
+ def forward(
+ self,
+ hidden_states,
+ cache_params: Cache | None = None,
+ attention_mask: torch.Tensor | None = None,
+ **kwargs,
+ ):
+ if is_fast_path_available and "cuda" in self.in_proj.weight.device.type and not is_torchdynamo_compiling():
+ # Use cuda stream to avoid NaN when using multiple GPUs, which is caused by multi-GPU synchronization issue.
+ # Mamba might launch on the default cuda stream that not strictly respect the current Pytorch cuda stream.
+ # This leads to kernel reading uninitialized memory before the data transfer is complete.
+ with torch.cuda.stream(torch.cuda.default_stream(hidden_states.device)):
+ return self.cuda_kernels_forward(hidden_states, cache_params, attention_mask)
+
+ return self.torch_forward(hidden_states, cache_params, attention_mask)
+
+
+class NemotronHRMSNorm(LlamaRMSNorm):
+ pass
+
+
+class NemotronHMLP(NemotronMLP, nn.Module):
+ def __init__(self, config, intermediate_size=None, **kwargs):
+ nn.Module.__init__()
+ self.config = config
+ self.hidden_size = config.hidden_size
+ self.intermediate_size = intermediate_size or config.intermediate_size
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
+ self.act_fn = ACT2FN[config.mlp_hidden_act]
+
+
+@use_experts_implementation(has_gate=False)
+class NemotronHExperts(nn.Module):
+ """
+ Collection of expert weights stored as 3D tensors.
+
+ **Architecture Note**: Unlike Mixtral or DeepSeek which use gated MLPs,
+ NemotronH uses a standard MLP architecture with only up_proj and down_proj
+ """
+
+ def __init__(self, config):
+ super().__init__()
+ self.num_experts = config.n_routed_experts
+ self.hidden_dim = config.hidden_size
+ self.intermediate_dim = config.moe_intermediate_size
+
+ # Determine input/output dimension based on whether latent projection is used
+ input_dim = config.moe_latent_size if config.moe_latent_size is not None else config.hidden_size
+
+ # All expert weights stored as 3D tensors: (num_experts, out_dim, in_dim)
+ # up_proj: (num_experts, intermediate_dim, input_dim)
+ self.up_proj = nn.Parameter(torch.empty(self.num_experts, self.intermediate_dim, input_dim))
+ # down_proj: (num_experts, input_dim, intermediate_dim)
+ self.down_proj = nn.Parameter(torch.empty(self.num_experts, input_dim, self.intermediate_dim))
+
+ self.act_fn = ACT2FN[config.mlp_hidden_act]
+
+ def forward(self, hidden_states: torch.Tensor, top_k_index: torch.Tensor, top_k_weights: torch.Tensor):
+ final_hidden_states = torch.zeros_like(hidden_states, dtype=top_k_weights.dtype)
+
+ # Create expert mask to identify which tokens go to which experts
+ with torch.no_grad():
+ expert_mask = torch.nn.functional.one_hot(top_k_index, num_classes=self.num_experts)
+ expert_mask = expert_mask.permute(2, 1, 0) # (num_experts, num_experts_per_tok, num_tokens)
+ # Only iterate over experts that have at least one token assigned
+ expert_hit = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero().squeeze(-1)
+
+ for expert_idx in expert_hit:
+ expert_idx = expert_idx.item()
+ # Find which tokens are routed to this expert
+ top_k_pos, token_idx = torch.where(expert_mask[expert_idx])
+
+ if token_idx.numel() == 0:
+ continue
+
+ # Get input for this expert
+ current_state = hidden_states[token_idx]
+
+ # Expert computation: down_proj(act_fn(up_proj(x)))
+ # No gating mechanism unlike Mixtral which uses: down_proj(act_fn(gate_proj(x)) * up_proj(x))
+ current_hidden_states = torch.nn.functional.linear(current_state, self.up_proj[expert_idx])
+ current_hidden_states = self.act_fn(current_hidden_states)
+ current_hidden_states = torch.nn.functional.linear(current_hidden_states, self.down_proj[expert_idx])
+
+ # Apply routing weights
+ current_hidden_states = current_hidden_states * top_k_weights[token_idx, top_k_pos, None]
+
+ # Accumulate into final output
+ final_hidden_states.index_add_(0, token_idx, current_hidden_states.to(final_hidden_states.dtype))
+
+ return final_hidden_states.to(hidden_states.dtype)
+
+
+class NemotronHMoE(DeepseekV3MoE):
+ """
+ Mixture-of-Experts (MoE) module for NemotronH.
+
+ Unique architectures:
+ - Uses non-gated MLP experts (NemotronHExperts) instead of gated experts
+ - Adds optional latent projection for computational efficiency
+ """
+
+ def __init__(self, config, layer_idx: int | None = None):
+ super().__init__(config)
+
+ # Replace with NemotronH-specific experts (non-gated MLP architecture)
+ self.experts = NemotronHExperts(config)
+ self.gate = NemotronHTopkRouter(config)
+
+ # Override shared_experts to use NemotronHMLP with correct intermediate size
+ self.shared_experts = NemotronHMLP(config=config, intermediate_size=config.moe_shared_expert_intermediate_size)
+
+ # NemotronH-specific latent projection layers
+ if config.moe_latent_size is not None:
+ self.fc1_latent_proj = nn.Linear(config.hidden_size, config.moe_latent_size, bias=config.mlp_bias)
+ self.fc2_latent_proj = nn.Linear(config.moe_latent_size, config.hidden_size, bias=config.mlp_bias)
+ else:
+ self.fc1_latent_proj = nn.Identity()
+ self.fc2_latent_proj = nn.Identity()
+
+ def forward(self, hidden_states):
+ residuals = hidden_states
+ orig_shape = hidden_states.shape
+ router_logits = self.gate(hidden_states)
+ topk_indices, topk_weights = self.route_tokens_to_experts(router_logits)
+ hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
+
+ # NemotronH-specific: latent projection
+ hidden_states = self.fc1_latent_proj(hidden_states)
+ hidden_states = self.experts(hidden_states, topk_indices, topk_weights)
+ hidden_states = self.fc2_latent_proj(hidden_states)
+
+ hidden_states = hidden_states.view(*orig_shape)
+ hidden_states = hidden_states + self.shared_experts(residuals)
+ return hidden_states
+
+
+class NemotronHTopkRouter(DeepseekV3TopkRouter):
+ pass
+
+
+class NemotronHAttention(JambaAttention):
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor | None = None,
+ past_key_values: Cache | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor, torch.Tensor | None]:
+ return super().forward(hidden_states, attention_mask, past_key_values, **kwargs)
+
+
+MIXER_TYPES = {
+ "mamba": NemotronHMamba2Mixer,
+ "attention": NemotronHAttention,
+ "moe": NemotronHMoE,
+ "mlp": NemotronHMLP,
+}
+
+
+class NemotronHBlock(GradientCheckpointingLayer):
+ """
+ A single transformer block in the NemotronH model.
+
+ This block can contain different types of mixers (Mamba, Attention, MLP, or MoE)
+ depending on the configuration. Each block applies pre-normalization followed by
+ the mixer, then adds a residual connection.
+
+ Args:
+ config (`NemotronHConfig`):
+ Model configuration specifying the block architecture.
+ layer_idx (`int`):
+ Index of this block in the model. Used to determine the block type from
+ `config.layers_block_type[layer_idx]`.
+ """
+
+ def __init__(self, config, layer_idx):
+ super().__init__()
+ self.config = config
+ self.layer_idx = layer_idx
+ self.norm = NemotronHRMSNorm(config.hidden_size, eps=config.layer_norm_epsilon)
+
+ self.block_type = config.layers_block_type[layer_idx]
+ self.mixer = MIXER_TYPES[self.block_type](config, layer_idx=layer_idx)
+
+ def forward(
+ self,
+ hidden_states,
+ past_key_values: Cache | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ use_cache: bool | None = False,
+ **kwargs: Unpack[TransformersKwargs],
+ ):
+ residual = hidden_states
+ hidden_states = self.norm(hidden_states.to(dtype=self.norm.weight.dtype))
+
+ if self.block_type == "mamba":
+ hidden_states = self.mixer(hidden_states, cache_params=past_key_values, attention_mask=attention_mask)
+ elif self.block_type == "attention":
+ hidden_states, _ = self.mixer(
+ hidden_states=hidden_states,
+ past_key_values=past_key_values,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ use_cache=use_cache,
+ **kwargs,
+ )
+ else:
+ hidden_states = self.mixer(hidden_states)
+
+ hidden_states = residual + hidden_states
+
+ return hidden_states
+
+
+class NemotronHPreTrainedModel(PreTrainedModel):
+ config: NemotronHConfig
+ base_model_prefix = "model"
+ supports_gradient_checkpointing = True
+ _no_split_modules = ["NemotronHBlock"]
+ _skip_keys_device_placement = ["past_key_values"]
+ _supports_flash_attn = True
+ _supports_flash_attn_2 = True
+ _supports_sdpa = True
+ _supports_flex_attn = True
+ _is_stateful = True
+ _can_record_outputs = {
+ "hidden_states": NemotronHBlock,
+ "attentions": NemotronHAttention,
+ }
+ _keep_in_fp32_modules_strict = [
+ "e_score_correction_bias",
+ ]
+ _keys_to_ignore_on_load_unexpected = [r"mtp.*"]
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ """Initialize the weights."""
+ super()._init_weights(module)
+ if isinstance(module, NemotronHMamba2Mixer):
+ # Only re-initialise params that were NOT loaded from a checkpoint.
+ # `_is_hf_initialized` is set by `from_pretrained` on each loaded
+ # parameter; without this guard a post-load safety pass of
+ # `_init_weights` would overwrite checkpoint values of
+ # A_log / D / dt_bias with fresh random draws.
+ if not getattr(module.A_log, "_is_hf_initialized", False):
+ A = torch.arange(1, self.config.mamba_num_heads + 1)
+ init.copy_(module.A_log, torch.log(A))
+ if not getattr(module.D, "_is_hf_initialized", False):
+ init.ones_(module.D)
+ if not getattr(module.dt_bias, "_is_hf_initialized", False):
+ dt = torch.exp(
+ torch.rand(self.config.mamba_num_heads)
+ * (math.log(self.config.time_step_max) - math.log(self.config.time_step_min))
+ + math.log(self.config.time_step_min)
+ ).clamp(min=self.config.time_step_floor)
+
+ # # Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
+ inv_dt = dt + torch.log(-torch.expm1(-dt))
+ with torch.no_grad():
+ init.copy_(module.dt_bias, inv_dt)
+ elif isinstance(module, NemotronHTopkRouter):
+ init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
+ init.zeros_(module.e_score_correction_bias)
+ elif isinstance(module, NemotronHExperts):
+ # Initialize expert weights
+ init.normal_(module.up_proj, mean=0.0, std=self.config.initializer_range)
+ init.normal_(module.down_proj, mean=0.0, std=self.config.initializer_range)
+
+ if isinstance(module, nn.Linear):
+ if module.bias is not None:
+ if not getattr(module.bias, "_is_hf_initialized", False):
+ init.zeros_(module.bias)
+ elif isinstance(module, nn.Embedding):
+ init.normal_(module.weight, std=self.config.initializer_range)
+
+ if self.config.rescale_prenorm_residual:
+ # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
+ # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
+ # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
+ # > -- GPT-2 :: https://openai.com/blog/better-language-models/
+ #
+ # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
+ for name, p in module.named_parameters():
+ if name == "out_proj.weight":
+ # Skip checkpoint-loaded weights so a post-load safety
+ # pass of `_init_weights` doesn't silently overwrite them.
+ if getattr(p, "_is_hf_initialized", False):
+ continue
+ # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
+ # Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
+ init.kaiming_uniform_(p, a=math.sqrt(5))
+ with torch.no_grad():
+ p_new = p / math.sqrt(self.config.num_hidden_layers)
+ init.copy_(p, p_new)
+
+
+class NemotronHModel(NemotronHPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size)
+ self.layers = nn.ModuleList([NemotronHBlock(config, layer_idx=idx) for idx in range(config.num_hidden_layers)])
+
+ self.norm_f = NemotronHRMSNorm(config.hidden_size, eps=config.layer_norm_epsilon)
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.embeddings
+
+ def set_input_embeddings(self, new_embeddings):
+ self.embeddings = new_embeddings
+
+ @merge_with_config_defaults
+ @capture_outputs
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ use_cache: bool | None = None,
+ attention_mask: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutputWithPast:
+ if (input_ids is None) ^ (inputs_embeds is not None): # ^ is python for xor
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
+
+ if inputs_embeds is None:
+ inputs_embeds = self.embeddings(input_ids)
+
+ if use_cache and past_key_values is None:
+ past_key_values = DynamicCache(config=self.config)
+
+ hidden_states = inputs_embeds
+
+ if position_ids is None:
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
+ position_ids = torch.arange(hidden_states.shape[1], device=hidden_states.device) + past_seen_tokens
+ position_ids = position_ids.unsqueeze(0)
+
+ causal_mask = create_causal_mask(
+ config=self.config,
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ position_ids=position_ids,
+ )
+ mamba_mask = self._update_mamba_mask(attention_mask, past_key_values)
+
+ # Map block types to their corresponding masks
+ block_type_to_mask = {
+ "mamba": mamba_mask,
+ "attention": causal_mask,
+ "moe": None,
+ "mlp": None,
+ }
+
+ for layer_idx, mixer_block in enumerate(self.layers):
+ layer_mask = block_type_to_mask[mixer_block.block_type]
+
+ hidden_states = mixer_block(
+ hidden_states,
+ attention_mask=layer_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ **kwargs,
+ )
+
+ hidden_states = self.norm_f(hidden_states)
+
+ return BaseModelOutputWithPast(
+ last_hidden_state=hidden_states,
+ past_key_values=past_key_values if use_cache else None,
+ )
+
+ def _update_mamba_mask(self, attention_mask, past_key_values):
+ """
+ No need for zeroing states when
+ 1. Cached forward
+ 2. Attending to all inputs
+ """
+ mamba_mask = attention_mask
+ if (past_key_values is not None and past_key_values.has_previous_state()) or (
+ attention_mask is not None and torch.all(attention_mask == 1)
+ ):
+ mamba_mask = None
+ return mamba_mask
+
+
+class NemotronHForCausalLM(ZambaForCausalLM):
+ _tied_weights_keys = {}
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ use_cache: bool | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ **kwargs,
+ ) -> tuple | CausalLMOutputWithPast:
+ outputs = self.model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ **kwargs,
+ )
+
+ hidden_states = outputs[0]
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
+ logits = self.lm_head(hidden_states[:, slice_indices, :]).float()
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
+
+ return CausalLMOutputWithPast(
+ loss=loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+__all__ = [
+ "NemotronHPreTrainedModel",
+ "NemotronHModel",
+ "NemotronHForCausalLM",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/nllb/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/nllb/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..998d0319b613f536e6ae56dd4b4cd7aba69a3c3e
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/nllb/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/nllb/__pycache__/tokenization_nllb.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/nllb/__pycache__/tokenization_nllb.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4424b184cc8ea21c4ad1398dd585db3953d5fc51
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/nllb/__pycache__/tokenization_nllb.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/nystromformer/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/nystromformer/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c32df6d8db909207e4867e119d2a7fca4a0bd907
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/nystromformer/__init__.py
@@ -0,0 +1,27 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_nystromformer import *
+ from .modeling_nystromformer import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/nystromformer/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/nystromformer/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..44aa6b63c0a7689565188df8d41590dca01a8370
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/nystromformer/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/nystromformer/__pycache__/configuration_nystromformer.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/nystromformer/__pycache__/configuration_nystromformer.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..19f824db594fda9ab58cea96cb838658d12dbc27
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/nystromformer/__pycache__/configuration_nystromformer.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/nystromformer/__pycache__/modeling_nystromformer.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/nystromformer/__pycache__/modeling_nystromformer.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..79aa48a6a13df07243bddf043e5b6c41604e9c4e
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/nystromformer/__pycache__/modeling_nystromformer.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/nystromformer/configuration_nystromformer.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/nystromformer/configuration_nystromformer.py
new file mode 100644
index 0000000000000000000000000000000000000000..64d625ffeb1ee69c3b54a6c04006a2fd3813fb86
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/nystromformer/configuration_nystromformer.py
@@ -0,0 +1,77 @@
+# Copyright 2022 UW-Madison and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Nystromformer model configuration"""
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring
+
+
+@auto_docstring(checkpoint="uw-madison/nystromformer-512")
+@strict
+class NystromformerConfig(PreTrainedConfig):
+ r"""
+ segment_means_seq_len (`int`, *optional*, defaults to 64):
+ Sequence length used in segment-means.
+ num_landmarks (`int`, *optional*, defaults to 64):
+ The number of landmark (or Nystrom) points to use in Nystrom approximation of the softmax self-attention
+ matrix.
+ conv_kernel_size (`int`, *optional*, defaults to 65):
+ The kernel size of depthwise convolution used in Nystrom approximation.
+ inv_coeff_init_option (`bool`, *optional*, defaults to `False`):
+ Whether or not to use exact coefficient computation for the initial values for the iterative method of
+ calculating the Moore-Penrose inverse of a matrix.
+
+ Example:
+
+ ```python
+ >>> from transformers import NystromformerModel, NystromformerConfig
+
+ >>> # Initializing a Nystromformer uw-madison/nystromformer-512 style configuration
+ >>> configuration = NystromformerConfig()
+
+ >>> # Initializing a model from the uw-madison/nystromformer-512 style configuration
+ >>> model = NystromformerModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "nystromformer"
+
+ vocab_size: int = 30000
+ hidden_size: int = 768
+ num_hidden_layers: int = 12
+ num_attention_heads: int = 12
+ intermediate_size: int = 3072
+ hidden_act: str = "gelu_new"
+ hidden_dropout_prob: float | int = 0.1
+ attention_probs_dropout_prob: float | int = 0.1
+ max_position_embeddings: int = 510
+ type_vocab_size: int = 2
+ segment_means_seq_len: int = 64
+ num_landmarks: int = 64
+ conv_kernel_size: int = 65
+ inv_coeff_init_option: bool = False
+ initializer_range: float = 0.02
+ layer_norm_eps: float = 1e-5
+ pad_token_id: int | None = 1
+ bos_token_id: int | None = 0
+ eos_token_id: int | list[int] | None = 2
+ add_cross_attention: bool = False
+ tie_word_embeddings: bool = True
+
+
+__all__ = ["NystromformerConfig"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/nystromformer/modeling_nystromformer.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/nystromformer/modeling_nystromformer.py
new file mode 100644
index 0000000000000000000000000000000000000000..fbd25214b37ac2c6177d6d994af2ce9ade37df55
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/nystromformer/modeling_nystromformer.py
@@ -0,0 +1,948 @@
+# Copyright 2022 UW-Madison The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch Nystromformer model."""
+
+import math
+
+import torch
+from torch import nn
+from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...masking_utils import create_bidirectional_mask
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import (
+ BaseModelOutputWithPastAndCrossAttentions,
+ MaskedLMOutput,
+ MultipleChoiceModelOutput,
+ QuestionAnsweringModelOutput,
+ SequenceClassifierOutput,
+ TokenClassifierOutput,
+)
+from ...modeling_utils import PreTrainedModel
+from ...pytorch_utils import apply_chunking_to_forward
+from ...utils import (
+ auto_docstring,
+ logging,
+)
+from .configuration_nystromformer import NystromformerConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+class NystromformerEmbeddings(nn.Module):
+ """Construct the embeddings from word, position and token_type embeddings."""
+
+ def __init__(self, config):
+ super().__init__()
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
+ self.position_embeddings = nn.Embedding(config.max_position_embeddings + 2, config.hidden_size)
+ self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
+
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
+ self.register_buffer(
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)) + 2, persistent=False
+ )
+ self.register_buffer(
+ "token_type_ids",
+ torch.zeros(self.position_ids.size(), dtype=torch.long, device=self.position_ids.device),
+ persistent=False,
+ )
+
+ def forward(self, input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None):
+ if input_ids is not None:
+ input_shape = input_ids.size()
+ else:
+ input_shape = inputs_embeds.size()[:-1]
+
+ seq_length = input_shape[1]
+
+ if position_ids is None:
+ position_ids = self.position_ids[:, :seq_length]
+
+ # Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
+ # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
+ # issue #5664
+ if token_type_ids is None:
+ if hasattr(self, "token_type_ids"):
+ buffered_token_type_ids = self.token_type_ids[:, :seq_length]
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
+ token_type_ids = buffered_token_type_ids_expanded
+ else:
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
+
+ if inputs_embeds is None:
+ inputs_embeds = self.word_embeddings(input_ids)
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
+ embeddings = inputs_embeds + token_type_embeddings
+
+ position_embeddings = self.position_embeddings(position_ids)
+ embeddings += position_embeddings
+
+ embeddings = self.LayerNorm(embeddings)
+ embeddings = self.dropout(embeddings)
+ return embeddings
+
+
+class NystromformerSelfAttention(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
+ raise ValueError(
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
+ f"heads ({config.num_attention_heads})"
+ )
+
+ self.num_attention_heads = config.num_attention_heads
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
+
+ self.num_landmarks = config.num_landmarks
+ self.seq_len = config.segment_means_seq_len
+ self.conv_kernel_size = config.conv_kernel_size
+
+ if config.inv_coeff_init_option:
+ self.init_option = config["inv_init_coeff_option"]
+ else:
+ self.init_option = "original"
+
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
+
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
+
+ if self.conv_kernel_size is not None:
+ self.conv = nn.Conv2d(
+ in_channels=self.num_attention_heads,
+ out_channels=self.num_attention_heads,
+ kernel_size=(self.conv_kernel_size, 1),
+ padding=(self.conv_kernel_size // 2, 0),
+ bias=False,
+ groups=self.num_attention_heads,
+ )
+
+ # Function to approximate Moore-Penrose inverse via the iterative method
+ def iterative_inv(self, mat, n_iter=6):
+ identity = torch.eye(mat.size(-1), device=mat.device)
+ key = mat
+
+ # The entries of key are positive and ||key||_{\infty} = 1 due to softmax
+ if self.init_option == "original":
+ # This original implementation is more conservative to compute coefficient of Z_0.
+ value = 1 / torch.max(torch.sum(key, dim=-2)) * key.transpose(-1, -2)
+ else:
+ # This is the exact coefficient computation, 1 / ||key||_1, of initialization of Z_0, leading to faster convergence.
+ value = 1 / torch.max(torch.sum(key, dim=-2), dim=-1).values[:, :, None, None] * key.transpose(-1, -2)
+
+ for _ in range(n_iter):
+ key_value = torch.matmul(key, value)
+ value = torch.matmul(
+ 0.25 * value,
+ 13 * identity
+ - torch.matmul(key_value, 15 * identity - torch.matmul(key_value, 7 * identity - key_value)),
+ )
+ return value
+
+ def forward(self, hidden_states, attention_mask=None, output_attentions=False):
+ input_shape = hidden_states.shape[:-1]
+ hidden_shape = (*input_shape, -1, self.attention_head_size)
+ query_layer = self.query(hidden_states).view(hidden_shape).transpose(1, 2)
+ key_layer = self.key(hidden_states).view(hidden_shape).transpose(1, 2)
+ value_layer = self.value(hidden_states).view(hidden_shape).transpose(1, 2)
+
+ query_layer = query_layer / math.sqrt(math.sqrt(self.attention_head_size))
+ key_layer = key_layer / math.sqrt(math.sqrt(self.attention_head_size))
+
+ if self.num_landmarks == self.seq_len:
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
+
+ if attention_mask is not None:
+ # Apply the attention mask is (precomputed for all layers in NystromformerModel forward() function)
+ attention_scores = attention_scores + attention_mask
+
+ attention_probs = nn.functional.softmax(attention_scores, dim=-1)
+ context_layer = torch.matmul(attention_probs, value_layer)
+
+ else:
+ q_landmarks = query_layer.reshape(
+ -1,
+ self.num_attention_heads,
+ self.num_landmarks,
+ self.seq_len // self.num_landmarks,
+ self.attention_head_size,
+ ).mean(dim=-2)
+ k_landmarks = key_layer.reshape(
+ -1,
+ self.num_attention_heads,
+ self.num_landmarks,
+ self.seq_len // self.num_landmarks,
+ self.attention_head_size,
+ ).mean(dim=-2)
+
+ kernel_1 = torch.nn.functional.softmax(torch.matmul(query_layer, k_landmarks.transpose(-1, -2)), dim=-1)
+ kernel_2 = torch.nn.functional.softmax(torch.matmul(q_landmarks, k_landmarks.transpose(-1, -2)), dim=-1)
+
+ attention_scores = torch.matmul(q_landmarks, key_layer.transpose(-1, -2))
+
+ if attention_mask is not None:
+ # Apply the attention mask is (precomputed for all layers in NystromformerModel forward() function)
+ attention_scores = attention_scores + attention_mask
+
+ kernel_3 = nn.functional.softmax(attention_scores, dim=-1)
+ attention_probs = torch.matmul(kernel_1, self.iterative_inv(kernel_2))
+ new_value_layer = torch.matmul(kernel_3, value_layer)
+ context_layer = torch.matmul(attention_probs, new_value_layer)
+
+ if self.conv_kernel_size is not None:
+ context_layer += self.conv(value_layer)
+
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
+ context_layer = context_layer.view(*new_context_layer_shape)
+
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
+
+ return outputs
+
+
+# Copied from transformers.models.bert.modeling_bert.BertSelfOutput
+class NystromformerSelfOutput(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
+ return hidden_states
+
+
+class NystromformerAttention(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.self = NystromformerSelfAttention(config)
+ self.output = NystromformerSelfOutput(config)
+
+ def forward(self, hidden_states, attention_mask=None, output_attentions=False):
+ self_outputs = self.self(hidden_states, attention_mask, output_attentions)
+ attention_output = self.output(self_outputs[0], hidden_states)
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
+ return outputs
+
+
+# Copied from transformers.models.bert.modeling_bert.BertIntermediate with Bert->Nystromformer
+class NystromformerIntermediate(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
+ if isinstance(config.hidden_act, str):
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
+ else:
+ self.intermediate_act_fn = config.hidden_act
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.intermediate_act_fn(hidden_states)
+ return hidden_states
+
+
+# Copied from transformers.models.bert.modeling_bert.BertOutput with Bert->Nystromformer
+class NystromformerOutput(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
+ return hidden_states
+
+
+class NystromformerLayer(GradientCheckpointingLayer):
+ def __init__(self, config):
+ super().__init__()
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
+ self.seq_len_dim = 1
+ self.attention = NystromformerAttention(config)
+ self.add_cross_attention = config.add_cross_attention
+ self.intermediate = NystromformerIntermediate(config)
+ self.output = NystromformerOutput(config)
+
+ def forward(self, hidden_states, attention_mask=None, output_attentions=False):
+ self_attention_outputs = self.attention(hidden_states, attention_mask, output_attentions=output_attentions)
+ attention_output = self_attention_outputs[0]
+
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
+
+ layer_output = apply_chunking_to_forward(
+ self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
+ )
+ outputs = (layer_output,) + outputs
+
+ return outputs
+
+ def feed_forward_chunk(self, attention_output):
+ intermediate_output = self.intermediate(attention_output)
+ layer_output = self.output(intermediate_output, attention_output)
+ return layer_output
+
+
+class NystromformerEncoder(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.layer = nn.ModuleList([NystromformerLayer(config) for _ in range(config.num_hidden_layers)])
+ self.gradient_checkpointing = False
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor | None = None,
+ output_attentions: bool = False,
+ output_hidden_states: bool = False,
+ return_dict: bool = True,
+ ):
+ all_hidden_states = () if output_hidden_states else None
+ all_self_attentions = () if output_attentions else None
+
+ for i, layer_module in enumerate(self.layer):
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ layer_outputs = layer_module(hidden_states, attention_mask, output_attentions)
+
+ hidden_states = layer_outputs[0]
+ if output_attentions:
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
+
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ if not return_dict:
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
+ return BaseModelOutputWithPastAndCrossAttentions(
+ last_hidden_state=hidden_states,
+ hidden_states=all_hidden_states,
+ attentions=all_self_attentions,
+ )
+
+
+# Copied from transformers.models.bert.modeling_bert.BertPredictionHeadTransform with Bert->Nystromformer
+class NystromformerPredictionHeadTransform(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ if isinstance(config.hidden_act, str):
+ self.transform_act_fn = ACT2FN[config.hidden_act]
+ else:
+ self.transform_act_fn = config.hidden_act
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.transform_act_fn(hidden_states)
+ hidden_states = self.LayerNorm(hidden_states)
+ return hidden_states
+
+
+# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->Nystromformer
+class NystromformerLMPredictionHead(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.transform = NystromformerPredictionHeadTransform(config)
+
+ # The output weights are the same as the input embeddings, but there is
+ # an output-only bias for each token.
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=True)
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
+
+ def forward(self, hidden_states):
+ hidden_states = self.transform(hidden_states)
+ hidden_states = self.decoder(hidden_states)
+ return hidden_states
+
+
+# Copied from transformers.models.bert.modeling_bert.BertOnlyMLMHead with Bert->Nystromformer
+class NystromformerOnlyMLMHead(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.predictions = NystromformerLMPredictionHead(config)
+
+ def forward(self, sequence_output: torch.Tensor) -> torch.Tensor:
+ prediction_scores = self.predictions(sequence_output)
+ return prediction_scores
+
+
+@auto_docstring
+class NystromformerPreTrainedModel(PreTrainedModel):
+ config: NystromformerConfig
+ base_model_prefix = "nystromformer"
+ supports_gradient_checkpointing = True
+
+ def _init_weights(self, module):
+ super()._init_weights(module)
+ if isinstance(module, NystromformerEmbeddings):
+ init.copy_(module.position_ids, torch.arange(module.position_ids.shape[-1]).expand((1, -1)) + 2)
+ init.zeros_(module.token_type_ids)
+
+
+@auto_docstring
+class NystromformerModel(NystromformerPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.config = config
+
+ self.embeddings = NystromformerEmbeddings(config)
+ self.encoder = NystromformerEncoder(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.embeddings.word_embeddings
+
+ def set_input_embeddings(self, value):
+ self.embeddings.word_embeddings = value
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple[torch.Tensor] | BaseModelOutputWithPastAndCrossAttentions:
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ if input_ids is not None and inputs_embeds is not None:
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
+ elif input_ids is not None:
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
+ input_shape = input_ids.size()
+ elif inputs_embeds is not None:
+ input_shape = inputs_embeds.size()[:-1]
+ else:
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
+
+ batch_size, seq_length = input_shape
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
+
+ if attention_mask is None:
+ attention_mask = torch.ones(((batch_size, seq_length)), device=device)
+
+ if token_type_ids is None:
+ if hasattr(self.embeddings, "token_type_ids"):
+ buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)
+ token_type_ids = buffered_token_type_ids_expanded
+ else:
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
+
+ embedding_output = self.embeddings(
+ input_ids=input_ids,
+ position_ids=position_ids,
+ token_type_ids=token_type_ids,
+ inputs_embeds=inputs_embeds,
+ )
+
+ attention_mask = create_bidirectional_mask(
+ config=self.config,
+ inputs_embeds=embedding_output,
+ attention_mask=attention_mask,
+ )
+
+ encoder_outputs = self.encoder(
+ embedding_output,
+ attention_mask=attention_mask,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+ sequence_output = encoder_outputs[0]
+
+ if not return_dict:
+ return (sequence_output,) + encoder_outputs[1:]
+
+ return BaseModelOutputWithPastAndCrossAttentions(
+ last_hidden_state=sequence_output,
+ hidden_states=encoder_outputs.hidden_states,
+ attentions=encoder_outputs.attentions,
+ cross_attentions=encoder_outputs.cross_attentions,
+ )
+
+
+@auto_docstring
+class NystromformerForMaskedLM(NystromformerPreTrainedModel):
+ _tied_weights_keys = {
+ "cls.predictions.decoder.weight": "nystromformer.embeddings.word_embeddings.weight",
+ "cls.predictions.decoder.bias": "cls.predictions.bias",
+ }
+
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.nystromformer = NystromformerModel(config)
+ self.cls = NystromformerOnlyMLMHead(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_output_embeddings(self):
+ return self.cls.predictions.decoder
+
+ def set_output_embeddings(self, new_embeddings):
+ self.cls.predictions.decoder = new_embeddings
+ self.cls.predictions.bias = new_embeddings.bias
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple[torch.Tensor] | MaskedLMOutput:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
+ """
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ outputs = self.nystromformer(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ sequence_output = outputs[0]
+ prediction_scores = self.cls(sequence_output)
+
+ masked_lm_loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss() # -100 index = padding token
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
+
+ if not return_dict:
+ output = (prediction_scores,) + outputs[1:]
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
+
+ return MaskedLMOutput(
+ loss=masked_lm_loss,
+ logits=prediction_scores,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+class NystromformerClassificationHead(nn.Module):
+ """Head for sentence-level classification tasks."""
+
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+ self.out_proj = nn.Linear(config.hidden_size, config.num_labels)
+
+ self.config = config
+
+ def forward(self, features, **kwargs):
+ x = features[:, 0, :] # take token (equiv. to [CLS])
+ x = self.dropout(x)
+ x = self.dense(x)
+ x = ACT2FN[self.config.hidden_act](x)
+ x = self.dropout(x)
+ x = self.out_proj(x)
+ return x
+
+
+@auto_docstring(
+ custom_intro="""
+ Nyströmformer Model transformer with a sequence classification/regression head on top (a linear layer on top of the
+ pooled output) e.g. for GLUE tasks.
+ """
+)
+class NystromformerForSequenceClassification(NystromformerPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+ self.nystromformer = NystromformerModel(config)
+ self.classifier = NystromformerClassificationHead(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple[torch.Tensor] | SequenceClassifierOutput:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ outputs = self.nystromformer(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ sequence_output = outputs[0]
+ logits = self.classifier(sequence_output)
+
+ loss = None
+ if labels is not None:
+ if self.config.problem_type is None:
+ if self.num_labels == 1:
+ self.config.problem_type = "regression"
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
+ self.config.problem_type = "single_label_classification"
+ else:
+ self.config.problem_type = "multi_label_classification"
+
+ if self.config.problem_type == "regression":
+ loss_fct = MSELoss()
+ if self.num_labels == 1:
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
+ else:
+ loss = loss_fct(logits, labels)
+ elif self.config.problem_type == "single_label_classification":
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+ elif self.config.problem_type == "multi_label_classification":
+ loss_fct = BCEWithLogitsLoss()
+ loss = loss_fct(logits, labels)
+ if not return_dict:
+ output = (logits,) + outputs[1:]
+ return ((loss,) + output) if loss is not None else output
+
+ return SequenceClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+class NystromformerForMultipleChoice(NystromformerPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.nystromformer = NystromformerModel(config)
+ self.pre_classifier = nn.Linear(config.hidden_size, config.hidden_size)
+ self.classifier = nn.Linear(config.hidden_size, 1)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple[torch.Tensor] | MultipleChoiceModelOutput:
+ r"""
+ input_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input-ids)
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
+ 1]`:
+
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ position_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
+ config.max_position_embeddings - 1]`.
+
+ [What are position IDs?](../glossary#position-ids)
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_choices, sequence_length, hidden_size)`, *optional*):
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
+ is useful if you want more control over how to convert *input_ids* indices into associated vectors than the
+ model's internal embedding lookup matrix.
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
+ num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
+ `input_ids` above)
+ """
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+ num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
+
+ input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
+ attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
+ token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
+ position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
+ inputs_embeds = (
+ inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
+ if inputs_embeds is not None
+ else None
+ )
+
+ outputs = self.nystromformer(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ hidden_state = outputs[0] # (bs * num_choices, seq_len, dim)
+ pooled_output = hidden_state[:, 0] # (bs * num_choices, dim)
+ pooled_output = self.pre_classifier(pooled_output) # (bs * num_choices, dim)
+ pooled_output = nn.ReLU()(pooled_output) # (bs * num_choices, dim)
+ logits = self.classifier(pooled_output)
+
+ reshaped_logits = logits.view(-1, num_choices)
+
+ loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(reshaped_logits, labels)
+
+ if not return_dict:
+ output = (reshaped_logits,) + outputs[1:]
+ return ((loss,) + output) if loss is not None else output
+
+ return MultipleChoiceModelOutput(
+ loss=loss,
+ logits=reshaped_logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+class NystromformerForTokenClassification(NystromformerPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+
+ self.nystromformer = NystromformerModel(config)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple[torch.Tensor] | TokenClassifierOutput:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
+ """
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ outputs = self.nystromformer(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ sequence_output = outputs[0]
+
+ sequence_output = self.dropout(sequence_output)
+ logits = self.classifier(sequence_output)
+
+ loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+
+ if not return_dict:
+ output = (logits,) + outputs[1:]
+ return ((loss,) + output) if loss is not None else output
+
+ return TokenClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+class NystromformerForQuestionAnswering(NystromformerPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ config.num_labels = 2
+ self.num_labels = config.num_labels
+
+ self.nystromformer = NystromformerModel(config)
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ start_positions: torch.LongTensor | None = None,
+ end_positions: torch.LongTensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple[torch.Tensor] | QuestionAnsweringModelOutput:
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ outputs = self.nystromformer(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ sequence_output = outputs[0]
+
+ logits = self.qa_outputs(sequence_output)
+ start_logits, end_logits = logits.split(1, dim=-1)
+ start_logits = start_logits.squeeze(-1)
+ end_logits = end_logits.squeeze(-1)
+
+ total_loss = None
+ if start_positions is not None and end_positions is not None:
+ # If we are on multi-GPU, split add a dimension
+ if len(start_positions.size()) > 1:
+ start_positions = start_positions.squeeze(-1)
+ if len(end_positions.size()) > 1:
+ end_positions = end_positions.squeeze(-1)
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
+ ignored_index = start_logits.size(1)
+ start_positions = start_positions.clamp(0, ignored_index)
+ end_positions = end_positions.clamp(0, ignored_index)
+
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
+ start_loss = loss_fct(start_logits, start_positions)
+ end_loss = loss_fct(end_logits, end_positions)
+ total_loss = (start_loss + end_loss) / 2
+
+ if not return_dict:
+ output = (start_logits, end_logits) + outputs[1:]
+ return ((total_loss,) + output) if total_loss is not None else output
+
+ return QuestionAnsweringModelOutput(
+ loss=total_loss,
+ start_logits=start_logits,
+ end_logits=end_logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+__all__ = [
+ "NystromformerForMaskedLM",
+ "NystromformerForMultipleChoice",
+ "NystromformerForQuestionAnswering",
+ "NystromformerForSequenceClassification",
+ "NystromformerForTokenClassification",
+ "NystromformerLayer",
+ "NystromformerModel",
+ "NystromformerPreTrainedModel",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/olmo/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/olmo/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..abb8bd316a0dae04586cfeee8ce6d16410a5082f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/olmo/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/olmo/__pycache__/configuration_olmo.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/olmo/__pycache__/configuration_olmo.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6df8ad76ffe52a4132ca6d2c6390f19abb8bf897
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/olmo/__pycache__/configuration_olmo.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/olmo/__pycache__/modeling_olmo.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/olmo/__pycache__/modeling_olmo.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..28c4b408c1a96c0979c49277f292943f6b257ca0
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/olmo/__pycache__/modeling_olmo.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/olmo/__pycache__/modular_olmo.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/olmo/__pycache__/modular_olmo.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..35e2b376c4748271b73238a0ca536f16520641ac
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/olmo/__pycache__/modular_olmo.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/olmo2/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/olmo2/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..88712344967f98e4bdf6d1427e3c3a2bc501b78d
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/olmo2/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/olmo2/__pycache__/configuration_olmo2.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/olmo2/__pycache__/configuration_olmo2.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..579f7aa9f0d406ff018079ae44cfc16d93159625
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/olmo2/__pycache__/configuration_olmo2.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/olmo2/__pycache__/modeling_olmo2.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/olmo2/__pycache__/modeling_olmo2.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8d6516a0c566af61e3df5b25e2bd62eaa65f4ba1
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/olmo2/__pycache__/modeling_olmo2.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/olmo2/__pycache__/modular_olmo2.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/olmo2/__pycache__/modular_olmo2.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2995d3ce0145bf234d20f37cf220f6069b239354
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/olmo2/__pycache__/modular_olmo2.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/olmo_hybrid/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/olmo_hybrid/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fe627f7aec7cc65b41a620653e6d0428d9321aea
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/olmo_hybrid/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/olmo_hybrid/__pycache__/configuration_olmo_hybrid.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/olmo_hybrid/__pycache__/configuration_olmo_hybrid.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8c64ecd31b313b07b90365705a94b7cff90f8a47
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/olmo_hybrid/__pycache__/configuration_olmo_hybrid.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/olmo_hybrid/__pycache__/modeling_olmo_hybrid.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/olmo_hybrid/__pycache__/modeling_olmo_hybrid.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8a0df810220a455f350e17ef53d1746f6f7ceb65
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/olmo_hybrid/__pycache__/modeling_olmo_hybrid.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/olmo_hybrid/__pycache__/modular_olmo_hybrid.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/olmo_hybrid/__pycache__/modular_olmo_hybrid.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..22303b31a12cd1caca34105099a4f2c9b8c888c8
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/olmo_hybrid/__pycache__/modular_olmo_hybrid.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/omdet_turbo/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/omdet_turbo/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..a8b49479b2599b9cc689f9ef281b61fd32ae01c9
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/omdet_turbo/__init__.py
@@ -0,0 +1,28 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_omdet_turbo import *
+ from .modeling_omdet_turbo import *
+ from .processing_omdet_turbo import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/omdet_turbo/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/omdet_turbo/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8335fdd6f0fa10e1f4ce284a44c6d6410e8e227d
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/omdet_turbo/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/omdet_turbo/__pycache__/configuration_omdet_turbo.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/omdet_turbo/__pycache__/configuration_omdet_turbo.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..284c31244b6a9d7f2ee95556e99e5efe35ce932a
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/omdet_turbo/__pycache__/configuration_omdet_turbo.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/omdet_turbo/__pycache__/modeling_omdet_turbo.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/omdet_turbo/__pycache__/modeling_omdet_turbo.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..66928c661f7d06165662bc89f9b5113fc3a90e99
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/omdet_turbo/__pycache__/modeling_omdet_turbo.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/omdet_turbo/__pycache__/processing_omdet_turbo.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/omdet_turbo/__pycache__/processing_omdet_turbo.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..00ef44208211b1c6bc20ce158ad06f2e6a761602
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/omdet_turbo/__pycache__/processing_omdet_turbo.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/omdet_turbo/configuration_omdet_turbo.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/omdet_turbo/configuration_omdet_turbo.py
new file mode 100644
index 0000000000000000000000000000000000000000..7be495e0770b752bdc18428041d96d451fc55413
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/omdet_turbo/configuration_omdet_turbo.py
@@ -0,0 +1,189 @@
+# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""OmDet-Turbo model configuration"""
+
+from typing import Literal
+
+from huggingface_hub.dataclasses import strict
+
+from ...backbone_utils import consolidate_backbone_kwargs_to_config
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring, logging
+from ..auto import CONFIG_MAPPING, AutoConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+@auto_docstring(checkpoint="omlab/omdet-turbo-swin-tiny-hf")
+@strict
+class OmDetTurboConfig(PreTrainedConfig):
+ r"""
+ apply_layernorm_after_vision_backbone (`bool`, *optional*, defaults to `True`):
+ Whether to apply layer normalization on the feature maps of the vision backbone output.
+ disable_custom_kernels (`bool`, *optional*, defaults to `False`):
+ Whether to disable custom kernels.
+ text_projection_in_dim (`int`, *optional*, defaults to 512):
+ The input dimension for the text projection.
+ text_projection_out_dim (`int`, *optional*, defaults to 512):
+ The output dimension for the text projection.
+ task_encoder_hidden_dim (`int`, *optional*, defaults to 1024):
+ The feedforward dimension for the task encoder.
+ class_embed_dim (`int`, *optional*, defaults to 512):
+ The dimension of the classes embeddings.
+ class_distance_type (`str`, *optional*, defaults to `"cosine"`):
+ The type of distance to compare predicted classes to projected classes embeddings.
+ Can be `"cosine"` or `"dot"`.
+ num_queries (`int`, *optional*, defaults to 900):
+ The number of queries.
+ csp_activation (`str`, *optional*, defaults to `"silu"`):
+ The activation function of the Cross Stage Partial (CSP) networks of the encoder.
+ conv_norm_activation (`str`, *optional*, defaults to `"gelu"`):
+ The activation function of the ConvNormLayer layers of the encoder.
+ encoder_feedforward_activation (`str`, *optional*, defaults to `"relu"`):
+ The activation function for the feedforward network of the encoder.
+ encoder_feedforward_dropout (`float`, *optional*, defaults to 0.0):
+ The dropout rate following the activation of the encoder feedforward network.
+ hidden_expansion (`int`, *optional*, defaults to 1):
+ The hidden expansion of the CSP networks in the encoder.
+ vision_features_channels (`tuple(int)`, *optional*, defaults to `[256, 256, 256]`):
+ The projected vision features channels used as inputs for the decoder.
+ encoder_in_channels (`List(int)`, *optional*, defaults to `[192, 384, 768]`):
+ The input channels for the encoder.
+ encoder_projection_indices (`List(int)`, *optional*, defaults to `[2]`):
+ The indices of the input features projected by each layers.
+ encoder_dim_feedforward (`int`, *optional*, defaults to 2048):
+ The feedforward dimension for the encoder.
+ positional_encoding_temperature (`int`, *optional*, defaults to 10000):
+ The positional encoding temperature in the encoder.
+ num_feature_levels (`int`, *optional*, defaults to 3):
+ The number of feature levels for the multi-scale deformable attention module of the decoder.
+ decoder_activation (`str`, *optional*, defaults to `"relu"`):
+ The activation function for the decoder.
+ decoder_dim_feedforward (`int`, *optional*, defaults to 2048):
+ The feedforward dimension for the decoder.
+ decoder_num_points (`int`, *optional*, defaults to 4):
+ The number of points sampled in the decoder multi-scale deformable attention module.
+ decoder_dropout (`float`, *optional*, defaults to 0.0):
+ The dropout rate for the decoder.
+ eval_size (`tuple[int, int]`, *optional*):
+ Height and width used to computes the effective height and width of the position embeddings after taking
+ into account the stride (see RTDetr).
+ learn_initial_query (`bool`, *optional*, defaults to `False`):
+ Whether to learn the initial query.
+ cache_size (`int`, *optional*, defaults to 100):
+ The cache size for the classes and prompts caches.
+
+ Examples:
+
+ ```python
+ >>> from transformers import OmDetTurboConfig, OmDetTurboForObjectDetection
+
+ >>> # Initializing a OmDet-Turbo omlab/omdet-turbo-swin-tiny-hf style configuration
+ >>> configuration = OmDetTurboConfig()
+
+ >>> # Initializing a model (with random weights) from the omlab/omdet-turbo-swin-tiny-hf style configuration
+ >>> model = OmDetTurboForObjectDetection(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "omdet-turbo"
+ sub_configs = {"backbone_config": AutoConfig, "text_config": AutoConfig}
+ attribute_map = {
+ "encoder_hidden_dim": "d_model",
+ "num_attention_heads": "encoder_attention_heads",
+ }
+
+ text_config: dict | PreTrainedConfig | None = None
+ backbone_config: dict | PreTrainedConfig | None = None
+ apply_layernorm_after_vision_backbone: bool = True
+ image_size: int | list[int] | tuple[int, int] = 640
+ disable_custom_kernels: bool = False
+ layer_norm_eps: float = 1e-5
+ batch_norm_eps: float = 1e-5
+ init_std: float = 0.02
+ text_projection_in_dim: int = 512
+ text_projection_out_dim: int = 512
+ task_encoder_hidden_dim: int = 1024
+ class_embed_dim: int = 512
+ class_distance_type: Literal["cosine", "dot"] = "cosine"
+ num_queries: int = 900
+ csp_activation: str = "silu"
+ conv_norm_activation: str = "gelu"
+ encoder_feedforward_activation: str = "relu"
+ encoder_feedforward_dropout: float | int = 0.0
+ encoder_dropout: float | int = 0.0
+ hidden_expansion: int = 1
+ encoder_hidden_dim: int = 256
+ vision_features_channels: list[int] | tuple[int, ...] = (256, 256, 256)
+ encoder_in_channels: list[int] | tuple[int, ...] = (192, 384, 768)
+ encoder_projection_indices: list[int] | tuple[int, ...] = (2,)
+ encoder_attention_heads: int = 8
+ encoder_dim_feedforward: int = 2048
+ encoder_layers: int = 1
+ positional_encoding_temperature: int = 10000
+ num_feature_levels: int = 3
+ decoder_hidden_dim: int = 256
+ decoder_num_heads: int = 8
+ decoder_num_layers: int = 6
+ decoder_activation: str = "relu"
+ decoder_dim_feedforward: int = 2048
+ decoder_num_points: int = 4
+ decoder_dropout: float | int = 0.0
+ eval_size: int | None = None
+ learn_initial_query: bool = False
+ cache_size: int = 100
+ is_encoder_decoder: bool = True
+
+ def __post_init__(self, **kwargs):
+ # Init timm backbone with hardcoded values for BC
+ timm_default_kwargs = {
+ "out_indices": [1, 2, 3],
+ "img_size": self.image_size,
+ "always_partition": True,
+ }
+ self.backbone_config, kwargs = consolidate_backbone_kwargs_to_config(
+ backbone_config=self.backbone_config,
+ default_backbone="swin_tiny_patch4_window7_224",
+ default_config_type="swin",
+ default_config_kwargs={"image_size": self.image_size, "out_indices": [2, 3, 4]},
+ timm_default_kwargs=timm_default_kwargs,
+ **kwargs,
+ )
+
+ # Extract timm.create_model kwargs; TimmBackbone doesn't forward arbitrary config attrs to timm
+ self.timm_kwargs = {}
+ if getattr(self.backbone_config, "model_type", None) == "timm_backbone":
+ for attr in ("img_size", "always_partition"):
+ if hasattr(self.backbone_config, attr):
+ self.timm_kwargs[attr] = getattr(self.backbone_config, attr)
+
+ if self.text_config is None:
+ logger.info("`text_config` is `None`. Initializing the config with the default `clip_text_model`")
+ self.text_config = CONFIG_MAPPING["clip_text_model"]()
+ elif isinstance(self.text_config, dict):
+ text_model_type = self.text_config.get("model_type")
+ self.text_config = CONFIG_MAPPING[text_model_type](**self.text_config)
+
+ super().__post_init__(**kwargs)
+
+ def to_dict(self):
+ output = super().to_dict()
+ output.pop("timm_kwargs", None)
+ return output
+
+
+__all__ = ["OmDetTurboConfig"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/omdet_turbo/modeling_omdet_turbo.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/omdet_turbo/modeling_omdet_turbo.py
new file mode 100644
index 0000000000000000000000000000000000000000..a00c0ab17c773f49ea14ce35a910f9aa2230971e
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/omdet_turbo/modeling_omdet_turbo.py
@@ -0,0 +1,1657 @@
+# Copyright 2024 Om Research Lab and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch OmDet-Turbo model."""
+
+import math
+import warnings
+from collections import OrderedDict
+from dataclasses import dataclass
+from functools import lru_cache
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from torch import Tensor
+
+from ... import initialization as init
+from ...activations import ACT2CLS, ACT2FN
+from ...integrations import use_kernel_forward_from_hub
+from ...masking_utils import create_bidirectional_mask
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_utils import PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import (
+ ModelOutput,
+ TransformersKwargs,
+ auto_docstring,
+ logging,
+ torch_compilable_check,
+)
+from ..auto import AutoBackbone, AutoModel
+from .configuration_omdet_turbo import OmDetTurboConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+@auto_docstring(
+ custom_intro="""
+ Base class for outputs of the OmDetTurboHybridEncoder.
+ """
+)
+@dataclass
+class OmDetTurboEncoderOutput(ModelOutput):
+ r"""
+ last_hidden_state (`torch.FloatTensor`):
+ Last hidden states of the encoder.
+ extracted_states (`tuple[torch.FloatTensor]`):
+ The extracted states from the Feature Pyramid Network (FPN) and Path Aggregation Network (PAN) of the encoder.
+ """
+
+ last_hidden_state: torch.FloatTensor | None = None
+ hidden_states: tuple[torch.FloatTensor] | None = None
+ attentions: tuple[torch.FloatTensor] | None = None
+ extracted_states: tuple[torch.FloatTensor] | None = None
+
+
+@auto_docstring(
+ custom_intro="""
+ Base class for outputs of the OmDetTurboDecoder.
+ """
+)
+@dataclass
+class OmDetTurboDecoderOutput(ModelOutput):
+ r"""
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
+ Sequence of hidden-states at the output of the last layer of the decoder.
+ decoder_coords (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)`):
+ The predicted coordinates of the objects.
+ decoder_classes (`torch.FloatTensor` of shape `(batch_size, num_queries, num_classes)`):
+ The predicted classes of the objects.
+ encoder_coord_logits (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)`):
+ The predicted coordinates of the objects from the encoder.
+ encoder_class_logits (`tuple[torch.FloatTensor]` of shape `(batch_size, num_queries, num_classes)`):
+ The predicted class of the objects from the encoder.
+ init_reference_points (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)`):
+ The initial reference points.
+ intermediate_reference_points (`tuple[tuple[torch.FloatTensor]]`):
+ The intermediate reference points.
+ """
+
+ last_hidden_state: torch.FloatTensor | None = None
+ hidden_states: tuple[torch.FloatTensor] | None = None
+ attentions: tuple[tuple[torch.FloatTensor]] | None = None
+ decoder_coords: torch.FloatTensor | None = None
+ decoder_classes: torch.FloatTensor | None = None
+ encoder_coord_logits: torch.FloatTensor | None = None
+ encoder_class_logits: tuple[torch.FloatTensor] | None = None
+ init_reference_points: torch.FloatTensor | None = None
+ intermediate_reference_points: tuple[tuple[torch.FloatTensor]] = None
+
+
+@auto_docstring(
+ custom_intro="""
+ Output type of [`OmDetTurboObjectDetectionOutput`].
+ """
+)
+@dataclass
+class OmDetTurboObjectDetectionOutput(ModelOutput):
+ r"""
+ loss (`torch.FloatTensor`):
+ The loss value.
+ decoder_coord_logits (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)`):
+ The predicted coordinates logits of the objects.
+ decoder_class_logits (`torch.FloatTensor` of shape `(batch_size, num_queries, num_classes)`):
+ The predicted class of the objects.
+ init_reference_points (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)`):
+ The initial reference points.
+ intermediate_reference_points (`tuple[tuple[torch.FloatTensor]]`):
+ The intermediate reference points.
+ encoder_coord_logits (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)`):
+ The predicted coordinates of the objects from the encoder.
+ encoder_class_logits (`tuple[torch.FloatTensor]`):
+ The predicted class of the objects from the encoder.
+ encoder_extracted_states (`torch.FloatTensor`):
+ The extracted states from the Feature Pyramid Network (FPN) and Path Aggregation Network (PAN) of the encoder.
+ decoder_hidden_states (`tuple[torch.FloatTensor]`, *optional*):
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of shape
+ `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer
+ plus the initial embedding outputs.
+ decoder_attentions (`tuple[tuple[torch.FloatTensor]]`, *optional*):
+ Tuple of tuples of `torch.FloatTensor` (one for attention for each layer) of shape `(batch_size, num_heads,
+ sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the
+ weighted average in the self-attention, cross-attention and multi-scale deformable attention heads.
+ encoder_hidden_states (`tuple[torch.FloatTensor]`, *optional*):
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of shape
+ `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer
+ plus the initial embedding outputs.
+ encoder_attentions (`tuple[tuple[torch.FloatTensor]]`, *optional*):
+ Tuple of tuples of `torch.FloatTensor` (one for attention for each layer) of shape `(batch_size, num_heads,
+ sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the
+ weighted average in the self-attention, cross-attention and multi-scale deformable attention heads.
+ classes_structure (`torch.LongTensor`, *optional*):
+ The number of queried classes for each image.
+ """
+
+ loss: torch.FloatTensor | None = None
+ decoder_coord_logits: torch.FloatTensor | None = None
+ decoder_class_logits: torch.FloatTensor | None = None
+ init_reference_points: torch.FloatTensor | None = None
+ intermediate_reference_points: tuple[tuple[torch.FloatTensor]] | None = None
+ encoder_coord_logits: torch.FloatTensor | None = None
+ encoder_class_logits: tuple[torch.FloatTensor] | None = None
+ encoder_extracted_states: torch.FloatTensor | None = None
+ decoder_hidden_states: tuple[torch.FloatTensor] | None = None
+ decoder_attentions: tuple[tuple[torch.FloatTensor]] | None = None
+ encoder_hidden_states: tuple[torch.FloatTensor] | None = None
+ encoder_attentions: tuple[tuple[torch.FloatTensor]] | None = None
+ classes_structure: torch.LongTensor | None = None
+
+
+@use_kernel_forward_from_hub("MultiScaleDeformableAttention")
+# Copied from transformers.models.deformable_detr.modeling_deformable_detr.MultiScaleDeformableAttention
+class MultiScaleDeformableAttention(nn.Module):
+ def forward(
+ self,
+ value: Tensor,
+ value_spatial_shapes: Tensor,
+ value_spatial_shapes_list: list[tuple],
+ level_start_index: Tensor,
+ sampling_locations: Tensor,
+ attention_weights: Tensor,
+ im2col_step: int,
+ ):
+ batch_size, _, num_heads, hidden_dim = value.shape
+ _, num_queries, num_heads, num_levels, num_points, _ = sampling_locations.shape
+ value_list = value.split([height * width for height, width in value_spatial_shapes_list], dim=1)
+ sampling_grids = 2 * sampling_locations - 1
+ sampling_value_list = []
+ for level_id, (height, width) in enumerate(value_spatial_shapes_list):
+ # batch_size, height*width, num_heads, hidden_dim
+ # -> batch_size, height*width, num_heads*hidden_dim
+ # -> batch_size, num_heads*hidden_dim, height*width
+ # -> batch_size*num_heads, hidden_dim, height, width
+ value_l_ = (
+ value_list[level_id]
+ .flatten(2)
+ .transpose(1, 2)
+ .reshape(batch_size * num_heads, hidden_dim, height, width)
+ )
+ # batch_size, num_queries, num_heads, num_points, 2
+ # -> batch_size, num_heads, num_queries, num_points, 2
+ # -> batch_size*num_heads, num_queries, num_points, 2
+ sampling_grid_l_ = sampling_grids[:, :, :, level_id].transpose(1, 2).flatten(0, 1)
+ # batch_size*num_heads, hidden_dim, num_queries, num_points
+ sampling_value_l_ = nn.functional.grid_sample(
+ value_l_,
+ sampling_grid_l_,
+ mode="bilinear",
+ padding_mode="zeros",
+ align_corners=False,
+ )
+ sampling_value_list.append(sampling_value_l_)
+ # (batch_size, num_queries, num_heads, num_levels, num_points)
+ # -> (batch_size, num_heads, num_queries, num_levels, num_points)
+ # -> (batch_size, num_heads, 1, num_queries, num_levels*num_points)
+ attention_weights = attention_weights.transpose(1, 2).reshape(
+ batch_size * num_heads, 1, num_queries, num_levels * num_points
+ )
+ output = (
+ (torch.stack(sampling_value_list, dim=-2).flatten(-2) * attention_weights)
+ .sum(-1)
+ .view(batch_size, num_heads * hidden_dim, num_queries)
+ )
+ return output.transpose(1, 2).contiguous()
+
+
+class OmDetTurboLRUCache:
+ def __init__(self, capacity: int):
+ self.cache = OrderedDict()
+ self.capacity = capacity
+ self.current_load = 0
+
+ def has(self, key) -> bool:
+ return key in self.cache
+
+ def get(self, key):
+ """
+ Get the value of the key if the key exists in the cache, otherwise return None.
+ Move the key to the end of the cache to show that it was recently used.
+ """
+ if key not in self.cache:
+ return None
+ self.cache.move_to_end(key)
+ return self.cache[key]
+
+ def put(self, key, value) -> None:
+ """
+ Add the key-value pair to the cache.
+ Move the key to the end of the cache to show that it was recently used.
+ If the cache is full, remove the first key (least recently used).
+ """
+ if key not in self.cache:
+ self.current_load += 1
+ if self.current_load > self.capacity:
+ self.cache.popitem(last=False)
+ self.current_load -= 1
+
+ self.cache[key] = value
+ self.cache.move_to_end(key)
+
+
+class OmDetTurboLanguageBackbone(nn.Module):
+ def __init__(self, config: OmDetTurboConfig):
+ super().__init__()
+ self.model = AutoModel.from_config(config.text_config)
+ self.text_projection = nn.Parameter(torch.zeros(config.text_projection_in_dim, config.text_projection_out_dim))
+
+ def forward(self, hidden_states, mask=None, encode_type="task"):
+ text_outputs = self.model(hidden_states)
+ pooled_output = text_outputs[0]
+ if encode_type == "task":
+ if mask is None:
+ raise ValueError("mask is required for task encoding")
+ max_len = (mask != 0).sum(1).max().item()
+ truncated_mask = mask[:, :max_len]
+ truncated_output = pooled_output[:, :max_len, :]
+ return truncated_output.transpose(0, 1), truncated_mask
+ elif encode_type == "class":
+ max_pooled_output = pooled_output[torch.arange(pooled_output.shape[0]), hidden_states.argmax(dim=-1)]
+ projected_output = max_pooled_output @ self.text_projection
+ return projected_output
+ else:
+ raise ValueError(f"encode_type {encode_type} is not supported")
+
+
+class OmDetTurboVisionBackbone(nn.Module):
+ def __init__(self, config: OmDetTurboConfig):
+ super().__init__()
+ self.apply_layernorm_after_vision_backbone = config.apply_layernorm_after_vision_backbone
+ self.vision_backbone = AutoBackbone.from_config(config.backbone_config, **getattr(config, "timm_kwargs", {}))
+ self.layer_norms = nn.ModuleList(
+ [nn.LayerNorm(in_channel_dim, eps=config.layer_norm_eps) for in_channel_dim in config.encoder_in_channels]
+ )
+
+ def forward(self, pixel_values):
+ outputs = self.vision_backbone(pixel_values).feature_maps
+ if self.apply_layernorm_after_vision_backbone:
+ outputs = [
+ layer_norm(output).permute(0, 3, 1, 2).contiguous()
+ for layer_norm, output in zip(self.layer_norms, outputs)
+ ]
+
+ return outputs
+
+
+# Copied from transformers.models.deformable_detr.modeling_deformable_detr.DeformableDetrMultiscaleDeformableAttention with DeformableDetr->OmDetTurbo, Deformable DETR->OmDet-Turbo
+class OmDetTurboMultiscaleDeformableAttention(nn.Module):
+ """
+ Multiscale deformable attention as proposed in Deformable DETR.
+ """
+
+ def __init__(self, config: OmDetTurboConfig, num_heads: int, n_points: int):
+ super().__init__()
+
+ self.attn = MultiScaleDeformableAttention()
+
+ if config.d_model % num_heads != 0:
+ raise ValueError(
+ f"embed_dim (d_model) must be divisible by num_heads, but got {config.d_model} and {num_heads}"
+ )
+ dim_per_head = config.d_model // num_heads
+ # check if dim_per_head is power of 2
+ if not ((dim_per_head & (dim_per_head - 1) == 0) and dim_per_head != 0):
+ warnings.warn(
+ "You'd better set embed_dim (d_model) in OmDetTurboMultiscaleDeformableAttention to make the"
+ " dimension of each attention head a power of 2 which is more efficient in the authors' CUDA"
+ " implementation."
+ )
+
+ self.im2col_step = 64
+
+ self.d_model = config.d_model
+ self.n_levels = config.num_feature_levels
+ self.n_heads = num_heads
+ self.n_points = n_points
+
+ self.sampling_offsets = nn.Linear(config.d_model, num_heads * self.n_levels * n_points * 2)
+ self.attention_weights = nn.Linear(config.d_model, num_heads * self.n_levels * n_points)
+ self.value_proj = nn.Linear(config.d_model, config.d_model)
+ self.output_proj = nn.Linear(config.d_model, config.d_model)
+
+ self.disable_custom_kernels = config.disable_custom_kernels
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor | None = None,
+ encoder_hidden_states=None,
+ encoder_attention_mask=None,
+ position_embeddings: torch.Tensor | None = None,
+ reference_points=None,
+ spatial_shapes=None,
+ spatial_shapes_list=None,
+ level_start_index=None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor, torch.Tensor]:
+ # add position embeddings to the hidden states before projecting to queries and keys
+ if position_embeddings is not None:
+ hidden_states = hidden_states + position_embeddings
+
+ batch_size, num_queries, _ = hidden_states.shape
+ batch_size, sequence_length, _ = encoder_hidden_states.shape
+ # Ignore copy
+ total_elements = sum(shape[0] * shape[1] for shape in spatial_shapes_list)
+ torch_compilable_check(
+ total_elements == sequence_length,
+ "Make sure to align the spatial shapes with the sequence length of the encoder hidden states",
+ )
+
+ value = self.value_proj(encoder_hidden_states)
+ if attention_mask is not None:
+ # we invert the attention_mask
+ value = value.masked_fill(~attention_mask[..., None], float(0))
+ value = value.view(batch_size, sequence_length, self.n_heads, self.d_model // self.n_heads)
+ sampling_offsets = self.sampling_offsets(hidden_states).view(
+ batch_size, num_queries, self.n_heads, self.n_levels, self.n_points, 2
+ )
+ attention_weights = self.attention_weights(hidden_states).view(
+ batch_size, num_queries, self.n_heads, self.n_levels * self.n_points
+ )
+ attention_weights = F.softmax(attention_weights, -1).view(
+ batch_size, num_queries, self.n_heads, self.n_levels, self.n_points
+ )
+ # batch_size, num_queries, n_heads, n_levels, n_points, 2
+ num_coordinates = reference_points.shape[-1]
+ if num_coordinates == 2:
+ offset_normalizer = torch.stack([spatial_shapes[..., 1], spatial_shapes[..., 0]], -1)
+ sampling_locations = (
+ reference_points[:, :, None, :, None, :]
+ + sampling_offsets / offset_normalizer[None, None, None, :, None, :]
+ )
+ elif num_coordinates == 4:
+ sampling_locations = (
+ reference_points[:, :, None, :, None, :2]
+ + sampling_offsets / self.n_points * reference_points[:, :, None, :, None, 2:] * 0.5
+ )
+ else:
+ raise ValueError(f"Last dim of reference_points must be 2 or 4, but got {reference_points.shape[-1]}")
+
+ output = self.attn(
+ value,
+ spatial_shapes,
+ spatial_shapes_list,
+ level_start_index,
+ sampling_locations,
+ attention_weights,
+ self.im2col_step,
+ )
+
+ output = self.output_proj(output)
+
+ return output, attention_weights
+
+
+# Copied from transformers.models.rt_detr.modeling_rt_detr.RTDetrConvNormLayer with RTDetr->OmDetTurbo
+class OmDetTurboConvNormLayer(nn.Module):
+ def __init__(self, config, in_channels, out_channels, kernel_size, stride, padding=None, activation=None):
+ super().__init__()
+ self.conv = nn.Conv2d(
+ in_channels,
+ out_channels,
+ kernel_size,
+ stride,
+ padding=(kernel_size - 1) // 2 if padding is None else padding,
+ bias=False,
+ )
+ self.norm = nn.BatchNorm2d(out_channels, config.batch_norm_eps)
+ self.activation = nn.Identity() if activation is None else ACT2CLS[activation]()
+
+ def forward(self, hidden_state):
+ hidden_state = self.conv(hidden_state)
+ hidden_state = self.norm(hidden_state)
+ hidden_state = self.activation(hidden_state)
+ return hidden_state
+
+
+# Copied from transformers.models.rt_detr.modeling_rt_detr.RTDetrRepVggBlock with RTDetr->OmDetTurbo, activation_function->csp_activation
+class OmDetTurboRepVggBlock(nn.Module):
+ """
+ RepVGG architecture block introduced by the work "RepVGG: Making VGG-style ConvNets Great Again".
+ """
+
+ def __init__(self, config: OmDetTurboConfig):
+ super().__init__()
+
+ activation = config.csp_activation
+ hidden_channels = int(config.encoder_hidden_dim * config.hidden_expansion)
+ self.conv1 = OmDetTurboConvNormLayer(config, hidden_channels, hidden_channels, 3, 1, padding=1)
+ self.conv2 = OmDetTurboConvNormLayer(config, hidden_channels, hidden_channels, 1, 1, padding=0)
+ self.activation = nn.Identity() if activation is None else ACT2CLS[activation]()
+
+ def forward(self, x):
+ y = self.conv1(x) + self.conv2(x)
+ return self.activation(y)
+
+
+# Copied from transformers.models.rt_detr.modeling_rt_detr.RTDetrCSPRepLayer with RTDetr->OmDetTurbo, activation_function->csp_activation
+class OmDetTurboCSPRepLayer(nn.Module):
+ """
+ Cross Stage Partial (CSP) network layer with RepVGG blocks.
+ """
+
+ def __init__(self, config: OmDetTurboConfig):
+ super().__init__()
+
+ in_channels = config.encoder_hidden_dim * 2
+ out_channels = config.encoder_hidden_dim
+ num_blocks = 3
+ activation = config.csp_activation
+
+ hidden_channels = int(out_channels * config.hidden_expansion)
+ self.conv1 = OmDetTurboConvNormLayer(config, in_channels, hidden_channels, 1, 1, activation=activation)
+ self.conv2 = OmDetTurboConvNormLayer(config, in_channels, hidden_channels, 1, 1, activation=activation)
+ self.bottlenecks = nn.Sequential(*[OmDetTurboRepVggBlock(config) for _ in range(num_blocks)])
+ if hidden_channels != out_channels:
+ self.conv3 = OmDetTurboConvNormLayer(config, hidden_channels, out_channels, 1, 1, activation=activation)
+ else:
+ self.conv3 = nn.Identity()
+
+ def forward(self, hidden_state):
+ hidden_state_1 = self.conv1(hidden_state)
+ hidden_state_1 = self.bottlenecks(hidden_state_1)
+ hidden_state_2 = self.conv2(hidden_state)
+ return self.conv3(hidden_state_1 + hidden_state_2)
+
+
+class OmDetTurboMultiheadAttention(nn.Module):
+ """Equivalent implementation of nn.MultiheadAttention with `batch_first=True`."""
+
+ def __init__(self, config, hidden_size, num_attention_heads, dropout):
+ super().__init__()
+ if hidden_size % num_attention_heads != 0:
+ raise ValueError(
+ f"The hidden size ({hidden_size}) is not a multiple of the number of attention "
+ f"heads ({num_attention_heads})"
+ )
+ self.num_attention_heads = num_attention_heads
+ self.attention_head_size = int(hidden_size / num_attention_heads)
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
+ self.query = nn.Linear(hidden_size, self.all_head_size)
+ self.key = nn.Linear(hidden_size, self.all_head_size)
+ self.value = nn.Linear(hidden_size, self.all_head_size)
+ self.out_proj = nn.Linear(hidden_size, hidden_size)
+ self.dropout = nn.Dropout(dropout)
+
+ def forward(
+ self,
+ queries: torch.Tensor,
+ keys: torch.Tensor,
+ values: torch.Tensor,
+ attention_mask: torch.FloatTensor | None = None,
+ output_attentions: bool | None = False,
+ ) -> tuple[torch.Tensor]:
+ batch_size, seq_length, _ = queries.shape
+ query_layer = (
+ self.query(queries)
+ .view(batch_size, -1, self.num_attention_heads, self.attention_head_size)
+ .transpose(1, 2)
+ )
+ key_layer = (
+ self.key(keys).view(batch_size, -1, self.num_attention_heads, self.attention_head_size).transpose(1, 2)
+ )
+ value_layer = (
+ self.value(values).view(batch_size, -1, self.num_attention_heads, self.attention_head_size).transpose(1, 2)
+ )
+
+ # Take the dot product between "query" and "key" to get the raw attention scores.
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
+
+ if attention_mask is not None:
+ attention_scores = attention_scores + attention_mask
+
+ # Normalize the attention scores to probabilities.
+ attention_probs = nn.functional.softmax(attention_scores, dim=-1)
+
+ # This is actually dropping out entire tokens to attend to, which might
+ # seem a bit unusual, but is taken from the original Transformer paper.
+ attention_probs = self.dropout(attention_probs)
+
+ context_layer = torch.matmul(attention_probs, value_layer)
+
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
+ context_layer = context_layer.view(new_context_layer_shape)
+
+ context_layer = self.out_proj(context_layer)
+
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
+
+ return outputs
+
+
+class OmDetTurboEncoderLayer(nn.Module):
+ def __init__(self, config: OmDetTurboConfig):
+ super().__init__()
+ self.self_attn = OmDetTurboMultiheadAttention(
+ config,
+ hidden_size=config.encoder_hidden_dim,
+ num_attention_heads=config.num_attention_heads,
+ dropout=config.encoder_dropout,
+ )
+ self.self_attn_layer_norm = nn.LayerNorm(config.encoder_hidden_dim, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.encoder_dropout)
+ self.activation_fn = ACT2FN[config.encoder_feedforward_activation]
+ self.encoder_feedforward_dropout = nn.Dropout(config.encoder_feedforward_dropout)
+ self.fc1 = nn.Linear(config.encoder_hidden_dim, config.encoder_dim_feedforward)
+ self.fc2 = nn.Linear(config.encoder_dim_feedforward, config.encoder_hidden_dim)
+ self.final_layer_norm = nn.LayerNorm(config.encoder_hidden_dim, eps=config.layer_norm_eps)
+
+ @staticmethod
+ def with_pos_embed(tensor, pos_embed):
+ return tensor if pos_embed is None else tensor + pos_embed
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor,
+ position_embeddings: torch.Tensor | None = None,
+ output_attentions: bool = False,
+ ):
+ """
+ Args:
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
+ attention_mask (`torch.FloatTensor`): attention mask of size
+ `(batch, 1, target_len, source_len)` where padding elements are indicated by very large negative
+ values.
+ position_embeddings (`torch.FloatTensor`, *optional*):
+ Object queries (also called content embeddings), to be added to the hidden states.
+ output_attentions (`bool`, *optional*, defaults to `False`):
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
+ returned tensors for more detail.
+ """
+ residual = hidden_states
+ query = key = self.with_pos_embed(hidden_states, position_embeddings)
+
+ hidden_states = self.self_attn(
+ queries=query,
+ keys=key,
+ values=hidden_states,
+ attention_mask=attention_mask,
+ output_attentions=output_attentions,
+ )
+ hidden_states, attentions = hidden_states if output_attentions else (hidden_states[0], None)
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = residual + hidden_states
+ hidden_states = self.self_attn_layer_norm(hidden_states)
+ residual = hidden_states
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
+ hidden_states = self.encoder_feedforward_dropout(hidden_states)
+ hidden_states = self.fc2(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = residual + hidden_states
+ hidden_states = self.final_layer_norm(hidden_states)
+ if self.training:
+ if not torch.isfinite(hidden_states).all():
+ clamp_value = torch.finfo(hidden_states.dtype).max - 1000
+ hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
+
+ if output_attentions:
+ return hidden_states, attentions
+
+ return (hidden_states,)
+
+
+class OmDetTurboEncoder(nn.Module):
+ def __init__(self, config: OmDetTurboConfig):
+ super().__init__()
+
+ self.layers = nn.ModuleList([OmDetTurboEncoderLayer(config) for _ in range(config.encoder_layers)])
+
+ def forward(
+ self, src, src_mask=None, pos_embed=None, output_attentions: bool = False
+ ) -> tuple[torch.Tensor | tuple[torch.Tensor]]:
+ hidden_states = src
+ attention = () if output_attentions else None
+ for layer in self.layers:
+ hidden_states = layer(
+ hidden_states,
+ attention_mask=src_mask,
+ position_embeddings=pos_embed,
+ output_attentions=output_attentions,
+ )
+ if output_attentions:
+ attention = attention + (hidden_states[1],)
+ hidden_states = hidden_states[0]
+
+ return hidden_states, attention
+
+
+class OmDetTurboHybridEncoder(nn.Module):
+ """
+ Encoder consisting of channel projection layers, a set of `OmDetTurboEncoder`, a top-down Feature Pyramid Network
+ (FPN) and a bottom-up Path Aggregation Network (PAN). More details on the paper: https://huggingface.co/papers/2304.08069
+
+ Args:
+ config: OmDetTurboConfig
+ """
+
+ def __init__(self, config: OmDetTurboConfig):
+ super().__init__()
+ self.config = config
+ self.in_channels = config.encoder_in_channels
+ self.encoder_hidden_dim = config.encoder_hidden_dim
+ self.encoder_projection_indices = config.encoder_projection_indices
+ self.positional_encoding_temperature = config.positional_encoding_temperature
+ self.eval_size = config.eval_size
+ self.out_channels = [self.encoder_hidden_dim for _ in self.in_channels]
+
+ self.channel_projection_layers = nn.ModuleList()
+ for in_channel in self.in_channels:
+ self.channel_projection_layers.append(
+ nn.Sequential(
+ nn.Conv2d(in_channel, self.encoder_hidden_dim, kernel_size=(1, 1), bias=False),
+ nn.BatchNorm2d(self.encoder_hidden_dim),
+ )
+ )
+
+ # encoder transformer
+ self.encoder = nn.ModuleList([OmDetTurboEncoder(config) for _ in range(len(self.encoder_projection_indices))])
+ # top-down fpn
+ self.lateral_convs = nn.ModuleList()
+ self.fpn_blocks = nn.ModuleList()
+ for _ in range(len(self.in_channels) - 1, 0, -1):
+ self.lateral_convs.append(
+ OmDetTurboConvNormLayer(
+ config,
+ in_channels=self.encoder_hidden_dim,
+ out_channels=self.encoder_hidden_dim,
+ kernel_size=1,
+ stride=1,
+ activation=config.conv_norm_activation,
+ )
+ )
+ self.fpn_blocks.append(OmDetTurboCSPRepLayer(config))
+
+ # bottom-up pan
+ self.downsample_convs = nn.ModuleList()
+ self.pan_blocks = nn.ModuleList()
+ for _ in range(len(self.in_channels) - 1):
+ self.downsample_convs.append(
+ OmDetTurboConvNormLayer(
+ config,
+ in_channels=self.encoder_hidden_dim,
+ out_channels=self.encoder_hidden_dim,
+ kernel_size=3,
+ stride=2,
+ activation=config.conv_norm_activation,
+ )
+ )
+ self.pan_blocks.append(OmDetTurboCSPRepLayer(config))
+
+ @staticmethod
+ def build_2d_sincos_position_embedding(
+ width, height, embed_dim=256, temperature=10000.0, device="cpu", dtype=torch.float32
+ ):
+ grid_w = torch.arange(int(width), dtype=dtype, device=device)
+ grid_h = torch.arange(int(height), dtype=dtype, device=device)
+ grid_w, grid_h = torch.meshgrid(grid_w, grid_h, indexing="ij")
+ if embed_dim % 4 != 0:
+ raise ValueError("Embed dimension must be divisible by 4 for 2D sin-cos position embedding")
+ pos_dim = embed_dim // 4
+ omega = torch.arange(pos_dim, dtype=dtype, device=device) / pos_dim
+ omega = 1.0 / (temperature**omega)
+
+ out_w = grid_w.flatten()[..., None] @ omega[None]
+ out_h = grid_h.flatten()[..., None] @ omega[None]
+
+ return torch.concat([out_w.sin(), out_w.cos(), out_h.sin(), out_h.cos()], dim=1)[None, :, :]
+
+ def forward(
+ self,
+ inputs_embeddings=None,
+ output_attentions=None,
+ output_hidden_states=None,
+ return_dict=None,
+ ):
+ r"""
+ Args:
+ inputs_embeddings (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
+ Flattened feature map (output of the backbone + projection layers) that is passed to the encoder.
+ output_attentions (`bool`, *optional*):
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
+ returned tensors for more detail.
+ output_hidden_states (`bool`, *optional*):
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
+ for more detail.
+ return_dict (`bool`, *optional*):
+ Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple.
+ """
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ hidden_states = inputs_embeddings
+
+ encoder_states = () if output_hidden_states else None
+ all_attentions = () if output_attentions else None
+ # get projection features
+ projected_features = [self.channel_projection_layers[i](feature) for i, feature in enumerate(hidden_states)]
+ # encoder
+ for encoder_layer_index, feature_to_project_index in enumerate(self.encoder_projection_indices):
+ if output_hidden_states:
+ encoder_states = encoder_states + (projected_features[feature_to_project_index],)
+ height, width = projected_features[feature_to_project_index].shape[2:]
+ # flatten [batch, channel, height, width] to [batch, height*width, channel]
+ src_flatten = projected_features[feature_to_project_index].flatten(2).permute(0, 2, 1)
+ if self.training or self.eval_size is None:
+ pos_embed = self.build_2d_sincos_position_embedding(
+ width,
+ height,
+ self.encoder_hidden_dim,
+ self.positional_encoding_temperature,
+ device=src_flatten.device,
+ dtype=src_flatten.dtype,
+ ).to(src_flatten.device, src_flatten.dtype)
+ else:
+ pos_embed = None
+ layer_outputs = self.encoder[encoder_layer_index](
+ src_flatten,
+ pos_embed=pos_embed,
+ output_attentions=output_attentions,
+ )
+ projected_features[feature_to_project_index] = (
+ layer_outputs[0].permute(0, 2, 1).reshape(-1, self.encoder_hidden_dim, height, width).contiguous()
+ )
+
+ if output_attentions:
+ all_attentions = all_attentions + (layer_outputs[1],)
+
+ if output_hidden_states:
+ encoder_states = encoder_states + (projected_features[feature_to_project_index],)
+
+ # Feature Pyramid Network (FPN)
+ fpn_feature_maps = [projected_features[-1]]
+ for idx in range(len(self.in_channels) - 1, 0, -1):
+ feat_high = fpn_feature_maps[0]
+ feat_low = projected_features[idx - 1]
+ feat_high = self.lateral_convs[len(self.in_channels) - 1 - idx](feat_high)
+ fpn_feature_maps[0] = feat_high
+ upsample_feat = F.interpolate(feat_high, scale_factor=2.0, mode="nearest")
+ fps_map = self.fpn_blocks[len(self.in_channels) - 1 - idx](torch.concat([upsample_feat, feat_low], dim=1))
+ fpn_feature_maps.insert(0, fps_map)
+
+ # Path Aggregation Network (PAN)
+ fpn_states = [fpn_feature_maps[0]]
+ for idx in range(len(self.in_channels) - 1):
+ feat_low = fpn_states[-1]
+ feat_high = fpn_feature_maps[idx + 1]
+ downsample_feat = self.downsample_convs[idx](feat_low)
+ hidden_states = self.pan_blocks[idx](
+ torch.concat([downsample_feat, feat_high.to(downsample_feat.device)], dim=1)
+ )
+ fpn_states.append(hidden_states)
+ if not return_dict:
+ return (fpn_states[-1], encoder_states, all_attentions, fpn_states)
+ return OmDetTurboEncoderOutput(
+ last_hidden_state=fpn_states[-1],
+ hidden_states=encoder_states,
+ attentions=all_attentions,
+ extracted_states=fpn_states,
+ )
+
+
+class OmDetTurboMLPWithDropout(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.linear1 = nn.Linear(config.class_embed_dim, config.task_encoder_hidden_dim)
+ self.activation = ACT2FN[config.decoder_activation]
+ self.dropout = nn.Dropout(config.decoder_dropout)
+ self.linear2 = nn.Linear(config.task_encoder_hidden_dim, config.class_embed_dim)
+
+ def forward(self, x):
+ return self.linear2(self.dropout(self.activation(self.linear1(x))))
+
+
+class OmDetTurboMLP(nn.Module):
+ """Very simple multi-layer perceptron (also called FFN)"""
+
+ def __init__(self, input_dim, hidden_dim, output_dim, num_layers):
+ super().__init__()
+ self.num_layers = num_layers
+ hidden_layers_dims = [hidden_dim] * (num_layers - 1)
+ layers_dims = [input_dim] + hidden_layers_dims + [output_dim]
+ self.layers = nn.ModuleList(
+ [nn.Linear(in_dim, out_dim) for in_dim, out_dim in zip(layers_dims[:-1], layers_dims[1:])]
+ )
+
+ def forward(self, x):
+ for i, layer in enumerate(self.layers):
+ x = F.relu(layer(x)) if i < self.num_layers - 1 else layer(x)
+ return x
+
+
+class OmDetTurboResidualLayer(nn.Module):
+ """
+ A residual connection followed by a layer norm.
+ """
+
+ def __init__(self, config):
+ super().__init__()
+ self.norm1 = nn.LayerNorm(config.class_embed_dim, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.decoder_dropout)
+
+ def forward(self, x, y):
+ return self.norm1(x + self.dropout(y))
+
+
+class OmDetTurboTaskEncoder(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.mlp = OmDetTurboMLPWithDropout(config)
+ self.res1 = OmDetTurboResidualLayer(config)
+
+ def forward(self, x):
+ mlp_out = self.mlp(x)
+ x = self.res1(x, mlp_out)
+ return x
+
+
+class OmDetTurboDeformableTransformerDecoderLayer(GradientCheckpointingLayer):
+ """
+ A single layer of the Deformable Transformer Decoder.
+ """
+
+ def __init__(self, config):
+ super().__init__()
+ # self attention
+ self.self_attn = OmDetTurboMultiheadAttention(
+ config,
+ hidden_size=config.decoder_hidden_dim,
+ num_attention_heads=config.decoder_num_heads,
+ dropout=config.decoder_dropout,
+ )
+ self.dropout1 = nn.Dropout(config.decoder_dropout)
+ self.norm1 = nn.LayerNorm(config.decoder_hidden_dim, eps=config.layer_norm_eps)
+
+ # cross attention
+ self.cross_attn = OmDetTurboMultiscaleDeformableAttention(
+ config, num_heads=config.decoder_num_heads, n_points=config.decoder_num_points
+ )
+ self.dropout2 = nn.Dropout(config.decoder_dropout)
+ self.norm2 = nn.LayerNorm(config.decoder_hidden_dim, eps=config.layer_norm_eps)
+
+ # feed forward network
+ self.linear1 = nn.Linear(config.decoder_hidden_dim, config.decoder_dim_feedforward)
+ self.act = ACT2FN[config.decoder_activation]
+ self.dropout3 = nn.Dropout(config.decoder_dropout)
+ self.linear2 = nn.Linear(config.decoder_dim_feedforward, config.decoder_hidden_dim)
+ self.dropout4 = nn.Dropout(config.decoder_dropout)
+ self.norm3 = nn.LayerNorm(config.decoder_hidden_dim, eps=config.layer_norm_eps)
+
+ self.output_attentions = config.output_attentions
+ self.output_hidden_states = config.output_hidden_states
+
+ @staticmethod
+ def with_pos_embed(tensor, pos):
+ return tensor if pos is None else tensor + pos
+
+ def forward(
+ self,
+ decoder_embeddings,
+ task_features,
+ reference_points,
+ vision_features,
+ vision_shapes,
+ vision_shapes_list,
+ level_start_index=None,
+ attention_mask=None,
+ padding_mask=None,
+ query_position=None,
+ output_attentions=None,
+ output_hidden_states=None,
+ ):
+ output_attentions = output_attentions if output_attentions is not None else self.output_attentions
+ output_hidden_states = output_hidden_states if output_hidden_states is not None else self.output_hidden_states
+
+ origin_embedding_len = decoder_embeddings.shape[1]
+
+ # self attention
+ query = key = self.with_pos_embed(decoder_embeddings, query_position)
+ # combine task_features with query, key, value
+ task_features = task_features.transpose(0, 1)
+ query = torch.cat((query, task_features), dim=1)
+ key = torch.cat((key, task_features), dim=1)
+ decoder_embeddings = torch.cat((decoder_embeddings, task_features), dim=1)
+
+ outputs = self.self_attn(
+ query,
+ key,
+ decoder_embeddings,
+ attention_mask=attention_mask,
+ output_attentions=output_attentions,
+ )
+ context, self_attention = outputs if output_attentions else (outputs[0], None)
+ decoder_embeddings = decoder_embeddings + self.dropout1(context)
+ decoder_embeddings = self.norm1(decoder_embeddings)
+
+ task_features = decoder_embeddings[:, origin_embedding_len:, :].transpose(0, 1)
+ decoder_embeddings = decoder_embeddings[:, :origin_embedding_len, :]
+
+ # cross attention
+ hidden_states = self.with_pos_embed(decoder_embeddings, query_position)
+ reference_points = reference_points.unsqueeze(2)
+ outputs, cross_attention = self.cross_attn(
+ hidden_states=hidden_states,
+ attention_mask=padding_mask,
+ encoder_hidden_states=vision_features,
+ reference_points=reference_points,
+ spatial_shapes=vision_shapes,
+ spatial_shapes_list=vision_shapes_list,
+ level_start_index=level_start_index,
+ )
+ decoder_embeddings = decoder_embeddings + self.dropout2(outputs)
+ residual = self.norm2(decoder_embeddings)
+
+ # feed forward network
+ decoder_embeddings = self.linear2(self.dropout3(self.act(self.linear1(residual))))
+ decoder_embeddings = residual + self.dropout4(decoder_embeddings)
+ decoder_embeddings = self.norm3(decoder_embeddings)
+
+ return (
+ decoder_embeddings,
+ task_features,
+ self_attention if output_attentions else None,
+ cross_attention if output_attentions else None,
+ )
+
+
+@auto_docstring
+class OmDetTurboPreTrainedModel(PreTrainedModel):
+ config: OmDetTurboConfig
+ base_model_prefix = "model"
+ main_input_name = "pixel_values"
+ input_modalities = ("image", "text")
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ def linear_init_(module_to_init):
+ bound = 1 / math.sqrt(module_to_init.weight.shape[0])
+ init.uniform_(module_to_init.weight, -bound, bound)
+ if hasattr(module_to_init, "bias") and module_to_init.bias is not None:
+ init.uniform_(module_to_init.bias, -bound, bound)
+
+ if isinstance(module, OmDetTurboEncoderLayer):
+ linear_init_(module.fc1)
+ linear_init_(module.fc2)
+ elif isinstance(module, OmDetTurboDecoder):
+ init.constant_(module.encoder_bbox_head.layers[-1].weight, 0.0)
+ init.constant_(module.encoder_bbox_head.layers[-1].bias, 0.0)
+ for mlp in module.decoder_bbox_head:
+ init.constant_(mlp.layers[-1].weight, 0.0)
+ init.constant_(mlp.layers[-1].bias, 0.0)
+ linear_init_(module.encoder_vision_features[0])
+ init.xavier_uniform_(module.encoder_vision_features[0].weight)
+ if module.learn_initial_query:
+ init.xavier_uniform_(module.tgt_embed.weight)
+ init.xavier_uniform_(module.query_position_head.layers[0].weight)
+ init.xavier_uniform_(module.query_position_head.layers[1].weight)
+ for layer in module.channel_projection_layers:
+ init.xavier_uniform_(layer[0].weight)
+ elif isinstance(module, OmDetTurboLanguageBackbone):
+ init.normal_(module.text_projection, std=self.config.text_projection_in_dim**-0.5)
+ elif isinstance(module, (nn.Linear, nn.Conv2d)):
+ init.normal_(module.weight, mean=0.0, std=self.config.init_std)
+ if module.bias is not None:
+ init.zeros_(module.bias)
+ elif isinstance(module, (nn.LayerNorm, nn.BatchNorm2d)):
+ init.ones_(module.weight)
+ init.zeros_(module.bias)
+ if getattr(module, "running_mean", None) is not None:
+ init.zeros_(module.running_mean)
+ init.ones_(module.running_var)
+ init.zeros_(module.num_batches_tracked)
+
+ def _set_gradient_checkpointing(self, module, value=False):
+ if isinstance(module, OmDetTurboDecoder):
+ module.gradient_checkpointing = value
+
+ @staticmethod
+ def _get_cache_key_at_index(input_ids, attention_mask, index):
+ input_ids = input_ids[index]
+ input_mask = attention_mask[index]
+ cache_key = tuple(input_ids[input_mask != 0].tolist())
+ return cache_key
+
+ def get_cached_class_embeddings(self, classes_input_ids, classes_attention_mask):
+ not_cached_index = []
+ not_cached_classes = []
+ total_embeddings = []
+ for idx, _ in enumerate(classes_input_ids):
+ cache_key = self._get_cache_key_at_index(classes_input_ids, classes_attention_mask, idx)
+ if self.language_cache_class.has(cache_key):
+ total_embeddings.append(self.language_cache_class.get(cache_key))
+ else:
+ total_embeddings.append(None)
+ not_cached_index.append(idx)
+ not_cached_classes.append(cache_key)
+
+ if not_cached_classes:
+ not_cached_classes_ids = torch.stack([classes_input_ids[idx] for idx in not_cached_index])
+ embeddings = self.language_backbone(not_cached_classes_ids, encode_type="class")
+ for idx, emb in enumerate(embeddings):
+ idx_to_put = not_cached_index[idx]
+ total_embeddings[idx_to_put] = emb
+ self.language_cache_class.put(not_cached_classes[idx], emb)
+
+ total_class_embs = torch.stack(total_embeddings).to(self.device)
+ return total_class_embs
+
+ def get_cached_task_embeddings(self, tasks_input_ids, tasks_attention_mask):
+ not_cached_index = []
+ not_cached_tasks = []
+ total_task_features = []
+ total_task_masks = []
+ for idx, _ in enumerate(tasks_input_ids):
+ cache_key = self._get_cache_key_at_index(tasks_input_ids, tasks_attention_mask, idx)
+ if self.language_cache_prompt.has(cache_key):
+ task_feature, task_mask = self.language_cache_prompt.get(cache_key)
+ total_task_features.append(task_feature)
+ total_task_masks.append(task_mask)
+ else:
+ total_task_features.append(None)
+ total_task_masks.append(None)
+ not_cached_index.append(idx)
+ not_cached_tasks.append(cache_key)
+
+ if not_cached_tasks:
+ not_cached_index_ids = torch.stack([tasks_input_ids[idx] for idx in not_cached_index])
+ not_cached_mask = torch.stack([tasks_attention_mask[idx] for idx in not_cached_index])
+ embeddings, masks = self.language_backbone(not_cached_index_ids, mask=not_cached_mask, encode_type="task")
+
+ for idx in range(embeddings.shape[1]):
+ emb = embeddings[:, [idx], :]
+ idx_to_put = not_cached_index[idx]
+ cur_mask = torch.unsqueeze(masks[idx], dim=0).to(self.device)
+ total_task_features[idx_to_put] = emb
+ total_task_masks[idx_to_put] = cur_mask
+ self.language_cache_prompt.put(not_cached_tasks[idx], (emb, cur_mask))
+
+ # pad before concat if needed
+ max_len = max(task.shape[0] for task in total_task_features)
+ for idx, task in enumerate(total_task_features):
+ if task.shape[0] < max_len:
+ pad_size = max_len - task.shape[0]
+ total_task_features[idx] = F.pad(task, (0, 0, 0, 0, 0, pad_size))
+ total_task_masks[idx] = F.pad(total_task_masks[idx], (0, pad_size))
+
+ total_task_features = torch.cat(total_task_features, dim=1).to(self.device)
+ total_task_masks = torch.cat(total_task_masks, dim=0).to(self.device)
+
+ return total_task_features, total_task_masks
+
+ def get_language_embedding(
+ self,
+ classes_input_ids,
+ classes_attention_mask,
+ tasks_input_ids,
+ tasks_attention_mask,
+ classes_structure,
+ ):
+ batched_classes_embeddings = self.get_cached_class_embeddings(classes_input_ids, classes_attention_mask)
+ # regroup class embeddings using saved structure
+ max_class_size = torch.max(classes_structure)
+ class_embeddings_regrouped = []
+ start = 0
+ for size in classes_structure:
+ pad_size = max_class_size - size
+ class_embeddings_regrouped.append(
+ F.pad(batched_classes_embeddings[start : start + size], (0, 0, 0, pad_size)).unsqueeze(1)
+ )
+ start += size
+ class_embeddings = torch.cat(class_embeddings_regrouped, dim=1)
+
+ task_embeddings, task_mask = self.get_cached_task_embeddings(tasks_input_ids, tasks_attention_mask)
+
+ return class_embeddings, task_embeddings, task_mask
+
+
+def _cosine_similarity_scaled(a, b, logit_scale):
+ a = a / a.norm(dim=2, keepdim=True).clamp_min(1e-12)
+ b = b / b.norm(dim=1, keepdim=True).clamp_min(1e-12)
+ logit_scale = logit_scale.exp()
+ logits_per_image = logit_scale * torch.bmm(a, b)
+ return logits_per_image
+
+
+def get_class_similarity(class_distance_type, cls_feature, class_proj):
+ logit_scale = torch.tensor(1 / 0.07).log()
+ if class_distance_type == "cosine":
+ class_logits = _cosine_similarity_scaled(cls_feature, class_proj, logit_scale)
+ elif class_distance_type == "dot":
+ class_logits = torch.bmm(cls_feature, class_proj)
+ else:
+ raise Exception(f"Unknown class_distance_type {class_distance_type}")
+ return class_logits
+
+
+def _inverse_sigmoid(x, eps=1e-5):
+ x = x.clamp(min=0, max=1)
+ x1 = x.clamp(min=eps)
+ x2 = (1 - x).clamp(min=eps)
+ return torch.log(x1 / x2)
+
+
+class OmDetTurboDecoder(OmDetTurboPreTrainedModel):
+ def __init__(self, config: OmDetTurboConfig):
+ self.config = config
+ super().__init__(config)
+ self.gradient_checkpointing = False
+
+ hidden_dim = config.decoder_hidden_dim
+ self.num_queries = config.num_queries
+ self.class_distance_type = config.class_distance_type
+ self.learn_initial_query = config.learn_initial_query
+
+ # backbone feature projection
+ self.channel_projection_layers = nn.ModuleList(
+ nn.Sequential(nn.Conv2d(x, hidden_dim, 1, bias=False), nn.BatchNorm2d(hidden_dim))
+ for x in config.vision_features_channels
+ )
+ self.task_encoder = OmDetTurboTaskEncoder(config)
+ if config.class_embed_dim != hidden_dim:
+ self.task_project = nn.Linear(config.class_embed_dim, hidden_dim)
+
+ # Transformer module
+ self.layers = nn.ModuleList(
+ [OmDetTurboDeformableTransformerDecoderLayer(config) for _ in range(config.decoder_num_layers)]
+ )
+ self.decoder_num_layers = config.decoder_num_layers
+ # decoder embedding
+ if self.learn_initial_query:
+ self.tgt_embed = nn.Embedding(self.num_queries, hidden_dim)
+ self.query_position_head = OmDetTurboMLP(
+ input_dim=4, hidden_dim=2 * hidden_dim, output_dim=hidden_dim, num_layers=2
+ )
+
+ # encoder head
+ self.encoder_vision_features = nn.Sequential(
+ nn.Linear(hidden_dim, hidden_dim), nn.LayerNorm(hidden_dim, eps=config.layer_norm_eps)
+ )
+ self.encoder_class_head = nn.Linear(config.class_embed_dim, hidden_dim)
+ self.encoder_bbox_head = OmDetTurboMLP(input_dim=hidden_dim, hidden_dim=hidden_dim, output_dim=4, num_layers=3)
+
+ # decoder head
+ self.decoder_class_head = nn.ModuleList(
+ [nn.Linear(config.class_embed_dim, hidden_dim) for _ in range(config.decoder_num_layers)]
+ )
+ self.decoder_bbox_head = nn.ModuleList(
+ [OmDetTurboMLP(hidden_dim, hidden_dim, 4, num_layers=3) for _ in range(config.decoder_num_layers)]
+ )
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @lru_cache(maxsize=32)
+ def generate_anchors(self, spatial_shapes=None, grid_size=0.05, device="cpu", dtype=torch.float32):
+ # We always generate anchors in float32 to preserve equivalence between
+ # dynamic and static anchor inference
+ # Ignore copy
+ if spatial_shapes is None:
+ raise ValueError("spatial_shapes must be provided")
+
+ anchors = []
+ for level, (height, width) in enumerate(spatial_shapes):
+ grid_y, grid_x = torch.meshgrid(
+ torch.arange(end=height, dtype=dtype, device=device),
+ torch.arange(end=width, dtype=dtype, device=device),
+ indexing="ij",
+ )
+ grid_xy = torch.stack([grid_x, grid_y], -1)
+ valid_wh = torch.tensor([width, height], dtype=dtype, device=device)
+ grid_xy = (grid_xy.unsqueeze(0) + 0.5) / valid_wh
+ wh = torch.ones_like(grid_xy, dtype=dtype, device=device) * grid_size * (2.0**level)
+ anchors.append(torch.concat([grid_xy, wh], -1).reshape(-1, height * width, 4))
+ # define the valid range for anchor coordinates
+ eps = 1e-2
+ anchors = torch.concat(anchors, 1)
+ valid_mask = ((anchors > eps) * (anchors < 1 - eps)).all(-1, keepdim=True)
+ anchors = torch.log(anchors / (1 - anchors))
+ anchors = torch.where(valid_mask, anchors, torch.inf)
+
+ return anchors, valid_mask
+
+ def _get_encoder_input(self, vision_features):
+ # get projection features
+ vision_features = [self.channel_projection_layers[i](feat) for i, feat in enumerate(vision_features)]
+ # get encoder inputs
+ new_vision_features = []
+ new_vision_shapes_list = []
+ for feat in vision_features:
+ height, width = feat.shape[2:]
+ # [batch_size, channels, height, width] -> [batch_size, height*width, channels]
+ new_vision_features.append(feat.flatten(2).permute(0, 2, 1))
+ # [num_feature_levels, 2]
+ new_vision_shapes_list.append((height, width))
+
+ # [batch_size, height*width, channels]
+ new_vision_features = torch.cat(new_vision_features, 1)
+ new_vision_shapes = torch.tensor(new_vision_shapes_list, dtype=torch.int64, device=vision_features[0].device)
+ level_start_index = torch.cat((new_vision_shapes.new_zeros((1,)), new_vision_shapes.prod(1).cumsum(0)[:-1]))
+
+ return new_vision_features, new_vision_shapes, new_vision_shapes_list, level_start_index
+
+ def _get_decoder_input(
+ self, vision_features, vision_shapes, class_features, denoise_embeddings=None, denoise_bboxes=None
+ ):
+ batch_size = len(vision_features)
+ # prepare input for decoder
+ anchors, valid_mask = self.generate_anchors(
+ vision_shapes, device=vision_features.device, dtype=vision_features.dtype
+ )
+ predicted_class_features = self.encoder_vision_features(
+ torch.where(
+ valid_mask,
+ vision_features,
+ torch.tensor(0.0, dtype=vision_features.dtype, device=vision_features.device),
+ )
+ )
+
+ original_class_projected = self.encoder_class_head(class_features).permute(1, 2, 0)
+ encoder_class_similarity = get_class_similarity(
+ self.class_distance_type, predicted_class_features, original_class_projected
+ )
+
+ # dynamic anchors + static content
+ # (batch_size, height*width, 4)
+ encoder_outputs_bboxes = self.encoder_bbox_head(predicted_class_features) + anchors
+
+ # query selection
+ # (batch_size, num_queries)
+ topk_ind = torch.topk(encoder_class_similarity.max(-1).values, self.num_queries, dim=1).indices.view(-1)
+ # (batch_size, num_queries)
+ batch_ind = (
+ torch.arange(end=batch_size, dtype=topk_ind.dtype, device=topk_ind.device)
+ .unsqueeze(-1)
+ .repeat(1, self.num_queries)
+ .view(-1)
+ )
+
+ reference_points = encoder_outputs_bboxes[batch_ind, topk_ind].view(batch_size, self.num_queries, -1)
+ encoder_bboxes = reference_points.sigmoid()
+ if denoise_bboxes is not None:
+ reference_points = torch.cat([denoise_bboxes, reference_points], 1)
+ if self.training:
+ reference_points = reference_points.detach()
+ encoder_class_similarity = encoder_class_similarity[batch_ind, topk_ind].view(batch_size, self.num_queries, -1)
+
+ if self.learn_initial_query:
+ embeddings = self.tgt_embed.weight.unsqueeze(0).repeat(batch_size, 1, 1)
+ else:
+ embeddings = predicted_class_features[batch_ind, topk_ind].view(batch_size, self.num_queries, -1)
+ if self.training:
+ embeddings = embeddings.detach()
+ if denoise_embeddings is not None:
+ embeddings = torch.cat([denoise_embeddings, embeddings], 1)
+
+ return embeddings, reference_points, encoder_bboxes, encoder_class_similarity, anchors
+
+ def forward(
+ self,
+ vision_features,
+ class_features,
+ task_features,
+ task_mask,
+ output_attentions=None,
+ output_hidden_states=None,
+ return_dict=None,
+ **kwargs,
+ ):
+ """
+ Args:
+ vision_features (`torch.FloatTensor`): The sequence of vision features. shape depends on the vision
+ backbone.
+ class_features (`torch.FloatTensor`): The sequence of class features of shape
+ `(class_sequence_length, batch_size, class_embed_dim)`.
+ task_features (`torch.FloatTensor`): The sequence of task features of shape
+ `(task_sequence_length, batch_size, decoder_hidden_dim)`.
+ task_mask (`torch.LongTensor`): The mask for the task features of shape `(batch_size, task_sequence_length)`.
+ output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention
+ layers. See `attentions` under returned tensors for more detail.
+ output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See
+ `hidden_states` under returned tensors for more detail.
+ return_dict (`bool`, *optional*): Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain
+ tuple.
+ """
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ vision_features, vision_shapes, vision_shapes_list, level_start_index = self._get_encoder_input(
+ vision_features
+ )
+
+ # todo add denoising for training
+ denoise_embeddings, denoise_bboxes, key_padding_mask = None, None, None
+ batch_size = task_mask.shape[0]
+
+ # compose attn_mask for vision_emb and task_emb fusion
+ task_features = self.task_encoder(task_features)
+ if self.task_project is not None:
+ task_features = self.task_project(task_features)
+ src_key_mask = (task_mask == 0).detach()
+ attn_mask_len = self.num_queries
+ fusion_size = attn_mask_len + task_features.shape[0]
+ key_padding_mask = torch.zeros([batch_size, fusion_size], dtype=torch.bool).to(task_features.device)
+ key_padding_mask[:, attn_mask_len:] = src_key_mask
+ decoder_embeddings, reference_points, encoder_bboxes, encoder_class_similarity, init_reference_points = (
+ self._get_decoder_input(
+ vision_features, tuple(vision_shapes_list), class_features, denoise_embeddings, denoise_bboxes
+ )
+ )
+ attention_mask = create_bidirectional_mask(
+ config=self.config,
+ inputs_embeds=torch.ones_like(key_padding_mask, dtype=decoder_embeddings.dtype)[..., None],
+ attention_mask=~key_padding_mask,
+ )
+
+ all_hidden_states = () if output_hidden_states else None
+ all_attns = () if output_attentions else None
+ all_self_attns = () if output_attentions else None
+ all_cross_attns = () if output_attentions else None
+ predicted_class_features = decoder_embeddings
+
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (predicted_class_features,)
+ decoder_bboxes = []
+ decoder_classes = []
+ last_refined_bbox = None
+ reference_points = reference_points.sigmoid()
+ for i, layer in enumerate(self.layers):
+ predicted_class_features, task_features, self_attention, cross_attention = layer(
+ predicted_class_features,
+ task_features,
+ reference_points,
+ vision_features,
+ vision_shapes,
+ vision_shapes_list,
+ level_start_index=level_start_index,
+ attention_mask=attention_mask,
+ query_position=self.query_position_head(reference_points),
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ )
+ if output_attentions:
+ all_self_attns = all_self_attns + (self_attention,)
+ all_cross_attns = all_cross_attns + (cross_attention,)
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (predicted_class_features,)
+
+ refined_bbox = torch.sigmoid(
+ self.decoder_bbox_head[i](predicted_class_features) + _inverse_sigmoid(reference_points)
+ )
+ original_class_projected = self.decoder_class_head[i](class_features).permute(1, 2, 0)
+ if self.training:
+ decoder_classes.append(
+ get_class_similarity(
+ class_distance_type=self.class_distance_type,
+ cls_feature=predicted_class_features,
+ class_proj=original_class_projected,
+ )
+ )
+ if i == 0:
+ decoder_bboxes.append(refined_bbox)
+ else:
+ decoder_bboxes.append(
+ torch.sigmoid(
+ self.decoder_bbox_head[i](predicted_class_features) + _inverse_sigmoid(last_refined_bbox)
+ )
+ )
+ elif i == self.decoder_num_layers - 1:
+ decoder_classes.append(
+ get_class_similarity(self.class_distance_type, predicted_class_features, original_class_projected)
+ )
+ decoder_bboxes.append(refined_bbox)
+ break
+ last_refined_bbox = refined_bbox
+ reference_points = refined_bbox.detach() if self.training else refined_bbox
+ if output_attentions:
+ all_attns += (all_self_attns, all_cross_attns)
+
+ last_hidden_state = predicted_class_features
+ decoder_bboxes = torch.stack(decoder_bboxes)
+ decoder_classes = torch.stack(decoder_classes)
+
+ if not return_dict:
+ return (
+ last_hidden_state,
+ all_hidden_states,
+ all_attns,
+ decoder_bboxes,
+ decoder_classes,
+ encoder_bboxes,
+ encoder_class_similarity,
+ init_reference_points,
+ reference_points,
+ )
+
+ return OmDetTurboDecoderOutput(
+ last_hidden_state=last_hidden_state,
+ hidden_states=all_hidden_states,
+ attentions=all_attns,
+ decoder_coords=decoder_bboxes,
+ decoder_classes=decoder_classes,
+ encoder_coord_logits=encoder_bboxes,
+ encoder_class_logits=encoder_class_similarity,
+ init_reference_points=init_reference_points,
+ intermediate_reference_points=reference_points,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ OmDetTurbo Model (consisting of a vision and a text backbone, and encoder-decoder architecture) outputting
+ bounding boxes and classes scores for tasks such as COCO detection.
+ """
+)
+class OmDetTurboForObjectDetection(OmDetTurboPreTrainedModel):
+ def __init__(self, config: OmDetTurboConfig):
+ super().__init__(config)
+ self.vision_backbone = OmDetTurboVisionBackbone(config)
+ self.language_backbone = OmDetTurboLanguageBackbone(config)
+ self.encoder = OmDetTurboHybridEncoder(config)
+ self.decoder = OmDetTurboDecoder(config)
+ self.num_queries = config.num_queries
+
+ self.language_cache_class = OmDetTurboLRUCache(config.cache_size)
+ self.language_cache_prompt = OmDetTurboLRUCache(config.cache_size)
+ self.vocab_size = config.text_config.vocab_size
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.language_backbone.model.get_input_embeddings()
+
+ def set_input_embeddings(self, value):
+ self.language_backbone.model.set_input_embeddings(value)
+
+ def resize_token_embeddings(
+ self, new_num_tokens: int | None = None, pad_to_multiple_of=None, mean_resizing: bool = True
+ ) -> nn.Embedding:
+ model_embeds = self.language_backbone.model.resize_token_embeddings(
+ new_num_tokens=new_num_tokens, pad_to_multiple_of=pad_to_multiple_of, mean_resizing=mean_resizing
+ )
+ self.config.text_config.vocab_size = model_embeds.num_embeddings
+ self.vocab_size = model_embeds.num_embeddings
+ return model_embeds
+
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: torch.FloatTensor,
+ classes_input_ids: torch.LongTensor,
+ classes_attention_mask: torch.LongTensor,
+ tasks_input_ids: torch.LongTensor,
+ tasks_attention_mask: torch.LongTensor,
+ classes_structure: torch.LongTensor,
+ labels: torch.LongTensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple[torch.FloatTensor] | OmDetTurboObjectDetectionOutput:
+ r"""
+ classes_input_ids (`torch.LongTensor` of shape `(total_classes (>= batch_size), sequence_length)`):
+ Indices of input classes sequence tokens in the vocabulary of the language model.
+ Several classes can be provided for each tasks, thus the tokenized classes are flattened
+ and the structure of the classes is provided in the `classes_structure` argument.
+
+ Indices can be obtained using [`OmDetTurboProcessor`]. See [`OmDetTurboProcessor.__call__`] for
+ details.
+
+ [What are input IDs?](../glossary#input-ids)
+ classes_attention_mask (`torch.BoolTensor` of shape `(total_classes (>= batch_size), num_classes, sequence_length)`):
+ Attention mask for the classes. This is a binary mask that indicates which tokens should be attended to,
+ and which should not.
+ tasks_input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ Indices of input tasks sequence tokens in the vocabulary of the language model.
+
+ Indices can be obtained using [`OmDetTurboProcessor`]. See [`OmDetTurboProcessor.__call__`] for
+ details.
+
+ [What are input IDs?](../glossary#input-ids)
+ tasks_attention_mask (`torch.BoolTensor` of shape `(batch_size, sequence_length)`):
+ Attention mask for the tasks. This is a binary mask that indicates which tokens should be attended to,
+ and which should not.
+ classes_structure (torch.LongTensor of shape `(batch_size)`):
+ Structure of the classes. This tensor indicates the number of classes for each task.
+
+ Examples:
+
+ ```python
+ >>> import httpx
+ >>> from io import BytesIO
+ >>> from PIL import Image
+
+ >>> from transformers import AutoProcessor, OmDetTurboForObjectDetection
+
+ >>> processor = AutoProcessor.from_pretrained("omlab/omdet-turbo-swin-tiny-hf")
+ >>> model = OmDetTurboForObjectDetection.from_pretrained("omlab/omdet-turbo-swin-tiny-hf")
+
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
+ >>> with httpx.stream("GET", url) as response:
+ ... image = Image.open(BytesIO(response.read()))
+ >>> classes = ["cat", "remote"]
+ >>> task = "Detect {}.".format(", ".join(classes))
+ >>> inputs = processor(image, text=classes, task=task, return_tensors="pt")
+
+ >>> outputs = model(**inputs)
+
+ >>> # convert outputs (bounding boxes and class logits)
+ >>> results = processor.post_process_grounded_object_detection(
+ ... outputs,
+ ... classes=classes,
+ ... target_sizes=[image.size[::-1]],
+ ... score_threshold=0.3,
+ ... nms_threshold=0.3,
+ >>> )[0]
+ >>> for score, class_name, box in zip(results["scores"], results["classes"], results["boxes"]):
+ ... box = [round(i, 1) for i in box.tolist()]
+ ... print(
+ ... f"Detected {class_name} with confidence "
+ ... f"{round(score.item(), 2)} at location {box}"
+ ... )
+ Detected remote with confidence 0.76 at location [39.9, 71.3, 176.5, 117.9]
+ Detected cat with confidence 0.72 at location [345.1, 22.5, 639.7, 371.9]
+ Detected cat with confidence 0.65 at location [12.7, 53.8, 315.5, 475.3]
+ Detected remote with confidence 0.57 at location [333.4, 75.6, 370.7, 187.0]
+ ```"""
+ if labels is not None:
+ raise NotImplementedError("Training is not implemented yet")
+
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ loss = None
+ image_features = self.vision_backbone(pixel_values)
+ encoder_outputs = self.encoder(
+ image_features,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+ class_features, task_features, task_mask = self.get_language_embedding(
+ classes_input_ids,
+ classes_attention_mask,
+ tasks_input_ids,
+ tasks_attention_mask,
+ classes_structure,
+ )
+ encoder_extracted_states = encoder_outputs.extracted_states if return_dict else encoder_outputs[-1]
+ decoder_outputs = self.decoder(
+ encoder_extracted_states,
+ class_features,
+ task_features,
+ task_mask,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ if not return_dict:
+ return tuple(
+ output
+ for output in [
+ loss,
+ decoder_outputs[3][-1],
+ decoder_outputs[4][-1],
+ decoder_outputs[7],
+ decoder_outputs[8],
+ decoder_outputs[5],
+ decoder_outputs[6],
+ encoder_outputs[-1],
+ decoder_outputs[1],
+ decoder_outputs[2],
+ encoder_outputs[1],
+ encoder_outputs[2],
+ classes_structure,
+ ]
+ if output is not None
+ )
+
+ return OmDetTurboObjectDetectionOutput(
+ loss=loss,
+ decoder_coord_logits=decoder_outputs.decoder_coords[-1],
+ decoder_class_logits=decoder_outputs.decoder_classes[-1],
+ init_reference_points=decoder_outputs.init_reference_points,
+ intermediate_reference_points=decoder_outputs.intermediate_reference_points,
+ encoder_coord_logits=decoder_outputs.encoder_coord_logits,
+ encoder_class_logits=decoder_outputs.encoder_class_logits,
+ encoder_extracted_states=encoder_outputs.extracted_states,
+ decoder_hidden_states=decoder_outputs.hidden_states,
+ decoder_attentions=decoder_outputs.attentions,
+ encoder_hidden_states=encoder_outputs.hidden_states,
+ encoder_attentions=encoder_outputs.attentions,
+ classes_structure=classes_structure,
+ )
+
+
+__all__ = ["OmDetTurboForObjectDetection", "OmDetTurboPreTrainedModel"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/omdet_turbo/processing_omdet_turbo.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/omdet_turbo/processing_omdet_turbo.py
new file mode 100644
index 0000000000000000000000000000000000000000..6c154978cedbbc0ca12c728bbf0fe45fa92baa67
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/omdet_turbo/processing_omdet_turbo.py
@@ -0,0 +1,353 @@
+# Copyright 2024 The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""
+Processor class for OmDet-Turbo.
+"""
+
+from typing import TYPE_CHECKING
+
+from ...feature_extraction_utils import BatchFeature
+from ...image_transforms import center_to_corners_format
+from ...image_utils import ImageInput
+from ...processing_utils import ProcessingKwargs, ProcessorMixin, TextKwargs, Unpack
+from ...tokenization_utils_base import PreTokenizedInput, TextInput
+from ...utils import (
+ TensorType,
+ auto_docstring,
+ is_torch_available,
+ is_torchvision_available,
+)
+from ...utils.import_utils import requires
+
+
+if TYPE_CHECKING:
+ from .modeling_omdet_turbo import OmDetTurboObjectDetectionOutput
+
+
+class OmDetTurboTextKwargs(TextKwargs, total=False):
+ """
+ task (`str`, `list[str]`, `TextInput`, or `PreTokenizedInput`, *optional*):
+ The detection task description(s) to encode. If not provided, a default task description is generated
+ from the `text` input (e.g., "Detect {text}."). Can be a single string, a list of strings (one per image),
+ or pre-tokenized input. The task description guides the model on what objects to detect in the images.
+ """
+
+ task: str | list[str] | TextInput | PreTokenizedInput | None
+
+
+if is_torch_available():
+ import torch
+
+
+if is_torchvision_available():
+ from torchvision.ops.boxes import batched_nms
+
+
+class OmDetTurboProcessorKwargs(ProcessingKwargs, total=False):
+ text_kwargs: OmDetTurboTextKwargs
+ _defaults = {
+ "text_kwargs": {
+ "add_special_tokens": True,
+ "padding": "max_length",
+ "truncation": True,
+ "max_length": 77,
+ "stride": 0,
+ "return_overflowing_tokens": False,
+ "return_special_tokens_mask": False,
+ "return_offsets_mapping": False,
+ "return_token_type_ids": False,
+ "return_length": False,
+ "verbose": True,
+ "task": None,
+ },
+ }
+
+
+def clip_boxes(box, box_size: tuple[int, int]):
+ """
+ Clip the boxes by limiting x coordinates to the range [0, width]
+ and y coordinates to the range [0, height].
+
+ Args:
+ box (Tensor): The box to be clipped.
+ box_size (height, width): The clipping box's size.
+ """
+ assert torch.isfinite(box).all(), "Box tensor contains infinite or NaN!"
+ height, width = box_size
+ x1 = box[:, 0].clamp(min=0, max=width)
+ y1 = box[:, 1].clamp(min=0, max=height)
+ x2 = box[:, 2].clamp(min=0, max=width)
+ y2 = box[:, 3].clamp(min=0, max=height)
+ box = torch.stack((x1, y1, x2, y2), dim=-1)
+
+ return box
+
+
+def compute_score(boxes):
+ """
+ Compute logit scores per class for each box (proposal) and an array of class indices
+ corresponding to each proposal, flattened across the proposal_num.
+ The indices in `classes` will later be used to filter and match the predicted classes
+ with the input class names.
+ """
+ num_classes = boxes.shape[2]
+ proposal_num = boxes.shape[1]
+ scores = torch.sigmoid(boxes)
+ classes = torch.arange(num_classes, device=boxes.device).unsqueeze(0).repeat(proposal_num, 1).flatten(0, 1)
+ return scores, classes
+
+
+def _post_process_boxes_for_image(
+ boxes: "torch.Tensor",
+ scores: "torch.Tensor",
+ labels: "torch.Tensor",
+ image_num_classes: int,
+ image_size: tuple[int, int],
+ threshold: float,
+ nms_threshold: float,
+ max_num_det: int | None = None,
+) -> tuple["torch.Tensor", "torch.Tensor", "torch.Tensor"]:
+ """
+ Filter predicted results using given thresholds and NMS.
+
+ Args:
+ boxes (`torch.Tensor`):
+ A Tensor of predicted class-specific or class-agnostic boxes for the image.
+ Shape (num_queries, max_num_classes_in_batch * 4) if doing class-specific regression,
+ or (num_queries, 4) if doing class-agnostic regression.
+ scores (`torch.Tensor` of shape (num_queries, max_num_classes_in_batch + 1)):
+ A Tensor of predicted class scores for the image.
+ labels (`torch.Tensor` of shape (num_queries * (max_num_classes_in_batch + 1),)):
+ A Tensor of predicted labels for the image.
+ image_num_classes (`int`):
+ The number of classes queried for detection on the image.
+ image_size (`tuple[int, int]`):
+ A tuple of (height, width) for the image.
+ threshold (`float`):
+ Only return detections with a confidence score exceeding this threshold.
+ nms_threshold (`float`):
+ The threshold to use for box non-maximum suppression. Value in [0, 1].
+ max_num_det (`int`, *optional*):
+ The maximum number of detections to return. Default is None.
+
+ Returns:
+ Tuple: A tuple with the following:
+ "boxes" (Tensor): A tensor of shape (num_filtered_objects, 4), containing the predicted boxes in (x1, y1, x2, y2) format.
+ "scores" (Tensor): A tensor of shape (num_filtered_objects,), containing the predicted confidence scores for each detection.
+ "labels" (Tensor): A tensor of ids, where each id is the predicted class id for the corresponding detection
+ """
+
+ # Filter by max number of detections
+ proposal_num = len(boxes) if max_num_det is None else max_num_det
+ scores_per_image, topk_indices = scores.flatten(0, 1).topk(proposal_num, sorted=False)
+ labels_per_image = labels[topk_indices]
+ boxes_per_image = boxes.view(-1, 1, 4).repeat(1, scores.shape[1], 1).view(-1, 4)
+ boxes_per_image = boxes_per_image[topk_indices]
+
+ # Convert and scale boxes to original image size
+ boxes_per_image = center_to_corners_format(boxes_per_image)
+ boxes_per_image = boxes_per_image * torch.tensor(image_size[::-1]).repeat(2).to(boxes_per_image.device)
+
+ # Filtering by confidence score
+ filter_mask = scores_per_image > threshold # R x K
+ score_keep = filter_mask.nonzero(as_tuple=False).view(-1)
+ boxes_per_image = boxes_per_image[score_keep]
+ scores_per_image = scores_per_image[score_keep]
+ labels_per_image = labels_per_image[score_keep]
+
+ # Ensure we did not overflow to non existing classes
+ filter_classes_mask = labels_per_image < image_num_classes
+ classes_keep = filter_classes_mask.nonzero(as_tuple=False).view(-1)
+ boxes_per_image = boxes_per_image[classes_keep]
+ scores_per_image = scores_per_image[classes_keep]
+ labels_per_image = labels_per_image[classes_keep]
+
+ # NMS
+ keep = batched_nms(boxes_per_image, scores_per_image, labels_per_image, nms_threshold)
+ boxes_per_image = boxes_per_image[keep]
+ scores_per_image = scores_per_image[keep]
+ labels_per_image = labels_per_image[keep]
+
+ # Clip to image size
+ boxes_per_image = clip_boxes(boxes_per_image, image_size)
+
+ return boxes_per_image, scores_per_image, labels_per_image
+
+
+@requires(backends=("vision", "torchvision"))
+@auto_docstring
+class OmDetTurboProcessor(ProcessorMixin):
+ def __init__(self, image_processor, tokenizer):
+ super().__init__(image_processor, tokenizer)
+
+ @auto_docstring
+ def __call__(
+ self,
+ images: ImageInput | None = None,
+ text: list[str] | list[list[str]] | None = None,
+ **kwargs: Unpack[OmDetTurboProcessorKwargs],
+ ) -> BatchFeature:
+ if images is None or text is None:
+ raise ValueError("You have to specify both `images` and `text`")
+
+ output_kwargs = self._merge_kwargs(
+ OmDetTurboProcessorKwargs,
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
+ **kwargs,
+ )
+
+ if isinstance(text, str):
+ text = text.strip(" ").split(",")
+
+ if not (len(text) and isinstance(text[0], (list, tuple))):
+ text = [text]
+
+ task = output_kwargs["text_kwargs"].pop("task", None)
+ if task is None:
+ task = [f"Detect {', '.join(text_single)}." for text_single in text]
+ elif not isinstance(task, (list, tuple)):
+ task = [task]
+
+ encoding_image_processor = self.image_processor(images, **output_kwargs["images_kwargs"])
+ tasks_encoding = self.tokenizer(text=task, **output_kwargs["text_kwargs"])
+
+ classes = text
+
+ classes_structure = torch.tensor([len(class_single) for class_single in classes], dtype=torch.long)
+ classes_flattened = [class_single for class_batch in classes for class_single in class_batch]
+ classes_encoding = self.tokenizer(text=classes_flattened, **output_kwargs["text_kwargs"])
+
+ encoding = BatchFeature()
+ encoding.update({f"tasks_{key}": value for key, value in tasks_encoding.items()})
+ encoding.update({f"classes_{key}": value for key, value in classes_encoding.items()})
+ encoding.update({"classes_structure": classes_structure})
+ encoding.update(encoding_image_processor)
+
+ return encoding
+
+ @property
+ def model_input_names(self):
+ image_processor_input_names = self.image_processor.model_input_names
+ tokenizer_input_names = [
+ "classes_attention_mask",
+ "tasks_attention_mask",
+ "tasks_input_ids",
+ "classes_input_ids",
+ "classes_structure",
+ ]
+ return tokenizer_input_names + image_processor_input_names
+
+ def _get_default_image_size(self) -> tuple[int, int]:
+ height = (
+ self.image_processor.size["height"]
+ if "height" in self.image_processor.size
+ else self.image_processor.size["shortest_edge"]
+ )
+ width = (
+ self.image_processor.size["width"]
+ if "width" in self.image_processor.size
+ else self.image_processor.size["longest_edge"]
+ )
+ return height, width
+
+ def post_process_grounded_object_detection(
+ self,
+ outputs: "OmDetTurboObjectDetectionOutput",
+ text_labels: list[str] | list[list[str]] | None = None,
+ threshold: float = 0.3,
+ nms_threshold: float = 0.5,
+ target_sizes: TensorType | list[tuple] | None = None,
+ max_num_det: int | None = None,
+ ):
+ """
+ Converts the raw output of [`OmDetTurboForObjectDetection`] into final bounding boxes in (top_left_x, top_left_y,
+ bottom_right_x, bottom_right_y) format and get the associated text class.
+
+ Args:
+ outputs ([`OmDetTurboObjectDetectionOutput`]):
+ Raw outputs of the model.
+ text_labels (Union[list[str], list[list[str]]], *optional*):
+ The input classes names. If not provided, `text_labels` will be set to `None` in `outputs`.
+ threshold (float, defaults to 0.3):
+ Only return detections with a confidence score exceeding this threshold.
+ nms_threshold (float, defaults to 0.5):
+ The threshold to use for box non-maximum suppression. Value in [0, 1].
+ target_sizes (`torch.Tensor` or `list[tuple[int, int]]`, *optional*):
+ Tensor of shape `(batch_size, 2)` or list of tuples (`tuple[int, int]`) containing the target size
+ `(height, width)` of each image in the batch. If unset, predictions will not be resized.
+ max_num_det (`int`, *optional*):
+ The maximum number of detections to return.
+ Returns:
+ `list[Dict]`: A list of dictionaries, each dictionary containing the scores, classes and boxes for an image
+ in the batch as predicted by the model.
+ """
+
+ batch_size = len(outputs.decoder_coord_logits)
+
+ # Inputs consistency check for target sizes
+ if target_sizes is None:
+ height, width = self._get_default_image_size()
+ target_sizes = [(height, width)] * batch_size
+
+ if any(len(image_size) != 2 for image_size in target_sizes):
+ raise ValueError(
+ "Each element of target_sizes must contain the size (height, width) of each image of the batch"
+ )
+
+ if len(target_sizes) != batch_size:
+ raise ValueError("Make sure that you pass in as many target sizes as output sequences")
+
+ # Inputs consistency check for text labels
+ if text_labels is not None and isinstance(text_labels[0], str):
+ text_labels = [text_labels]
+
+ if text_labels is not None and len(text_labels) != batch_size:
+ raise ValueError("Make sure that you pass in as many classes group as output sequences")
+
+ # Convert target_sizes to list for easier handling
+ if isinstance(target_sizes, torch.Tensor):
+ target_sizes = target_sizes.tolist()
+
+ batch_boxes = outputs.decoder_coord_logits
+ batch_logits = outputs.decoder_class_logits
+ batch_num_classes = outputs.classes_structure
+
+ batch_scores, batch_labels = compute_score(batch_logits)
+
+ results = []
+ for boxes, scores, image_size, image_num_classes in zip(
+ batch_boxes, batch_scores, target_sizes, batch_num_classes
+ ):
+ boxes, scores, labels = _post_process_boxes_for_image(
+ boxes=boxes,
+ scores=scores,
+ labels=batch_labels,
+ image_num_classes=image_num_classes,
+ image_size=image_size,
+ threshold=threshold,
+ nms_threshold=nms_threshold,
+ max_num_det=max_num_det,
+ )
+ result = {"boxes": boxes, "scores": scores, "labels": labels, "text_labels": None}
+ results.append(result)
+
+ # Add text labels
+ if text_labels is not None:
+ for result, image_text_labels in zip(results, text_labels):
+ result["text_labels"] = [image_text_labels[idx] for idx in result["labels"]]
+
+ return results
+
+
+__all__ = ["OmDetTurboProcessor"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/oneformer/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/oneformer/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..b8dcfac01991d238e12406df77467e8d0827cfae
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/oneformer/__init__.py
@@ -0,0 +1,30 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_oneformer import *
+ from .image_processing_oneformer import *
+ from .image_processing_pil_oneformer import *
+ from .modeling_oneformer import *
+ from .processing_oneformer import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/oneformer/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/oneformer/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..309077f4594c31255a9532788380ef5e48deae9d
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/oneformer/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/oneformer/__pycache__/configuration_oneformer.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/oneformer/__pycache__/configuration_oneformer.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..93d23d9d7b19f2c3428da39b9c59d231e96d748f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/oneformer/__pycache__/configuration_oneformer.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/oneformer/__pycache__/image_processing_oneformer.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/oneformer/__pycache__/image_processing_oneformer.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0e8170286f4b269d3a434e6596306086cd90ff7f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/oneformer/__pycache__/image_processing_oneformer.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/oneformer/__pycache__/image_processing_pil_oneformer.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/oneformer/__pycache__/image_processing_pil_oneformer.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c0c001fefff618cad088684c43c68e4a5daae952
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/oneformer/__pycache__/image_processing_pil_oneformer.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/oneformer/__pycache__/processing_oneformer.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/oneformer/__pycache__/processing_oneformer.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3912a9bf8c91f5ff606aedcd9bf930262553f036
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/oneformer/__pycache__/processing_oneformer.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/oneformer/configuration_oneformer.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/oneformer/configuration_oneformer.py
new file mode 100644
index 0000000000000000000000000000000000000000..f3ac0e9bae888c917994fdd80d60054edabcbd41
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/oneformer/configuration_oneformer.py
@@ -0,0 +1,158 @@
+# Copyright 2022 SHI Labs and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""OneFormer model configuration"""
+
+from huggingface_hub.dataclasses import strict
+
+from ...backbone_utils import consolidate_backbone_kwargs_to_config
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring
+from ..auto import AutoConfig
+
+
+@auto_docstring(checkpoint="shi-labs/oneformer_ade20k_swin_tiny")
+@strict
+class OneFormerConfig(PreTrainedConfig):
+ r"""
+ ignore_value (`int`, *optional*, defaults to 255):
+ Values to be ignored in GT label while calculating loss.
+ num_queries (`int`, *optional*, defaults to 150):
+ Number of object queries.
+ contrastive_weight (`float`, *optional*, defaults to 0.5):
+ Weight for contrastive loss.
+ contrastive_temperature (`float`, *optional*, defaults to 0.07):
+ Initial value for scaling the contrastive logits.
+ train_num_points (`int`, *optional*, defaults to 12544):
+ Number of points to sample while calculating losses on mask predictions.
+ oversample_ratio (`float`, *optional*, defaults to 3.0):
+ Ratio to decide how many points to oversample.
+ importance_sample_ratio (`float`, *optional*, defaults to 0.75):
+ Ratio of points that are sampled via importance sampling..
+ is_training (`bool`, *optional*, defaults to `False`):
+ Whether to run in training or inference mode.
+ output_auxiliary_logits (`bool`, *optional*, defaults to `True`):
+ Whether to return intermediate predictions from transformer decoder.
+ strides (`list`, *optional*, defaults to `[4, 8, 16, 32]`):
+ List containing the strides for feature maps in the encoder.
+ task_seq_len (`int`, *optional*, defaults to 77):
+ Sequence length for tokenizing text list input.
+ text_encoder_width (`int`, *optional*, defaults to 256):
+ Hidden size for text encoder.
+ text_encoder_context_length (`int`, *optional*, defaults to 77):
+ Input sequence length for text encoder.
+ text_encoder_num_layers (`int`, *optional*, defaults to 6):
+ Number of layers for transformer in text encoder.
+ text_encoder_vocab_size (`int`, *optional*, defaults to 49408):
+ Vocabulary size for tokenizer.
+ text_encoder_proj_layers (`int`, *optional*, defaults to 2):
+ Number of layers in MLP for project text queries.
+ text_encoder_n_ctx (`int`, *optional*, defaults to 16):
+ Number of learnable text context queries.
+ conv_dim (`int`, *optional*, defaults to 256):
+ Feature map dimension to map outputs from the backbone.
+ mask_dim (`int`, *optional*, defaults to 256):
+ Dimension for feature maps in pixel decoder.
+ hidden_dim (`int`, *optional*, defaults to 256):
+ Dimension for hidden states in transformer decoder.
+ encoder_feedforward_dim (`int`, *optional*, defaults to 1024):
+ Dimension for FFN layer in pixel decoder.
+ norm (`str`, *optional*, defaults to `"GN"`):
+ Type of normalization.
+ use_task_norm (`bool`, *optional*, defaults to `True`):
+ Whether to normalize the task token.
+ dim_feedforward (`int`, *optional*, defaults to 2048):
+ Dimension for FFN layer in transformer decoder.
+ pre_norm (`bool`, *optional*, defaults to `False`):
+ Whether to normalize hidden states before attention layers in transformer decoder.
+ enforce_input_proj (`bool`, *optional*, defaults to `False`):
+ Whether to project hidden states in transformer decoder.
+ query_dec_layers (`int`, *optional*, defaults to 2):
+ Number of layers in query transformer.
+ common_stride (`int`, *optional*, defaults to 4):
+ Common stride used for features in pixel decoder.
+
+ Examples:
+ ```python
+ >>> from transformers import OneFormerConfig, OneFormerModel
+
+ >>> # Initializing a OneFormer shi-labs/oneformer_ade20k_swin_tiny configuration
+ >>> configuration = OneFormerConfig()
+ >>> # Initializing a model (with random weights) from the shi-labs/oneformer_ade20k_swin_tiny style configuration
+ >>> model = OneFormerModel(configuration)
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```
+ """
+
+ model_type = "oneformer"
+ sub_configs = {"backbone_config": AutoConfig}
+ attribute_map = {"hidden_size": "hidden_dim", "num_hidden_layers": "decoder_layers"}
+
+ backbone_config: dict | PreTrainedConfig | None = None
+ ignore_value: int = 255
+ num_queries: int = 150
+ no_object_weight: float = 0.1
+ class_weight: float = 2.0
+ mask_weight: float = 5.0
+ dice_weight: float = 5.0
+ contrastive_weight: float = 0.5
+ contrastive_temperature: float = 0.07
+ train_num_points: int = 12544
+ oversample_ratio: float = 3.0
+ importance_sample_ratio: float = 0.75
+ init_std: float = 0.02
+ init_xavier_std: float = 1.0
+ layer_norm_eps: float = 1e-05
+ is_training: bool = False
+ use_auxiliary_loss: bool = True
+ output_auxiliary_logits: bool = True
+ strides: list[int] | tuple[int, ...] = (4, 8, 16, 32)
+ task_seq_len: int = 77
+ text_encoder_width: int = 256
+ text_encoder_context_length: int = 77
+ text_encoder_num_layers: int = 6
+ text_encoder_vocab_size: int = 49408
+ text_encoder_proj_layers: int = 2
+ text_encoder_n_ctx: int = 16
+ conv_dim: int = 256
+ mask_dim: int = 256
+ hidden_dim: int = 256
+ encoder_feedforward_dim: int = 1024
+ norm: str = "GN"
+ encoder_layers: int = 6
+ decoder_layers: int = 10
+ use_task_norm: bool = True
+ num_attention_heads: int = 8
+ dropout: float | int = 0.1
+ dim_feedforward: int = 2048
+ pre_norm: bool = False
+ enforce_input_proj: bool = False
+ query_dec_layers: int = 2
+ common_stride: int = 4
+
+ def __post_init__(self, **kwargs):
+ self.backbone_config, kwargs = consolidate_backbone_kwargs_to_config(
+ backbone_config=self.backbone_config,
+ default_config_type="swin",
+ default_config_kwargs={
+ "drop_path_rate": 0.3,
+ "out_features": ["stage1", "stage2", "stage3", "stage4"],
+ },
+ **kwargs,
+ )
+
+ super().__post_init__(**kwargs)
+
+
+__all__ = ["OneFormerConfig"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/oneformer/image_processing_oneformer.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/oneformer/image_processing_oneformer.py
new file mode 100644
index 0000000000000000000000000000000000000000..ccee798bc39ec853f11f6e6fc4d7c5413cc952da
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/oneformer/image_processing_oneformer.py
@@ -0,0 +1,969 @@
+# Copyright 2025 SHI Labs and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Image processor class for OneFormer."""
+
+import json
+import os
+from typing import Union
+
+import torch
+from torch import nn
+from torchvision.transforms.v2 import functional as tvF
+
+from ...image_processing_backends import TorchvisionBackend
+from ...image_processing_utils import BatchFeature
+from ...image_transforms import group_images_by_shape, reorder_images
+from ...image_utils import (
+ IMAGENET_DEFAULT_MEAN,
+ IMAGENET_DEFAULT_STD,
+ ChannelDimension,
+ ImageInput,
+ PILImageResampling,
+ SizeDict,
+ get_max_height_width,
+)
+from ...processing_utils import ImagesKwargs, Unpack
+from ...utils import (
+ TensorType,
+ auto_docstring,
+ logging,
+)
+
+
+try:
+ from huggingface_hub import hf_hub_download
+ from huggingface_hub.utils import RepositoryNotFoundError
+except ImportError:
+ hf_hub_download = None
+ RepositoryNotFoundError = None
+
+
+logger = logging.get_logger(__name__)
+
+
+class OneFormerImageProcessorKwargs(ImagesKwargs, total=False):
+ r"""
+ repo_path (`str`, *optional*, defaults to `shi-labs/oneformer_demo`):
+ Path to a local directory or HuggingFace Hub repository containing model metadata.
+ class_info_file (`str`, *optional*):
+ Path to the JSON file within the repository that contains class metadata.
+ num_text (`int`, *optional*):
+ Number of text queries for the text encoder, used as task-guiding prompts.
+ num_labels (`int`, *optional*):
+ Number of semantic classes for segmentation, determining the output layer's size.
+ ignore_index (`int`, *optional*):
+ Label to ignore in segmentation maps, often used for padding.
+ do_reduce_labels (`bool`, *optional*, defaults to `False`):
+ Whether to decrement all label values by 1, mapping the background class to `ignore_index`.
+ """
+
+ repo_path: str | None
+ class_info_file: str | None
+ num_text: int | None
+ num_labels: int | None
+ ignore_index: int | None
+ do_reduce_labels: bool
+
+
+def prepare_metadata(class_info):
+ metadata = {}
+ class_names = []
+ thing_ids = []
+ for key, info in class_info.items():
+ metadata[key] = info["name"]
+ class_names.append(info["name"])
+ if info["isthing"]:
+ thing_ids.append(int(key))
+ metadata["thing_ids"] = thing_ids
+ metadata["class_names"] = class_names
+ return metadata
+
+
+def load_metadata(repo_id, class_info_file):
+ fname = os.path.join("" if repo_id is None else repo_id, class_info_file)
+
+ if not os.path.exists(fname) or not os.path.isfile(fname):
+ if repo_id is None:
+ raise ValueError(f"Could not file {fname} locally. repo_id must be defined if loading from the hub")
+ if hf_hub_download is None:
+ raise ImportError(
+ "huggingface_hub is required to download metadata files. Install it with `pip install huggingface_hub`"
+ )
+ # We try downloading from a dataset by default for backward compatibility
+ try:
+ fname = hf_hub_download(repo_id, class_info_file, repo_type="dataset")
+ except RepositoryNotFoundError:
+ fname = hf_hub_download(repo_id, class_info_file)
+
+ with open(fname, "r") as f:
+ class_info = json.load(f)
+
+ return class_info
+
+
+def make_pixel_mask(image: "torch.Tensor", output_size: tuple[int, int]) -> "torch.Tensor":
+ """
+ Make a pixel mask for the image, where 1 indicates a valid pixel and 0 indicates padding.
+
+ Args:
+ image (`torch.Tensor`):
+ Image to make the pixel mask for.
+ output_size (`Tuple[int, int]`):
+ Output size of the mask.
+ """
+
+ input_height, input_width = image.shape[-2], image.shape[-1]
+ mask = torch.zeros(output_size, dtype=torch.int64)
+ mask[:input_height, :input_width] = 1
+ return mask
+
+
+def binary_mask_to_rle(mask):
+ """
+ Converts given binary mask of shape `(height, width)` to the run-length encoding (RLE) format.
+
+ Args:
+ mask (`torch.Tensor` or `numpy.array`):
+ A binary mask tensor of shape `(height, width)` where 0 denotes background and 1 denotes the target
+ segment_id or class_id.
+ Returns:
+ `List`: Run-length encoded list of the binary mask. Refer to COCO API for more information about the RLE
+ format.
+ """
+ import numpy as np
+
+ # Convert to torch tensor if numpy array
+ if isinstance(mask, np.ndarray):
+ mask = torch.from_numpy(mask)
+
+ pixels = mask.flatten()
+ pixels = torch.concat(
+ [
+ torch.tensor([0], device=pixels.device, dtype=pixels.dtype),
+ pixels,
+ torch.tensor([0], device=pixels.device, dtype=pixels.dtype),
+ ]
+ )
+ runs = torch.where(pixels[1:] != pixels[:-1])[0] + 1
+ runs[1::2] -= runs[::2]
+ return list(runs)
+
+
+def convert_segmentation_to_rle(segmentation):
+ """
+ Converts given segmentation map of shape `(height, width)` to the run-length encoding (RLE) format.
+
+ Args:
+ segmentation (`torch.Tensor` or `numpy.array`):
+ A segmentation map of shape `(height, width)` where each value denotes a segment or class id.
+ Returns:
+ `List[List]`: A list of lists, where each list is the run-length encoding of a segment / class id.
+ """
+ segment_ids = torch.unique(segmentation)
+
+ run_length_encodings = []
+ for idx in segment_ids:
+ mask = torch.where(segmentation == idx, 1, 0)
+ rle = binary_mask_to_rle(mask)
+ run_length_encodings.append(rle)
+
+ return run_length_encodings
+
+
+def remove_low_and_no_objects(masks, scores, labels, object_mask_threshold, num_labels):
+ """
+ Binarize the given masks using `object_mask_threshold`, it returns the associated values of `masks`, `scores` and
+ `labels`.
+
+ Args:
+ masks (`torch.Tensor`):
+ A tensor of shape `(num_queries, height, width)`.
+ scores (`torch.Tensor`):
+ A tensor of shape `(num_queries)`.
+ labels (`torch.Tensor`):
+ A tensor of shape `(num_queries)`.
+ object_mask_threshold (`float`):
+ A number between 0 and 1 used to binarize the masks.
+ Raises:
+ `ValueError`: Raised when the first dimension doesn't match in all input tensors.
+ Returns:
+ `Tuple[`torch.Tensor`, `torch.Tensor`, `torch.Tensor`]`: The `masks`, `scores` and `labels` without the region
+ < `object_mask_threshold`.
+ """
+ if not (masks.shape[0] == scores.shape[0] == labels.shape[0]):
+ raise ValueError("mask, scores and labels must have the same shape!")
+
+ to_keep = labels.ne(num_labels) & (scores > object_mask_threshold)
+
+ return masks[to_keep], scores[to_keep], labels[to_keep]
+
+
+def check_segment_validity(mask_labels, mask_probs, k, mask_threshold=0.5, overlap_mask_area_threshold=0.8):
+ # Get the mask associated with the k class
+ mask_k = mask_labels == k
+ mask_k_area = mask_k.sum()
+
+ # Compute the area of all the stuff in query k
+ original_area = (mask_probs[k] >= mask_threshold).sum()
+ mask_exists = mask_k_area > 0 and original_area > 0
+
+ # Eliminate disconnected tiny segments
+ if mask_exists:
+ area_ratio = mask_k_area / original_area
+ if not area_ratio.item() > overlap_mask_area_threshold:
+ mask_exists = False
+
+ return mask_exists, mask_k
+
+
+def compute_segments(
+ mask_probs,
+ pred_scores,
+ pred_labels,
+ mask_threshold: float = 0.5,
+ overlap_mask_area_threshold: float = 0.8,
+ label_ids_to_fuse: set[int] | None = None,
+ target_size: tuple[int, int] | None = None,
+):
+ height = mask_probs.shape[1] if target_size is None else target_size[0]
+ width = mask_probs.shape[2] if target_size is None else target_size[1]
+
+ segmentation = torch.zeros((height, width), dtype=torch.int32, device=mask_probs.device)
+ segments: list[dict] = []
+
+ if target_size is not None:
+ mask_probs = tvF.resize(
+ mask_probs.unsqueeze(0),
+ size=target_size,
+ interpolation=tvF.InterpolationMode.BILINEAR,
+ )[0]
+
+ current_segment_id = 0
+
+ mask_probs *= pred_scores.view(-1, 1, 1)
+ mask_labels = mask_probs.argmax(0) # [height, width]
+
+ stuff_memory_list: dict[str, int] = {}
+ for k in range(pred_labels.shape[0]):
+ pred_class = pred_labels[k].item()
+ should_fuse = pred_class in label_ids_to_fuse
+
+ mask_exists, mask_k = check_segment_validity(
+ mask_labels, mask_probs, k, mask_threshold, overlap_mask_area_threshold
+ )
+
+ if mask_exists:
+ if pred_class in stuff_memory_list:
+ current_segment_id = stuff_memory_list[pred_class]
+ else:
+ current_segment_id += 1
+
+ segmentation[mask_k] = current_segment_id
+ segment_score = round(pred_scores[k].item(), 6)
+ segments.append(
+ {
+ "id": current_segment_id,
+ "label_id": pred_class,
+ "was_fused": should_fuse,
+ "score": segment_score,
+ }
+ )
+ if should_fuse:
+ stuff_memory_list[pred_class] = current_segment_id
+
+ return segmentation, segments
+
+
+@auto_docstring
+class OneFormerImageProcessor(TorchvisionBackend):
+ resample = PILImageResampling.BILINEAR
+ image_mean = IMAGENET_DEFAULT_MEAN
+ image_std = IMAGENET_DEFAULT_STD
+ size = {"shortest_edge": 800, "longest_edge": 1333}
+ crop_size = None
+ do_resize = True
+ do_rescale = True
+ do_normalize = True
+ default_to_square = False
+ do_center_crop = False
+ do_convert_rgb = True
+ rescale_factor = 1 / 255
+ ignore_index = None
+ do_reduce_labels = False
+ repo_path = "shi-labs/oneformer_demo"
+ class_info_file = None
+ num_text = None
+ num_labels = None
+ valid_kwargs = OneFormerImageProcessorKwargs
+ model_input_names = ["pixel_values", "pixel_mask", "task_inputs"]
+
+ def __init__(self, **kwargs: Unpack[OneFormerImageProcessorKwargs]):
+ super().__init__(**kwargs)
+ if self.class_info_file:
+ self.metadata = prepare_metadata(load_metadata(self.repo_path, self.class_info_file))
+
+ @auto_docstring
+ def preprocess(
+ self,
+ images: ImageInput,
+ task_inputs: list[str] | None = None,
+ segmentation_maps: ImageInput | None = None,
+ instance_id_to_semantic_id: list[dict[int, int]] | dict[int, int] | None = None,
+ **kwargs: Unpack[OneFormerImageProcessorKwargs],
+ ) -> BatchFeature:
+ r"""
+ task_inputs (`list[str]`, *optional*):
+ List of tasks (`"panoptic"`, `"instance"`, `"semantic"`) for each image in the batch.
+ segmentation_maps (`ImageInput`, *optional*):
+ The segmentation maps.
+ instance_id_to_semantic_id (`Union[list[dict[int, int]], dict[int, int]]`, *optional*):
+ A mapping from instance IDs to semantic IDs.
+ """
+ return super().preprocess(images, task_inputs, segmentation_maps, instance_id_to_semantic_id, **kwargs)
+
+ def _preprocess_image_like_inputs(
+ self,
+ images: ImageInput,
+ task_inputs: list[str] | None,
+ segmentation_maps: ImageInput,
+ instance_id_to_semantic_id: list[dict[int, int]] | dict[int, int] | None,
+ do_convert_rgb: bool,
+ input_data_format: ChannelDimension,
+ device: Union[str, "torch.device"] | None = None,
+ **kwargs: Unpack[OneFormerImageProcessorKwargs],
+ ) -> BatchFeature:
+ """
+ Preprocess image-like inputs.
+ To be overridden by subclasses when image-like inputs other than images should be processed.
+ It can be used for segmentation maps, depth maps, etc.
+ """
+ # Prepare input images
+ images = self._prepare_image_like_inputs(
+ images=images, do_convert_rgb=do_convert_rgb, input_data_format=input_data_format, device=device
+ )
+ if segmentation_maps is not None:
+ segmentation_maps = self._prepare_image_like_inputs(
+ images=segmentation_maps,
+ expected_ndims=2,
+ do_convert_rgb=False,
+ input_data_format=ChannelDimension.FIRST,
+ )
+ return self._preprocess(images, task_inputs, segmentation_maps, instance_id_to_semantic_id, **kwargs)
+
+ def _preprocess(
+ self,
+ images: list["torch.Tensor"],
+ task_inputs: list[str] | None,
+ segmentation_maps: list["torch.Tensor"],
+ instance_id_to_semantic_id: list[dict[int, int]] | dict[int, int] | None,
+ do_resize: bool,
+ size: SizeDict,
+ resample: "PILImageResampling | tvF.InterpolationMode | int | None",
+ do_rescale: bool,
+ rescale_factor: float,
+ do_normalize: bool,
+ image_mean: float | list[float] | None,
+ image_std: float | list[float] | None,
+ ignore_index: int | None,
+ do_reduce_labels: bool | None,
+ disable_grouping: bool | None,
+ return_tensors: str | TensorType | None,
+ **kwargs,
+ ) -> BatchFeature:
+ grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping)
+
+ processed_images_grouped = {}
+
+ for shape, stacked_images in grouped_images.items():
+ if do_resize:
+ stacked_images = self.resize(image=stacked_images, size=size, resample=resample)
+ stacked_images = self.rescale_and_normalize(
+ stacked_images, do_rescale, rescale_factor, do_normalize, image_mean, image_std
+ )
+ processed_images_grouped[shape] = stacked_images
+ processed_images = reorder_images(processed_images_grouped, grouped_images_index)
+
+ processed_segmentation_maps = None
+ if segmentation_maps is not None:
+ grouped_segmentation_maps, grouped_segmentation_maps_index = group_images_by_shape(
+ segmentation_maps, disable_grouping=disable_grouping
+ )
+ processed_segmentation_maps_grouped = {}
+ for shape, stacked_segmentation_maps in grouped_segmentation_maps.items():
+ if do_resize:
+ stacked_segmentation_maps = self.resize(
+ stacked_segmentation_maps, size=size, resample=tvF.InterpolationMode.NEAREST_EXACT
+ )
+ processed_segmentation_maps_grouped[shape] = stacked_segmentation_maps
+ processed_segmentation_maps = reorder_images(
+ processed_segmentation_maps_grouped, grouped_segmentation_maps_index
+ )
+
+ encoded_inputs = self.encode_inputs(
+ processed_images,
+ task_inputs,
+ segmentation_maps=processed_segmentation_maps,
+ instance_id_to_semantic_id=instance_id_to_semantic_id,
+ ignore_index=ignore_index,
+ do_reduce_labels=do_reduce_labels,
+ return_tensors=return_tensors,
+ )
+
+ return encoded_inputs
+
+ def _pad_image(
+ self,
+ image: "torch.Tensor",
+ output_size: tuple[int, int],
+ constant_values: float = 0,
+ ) -> "torch.Tensor":
+ """
+ Pad an image with zeros to the given size using torch operations.
+
+ Args:
+ image (`torch.Tensor`):
+ Image tensor in channel-first format (C, H, W).
+ output_size (`tuple[int, int]`):
+ Target output size (height, width).
+ constant_values (`float`, *optional*, defaults to 0):
+ The value to use for padding.
+
+ Returns:
+ `torch.Tensor`: The padded image.
+ """
+ input_height, input_width = image.shape[1], image.shape[2]
+ output_height, output_width = output_size
+
+ pad_bottom = output_height - input_height
+ pad_right = output_width - input_width
+
+ padded_image = tvF.pad(image, padding=[0, 0, pad_right, pad_bottom], fill=constant_values)
+
+ return padded_image
+
+ def pad(
+ self,
+ images: list["torch.Tensor"],
+ return_pixel_mask: bool = True,
+ return_tensors: str | TensorType | None = None,
+ ) -> BatchFeature:
+ """
+ Pad a batch of images to the same size using torch operations.
+
+ Args:
+ images (`List[torch.Tensor]`):
+ List of image tensors in channel-first format.
+ return_pixel_mask (`bool`, *optional*, defaults to `True`):
+ Whether to return pixel masks.
+ return_tensors (`str` or `TensorType`, *optional*):
+ The type of tensors to return.
+
+ Returns:
+ `BatchFeature`: Padded images and optional pixel masks.
+ """
+ outputs = super().pad(images, return_mask=return_pixel_mask)
+ padded_images = outputs[0] if return_pixel_mask else outputs
+ pixel_masks = outputs[1] if return_pixel_mask else None
+
+ if return_tensors:
+ padded_images = torch.stack(padded_images, dim=0)
+ if return_pixel_mask:
+ pixel_masks = torch.stack(pixel_masks, dim=0)
+
+ data = {"pixel_values": padded_images}
+ if return_pixel_mask:
+ data["pixel_mask"] = pixel_masks
+
+ return BatchFeature(data=data, tensor_type=return_tensors)
+
+ def convert_segmentation_map_to_binary_masks(
+ self,
+ segmentation_map: "torch.Tensor",
+ instance_id_to_semantic_id: dict[int, int] | None = None,
+ ignore_index: int | None = None,
+ do_reduce_labels: bool = False,
+ ):
+ if do_reduce_labels and ignore_index is None:
+ raise ValueError("If `do_reduce_labels` is True, `ignore_index` must be provided.")
+
+ if do_reduce_labels:
+ segmentation_map = torch.where(segmentation_map == 0, ignore_index, segmentation_map - 1)
+
+ all_labels = torch.unique(segmentation_map)
+
+ if ignore_index is not None:
+ all_labels = all_labels[all_labels != ignore_index]
+
+ binary_masks = [(segmentation_map == i) for i in all_labels]
+
+ if binary_masks:
+ binary_masks = torch.stack(binary_masks, dim=0)
+ else:
+ binary_masks = torch.zeros((0, *segmentation_map.shape), device=segmentation_map.device)
+
+ # Convert instance ids to class ids
+ if instance_id_to_semantic_id is not None:
+ labels = torch.zeros(all_labels.shape[0], device=segmentation_map.device)
+
+ for i, label in enumerate(all_labels):
+ class_id = instance_id_to_semantic_id[(label.item() + 1 if do_reduce_labels else label.item())]
+ labels[i] = class_id - 1 if do_reduce_labels else class_id
+ else:
+ labels = all_labels
+
+ return (
+ binary_masks.float(),
+ labels.long(),
+ )
+
+ def get_semantic_annotations(self, label, num_class_obj):
+ annotation_classes = label["classes"]
+ annotation_masks = label["masks"]
+
+ texts = ["a semantic photo"] * self.num_text
+ classes = []
+ masks = []
+
+ for idx in range(len(annotation_classes)):
+ class_id = annotation_classes[idx]
+ mask = annotation_masks[idx]
+ if not torch.all(mask == 0):
+ if class_id not in classes:
+ cls_name = self.metadata[str(class_id.cpu().item())]
+ classes.append(class_id)
+ masks.append(mask)
+ num_class_obj[cls_name] += 1
+ else:
+ idx = classes.index(class_id)
+ masks[idx] += mask
+ masks[idx] = torch.clamp(masks[idx], 0, 1)
+
+ num = 0
+ for i, cls_name in enumerate(self.metadata["class_names"]):
+ if num_class_obj[cls_name] > 0:
+ for _ in range(num_class_obj[cls_name]):
+ if num >= len(texts):
+ break
+ texts[num] = f"a photo with a {cls_name}"
+ num += 1
+
+ classes = torch.stack(classes)
+ masks = torch.stack(masks)
+ return classes, masks, texts
+
+ def get_instance_annotations(self, label, num_class_obj):
+ annotation_classes = label["classes"]
+ annotation_masks = label["masks"]
+
+ texts = ["an instance photo"] * self.num_text
+ classes = []
+ masks = []
+
+ for idx in range(len(annotation_classes)):
+ class_id = annotation_classes[idx]
+ mask = annotation_masks[idx]
+
+ if class_id in self.metadata["thing_ids"]:
+ if not torch.all(mask == 0):
+ cls_name = self.metadata[str(class_id.cpu().item())]
+ classes.append(class_id)
+ masks.append(mask)
+ num_class_obj[cls_name] += 1
+
+ num = 0
+ for i, cls_name in enumerate(self.metadata["class_names"]):
+ if num_class_obj[cls_name] > 0:
+ for _ in range(num_class_obj[cls_name]):
+ if num >= len(texts):
+ break
+ texts[num] = f"a photo with a {cls_name}"
+ num += 1
+
+ classes = torch.stack(classes)
+ masks = torch.stack(masks)
+ return classes, masks, texts
+
+ def get_panoptic_annotations(self, label, num_class_obj):
+ annotation_classes = label["classes"]
+ annotation_masks = label["masks"]
+
+ texts = ["an panoptic photo"] * self.num_text
+ classes = []
+ masks = []
+ for idx in range(len(annotation_classes)):
+ class_id = annotation_classes[idx]
+ mask = annotation_masks[idx] if hasattr(annotation_masks[idx], "data") else annotation_masks[idx]
+ if not torch.all(mask == 0):
+ cls_name = self.metadata[str(class_id.cpu().item())]
+ classes.append(class_id)
+ masks.append(mask)
+ num_class_obj[cls_name] += 1
+
+ num = 0
+ for i, cls_name in enumerate(self.metadata["class_names"]):
+ if num_class_obj[cls_name] > 0:
+ for _ in range(num_class_obj[cls_name]):
+ if num >= len(texts):
+ break
+ texts[num] = f"a photo with a {cls_name}"
+ num += 1
+
+ classes = torch.stack(classes)
+ masks = torch.stack(masks)
+ return classes, masks, texts
+
+ def encode_inputs(
+ self,
+ pixel_values_list: list["ImageInput"],
+ task_inputs: list[str] | None = None,
+ segmentation_maps: list["ImageInput"] | None = None,
+ instance_id_to_semantic_id: list[dict[int, int]] | dict[int, int] | None = None,
+ ignore_index: int | None = None,
+ do_reduce_labels: bool = False,
+ return_tensors: str | TensorType | None = None,
+ ) -> BatchFeature:
+ ignore_index = self.ignore_index if ignore_index is None else ignore_index
+ do_reduce_labels = self.do_reduce_labels if do_reduce_labels is None else do_reduce_labels
+ if task_inputs is None:
+ task_inputs = ["panoptic"]
+ pixel_values_list = self._prepare_image_like_inputs(
+ pixel_values_list, input_data_format=ChannelDimension.FIRST
+ )
+ if segmentation_maps is not None:
+ segmentation_maps = self._prepare_image_like_inputs(
+ images=segmentation_maps,
+ expected_ndims=2,
+ do_convert_rgb=False,
+ input_data_format=ChannelDimension.FIRST,
+ )
+ pad_size = get_max_height_width(pixel_values_list)
+ encoded_inputs = self.pad(pixel_values_list, return_tensors=return_tensors)
+
+ annotations = None
+ if segmentation_maps is not None:
+ annotations = []
+ for idx, segmentation_map in enumerate(segmentation_maps):
+ # Use instance2class_id mapping per image
+ if isinstance(instance_id_to_semantic_id, list):
+ instance_id = instance_id_to_semantic_id[idx]
+ else:
+ instance_id = instance_id_to_semantic_id
+
+ # Convert segmentation map to binary masks using torch operations
+ masks, classes = self.convert_segmentation_map_to_binary_masks(
+ segmentation_map,
+ instance_id,
+ ignore_index=ignore_index,
+ do_reduce_labels=do_reduce_labels,
+ )
+
+ annotations.append({"masks": masks, "classes": classes})
+
+ if annotations is not None:
+ mask_labels = []
+ class_labels = []
+ text_inputs = []
+ num_class_obj = dict.fromkeys(self.metadata["class_names"], 0)
+
+ for i, label in enumerate(annotations):
+ task = task_inputs[i]
+
+ if task == "semantic":
+ classes, masks, texts = self.get_semantic_annotations(label, num_class_obj)
+ elif task == "instance":
+ classes, masks, texts = self.get_instance_annotations(label, num_class_obj)
+ elif task == "panoptic":
+ classes, masks, texts = self.get_panoptic_annotations(label, num_class_obj)
+ else:
+ raise ValueError(f"{task} was not expected, expected `semantic`, `instance` or `panoptic`")
+ # Pad masks to max size using torch operations
+ padded_masks = [
+ self._pad_image(image=mask, output_size=pad_size, constant_values=ignore_index) for mask in masks
+ ]
+ padded_masks = torch.cat(padded_masks, dim=0)
+ mask_labels.append(padded_masks)
+ class_labels.append(classes)
+ text_inputs.append(texts)
+
+ encoded_inputs["mask_labels"] = mask_labels
+ encoded_inputs["class_labels"] = class_labels
+ encoded_inputs["text_inputs"] = text_inputs
+
+ encoded_inputs["task_inputs"] = [f"the task is {task_input}" for task_input in task_inputs]
+ return encoded_inputs
+
+ def post_process_semantic_segmentation(
+ self, outputs, target_sizes: list[tuple[int, int]] | None = None
+ ) -> "torch.Tensor":
+ """
+ Converts the output of [`MaskFormerForInstanceSegmentation`] into semantic segmentation maps. Only supports
+ PyTorch.
+
+ Args:
+ outputs ([`MaskFormerForInstanceSegmentation`]):
+ Raw outputs of the model.
+ target_sizes (`List[Tuple[int, int]]`, *optional*):
+ List of length (batch_size), where each list item (`Tuple[int, int]]`) corresponds to the requested
+ final size (height, width) of each prediction. If left to None, predictions will not be resized.
+ Returns:
+ `List[torch.Tensor]`:
+ A list of length `batch_size`, where each item is a semantic segmentation map of shape (height, width)
+ corresponding to the target_sizes entry (if `target_sizes` is specified). Each entry of each
+ `torch.Tensor` correspond to a semantic class id.
+ """
+ class_queries_logits = outputs.class_queries_logits # [batch_size, num_queries, num_classes+1]
+ masks_queries_logits = outputs.masks_queries_logits # [batch_size, num_queries, height, width]
+
+ # Remove the null class `[..., :-1]`
+ masks_classes = class_queries_logits.softmax(dim=-1)[..., :-1]
+ masks_probs = masks_queries_logits.sigmoid() # [batch_size, num_queries, height, width]
+
+ # Semantic segmentation logits of shape (batch_size, num_classes, height, width)
+ segmentation = torch.einsum("bqc, bqhw -> bchw", masks_classes, masks_probs)
+ batch_size = class_queries_logits.shape[0]
+
+ # Resize logits and compute semantic segmentation maps
+ if target_sizes is not None:
+ if batch_size != len(target_sizes):
+ raise ValueError(
+ "Make sure that you pass in as many target sizes as the batch dimension of the logits"
+ )
+
+ semantic_segmentation = []
+ for idx in range(batch_size):
+ resized_logits = tvF.resize(
+ segmentation[idx].unsqueeze(dim=0),
+ size=target_sizes[idx],
+ interpolation=tvF.InterpolationMode.BILINEAR,
+ )
+ semantic_map = resized_logits[0].argmax(dim=0)
+ semantic_segmentation.append(semantic_map)
+ else:
+ semantic_segmentation = segmentation.argmax(dim=1)
+ semantic_segmentation = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0])]
+
+ return semantic_segmentation
+
+ def post_process_instance_segmentation(
+ self,
+ outputs,
+ task_type: str = "instance",
+ is_demo: bool = True,
+ threshold: float = 0.5,
+ mask_threshold: float = 0.5,
+ overlap_mask_area_threshold: float = 0.8,
+ target_sizes: list[tuple[int, int]] | None = None,
+ return_coco_annotation: bool | None = False,
+ ):
+ """
+ Converts the output of [`OneFormerForUniversalSegmentationOutput`] into image instance segmentation
+ predictions. Only supports PyTorch.
+
+ Args:
+ outputs ([`OneFormerForUniversalSegmentationOutput`]):
+ The outputs from [`OneFormerForUniversalSegmentationOutput`].
+ task_type (`str`, *optional*, defaults to "instance"):
+ The post processing depends on the task token input. If the `task_type` is "panoptic", we need to
+ ignore the stuff predictions.
+ is_demo (`bool`, *optional)*, defaults to `True`):
+ Whether the model is in demo mode. If true, use threshold to predict final masks.
+ threshold (`float`, *optional*, defaults to 0.5):
+ The probability score threshold to keep predicted instance masks.
+ mask_threshold (`float`, *optional*, defaults to 0.5):
+ Threshold to use when turning the predicted masks into binary values.
+ overlap_mask_area_threshold (`float`, *optional*, defaults to 0.8):
+ The overlap mask area threshold to merge or discard small disconnected parts within each binary
+ instance mask.
+ target_sizes (`List[Tuple]`, *optional*):
+ List of length (batch_size), where each list item (`Tuple[int, int]]`) corresponds to the requested
+ final size (height, width) of each prediction in batch. If left to None, predictions will not be
+ resized.
+ return_coco_annotation (`bool`, *optional)*, defaults to `False`):
+ Whether to return predictions in COCO format.
+
+ Returns:
+ `List[Dict]`: A list of dictionaries, one per image, each dictionary containing two keys:
+ - **segmentation** -- a tensor of shape `(height, width)` where each pixel represents a `segment_id`, set
+ to `None` if no mask if found above `threshold`. If `target_sizes` is specified, segmentation is resized
+ to the corresponding `target_sizes` entry.
+ - **segments_info** -- A dictionary that contains additional information on each segment.
+ - **id** -- an integer representing the `segment_id`.
+ - **label_id** -- An integer representing the label / semantic class id corresponding to `segment_id`.
+ - **was_fused** -- a boolean, `True` if `label_id` was in `label_ids_to_fuse`, `False` otherwise.
+ Multiple instances of the same class / label were fused and assigned a single `segment_id`.
+ - **score** -- Prediction score of segment with `segment_id`.
+ """
+ class_queries_logits = outputs.class_queries_logits # [batch_size, num_queries, num_classes+1]
+ masks_queries_logits = outputs.masks_queries_logits # [batch_size, num_queries, height, width]
+
+ device = masks_queries_logits.device
+ batch_size = class_queries_logits.shape[0]
+ num_queries = class_queries_logits.shape[1]
+ num_classes = class_queries_logits.shape[-1] - 1
+
+ # Loop over items in batch size
+ results: list[dict[str, torch.Tensor]] = []
+
+ for i in range(batch_size):
+ # [Q, K]
+ scores = nn.functional.softmax(class_queries_logits[i], dim=-1)[:, :-1]
+ labels = torch.arange(num_classes, device=device).unsqueeze(0).repeat(num_queries, 1).flatten(0, 1)
+
+ # scores_per_image, topk_indices = scores.flatten(0, 1).topk(self.num_queries, sorted=False)
+ scores_per_image, topk_indices = scores.flatten(0, 1).topk(num_queries, sorted=False)
+ labels_per_image = labels[topk_indices]
+
+ topk_indices = torch.div(topk_indices, num_classes, rounding_mode="floor")
+ # mask_pred = mask_pred.unsqueeze(1).repeat(1, self.sem_seg_head.num_classes, 1).flatten(0, 1)
+ mask_pred = masks_queries_logits[i][topk_indices]
+
+ # Only consider scores with confidence over [threshold] for demo
+ if is_demo:
+ keep = scores_per_image > threshold
+ scores_per_image = scores_per_image[keep]
+ labels_per_image = labels_per_image[keep]
+ mask_pred = mask_pred[keep]
+
+ # if this is panoptic segmentation, we only keep the "thing" classes
+ if task_type == "panoptic":
+ keep = torch.zeros_like(scores_per_image).bool()
+ for j, lab in enumerate(labels_per_image):
+ keep[j] = lab in self.metadata["thing_ids"]
+
+ scores_per_image = scores_per_image[keep]
+ labels_per_image = labels_per_image[keep]
+ mask_pred = mask_pred[keep]
+
+ if mask_pred.shape[0] <= 0:
+ height, width = target_sizes[i] if target_sizes is not None else mask_pred.shape[1:]
+ segmentation = torch.zeros((height, width)) - 1
+ results.append({"segmentation": segmentation, "segments_info": []})
+ continue
+
+ if "ade20k" in self.class_info_file and not is_demo and "instance" in task_type:
+ for j in range(labels_per_image.shape[0]):
+ labels_per_image[j] = self.metadata["thing_ids"].index(labels_per_image[j].item())
+
+ # Get segmentation map and segment information of batch item
+ target_size = target_sizes[i] if target_sizes is not None else None
+ segmentation, segments = compute_segments(
+ mask_pred,
+ scores_per_image,
+ labels_per_image,
+ mask_threshold,
+ overlap_mask_area_threshold,
+ set(),
+ target_size,
+ )
+
+ # Return segmentation map in run-length encoding (RLE) format
+ if return_coco_annotation:
+ segmentation = convert_segmentation_to_rle(segmentation)
+
+ results.append({"segmentation": segmentation, "segments_info": segments})
+ return results
+
+ # Copied from transformers.models.maskformer.image_processing_maskformer.MaskFormerImageProcessor.post_process_panoptic_segmentation
+ def post_process_panoptic_segmentation(
+ self,
+ outputs,
+ threshold: float = 0.5,
+ mask_threshold: float = 0.5,
+ overlap_mask_area_threshold: float = 0.8,
+ label_ids_to_fuse: set[int] | None = None,
+ target_sizes: list[tuple[int, int]] | None = None,
+ ) -> list[dict]:
+ """
+ Converts the output of [`MaskFormerForInstanceSegmentationOutput`] into image panoptic segmentation
+ predictions. Only supports PyTorch.
+
+ Args:
+ outputs ([`MaskFormerForInstanceSegmentationOutput`]):
+ The outputs from [`MaskFormerForInstanceSegmentation`].
+ threshold (`float`, *optional*, defaults to 0.5):
+ The probability score threshold to keep predicted instance masks.
+ mask_threshold (`float`, *optional*, defaults to 0.5):
+ Threshold to use when turning the predicted masks into binary values.
+ overlap_mask_area_threshold (`float`, *optional*, defaults to 0.8):
+ The overlap mask area threshold to merge or discard small disconnected parts within each binary
+ instance mask.
+ label_ids_to_fuse (`Set[int]`, *optional*):
+ The labels in this state will have all their instances be fused together. For instance we could say
+ there can only be one sky in an image, but several persons, so the label ID for sky would be in that
+ set, but not the one for person.
+ target_sizes (`list[Tuple]`, *optional*):
+ List of length (batch_size), where each list item (`tuple[int, int]]`) corresponds to the requested
+ final size (height, width) of each prediction in batch. If left to None, predictions will not be
+ resized.
+
+ Returns:
+ `list[Dict]`: A list of dictionaries, one per image, each dictionary containing two keys:
+ - **segmentation** -- a tensor of shape `(height, width)` where each pixel represents a `segment_id`, set
+ to `None` if no mask if found above `threshold`. If `target_sizes` is specified, segmentation is resized
+ to the corresponding `target_sizes` entry.
+ - **segments_info** -- A dictionary that contains additional information on each segment.
+ - **id** -- an integer representing the `segment_id`.
+ - **label_id** -- An integer representing the label / semantic class id corresponding to `segment_id`.
+ - **was_fused** -- a boolean, `True` if `label_id` was in `label_ids_to_fuse`, `False` otherwise.
+ Multiple instances of the same class / label were fused and assigned a single `segment_id`.
+ - **score** -- Prediction score of segment with `segment_id`.
+ """
+
+ if label_ids_to_fuse is None:
+ logger.warning("`label_ids_to_fuse` unset. No instance will be fused.")
+ label_ids_to_fuse = set()
+
+ class_queries_logits = outputs.class_queries_logits # [batch_size, num_queries, num_classes+1]
+ masks_queries_logits = outputs.masks_queries_logits # [batch_size, num_queries, height, width]
+
+ batch_size = class_queries_logits.shape[0]
+ num_labels = class_queries_logits.shape[-1] - 1
+
+ mask_probs = masks_queries_logits.sigmoid() # [batch_size, num_queries, height, width]
+
+ # Predicted label and score of each query (batch_size, num_queries)
+ pred_scores, pred_labels = nn.functional.softmax(class_queries_logits, dim=-1).max(-1)
+
+ # Loop over items in batch size
+ results: list[dict[str, TensorType]] = []
+
+ for i in range(batch_size):
+ mask_probs_item, pred_scores_item, pred_labels_item = remove_low_and_no_objects(
+ mask_probs[i], pred_scores[i], pred_labels[i], threshold, num_labels
+ )
+
+ # No mask found
+ if mask_probs_item.shape[0] <= 0:
+ height, width = target_sizes[i] if target_sizes is not None else mask_probs_item.shape[1:]
+ segmentation = torch.zeros((height, width)) - 1
+ results.append({"segmentation": segmentation, "segments_info": []})
+ continue
+
+ # Get segmentation map and segment information of batch item
+ target_size = target_sizes[i] if target_sizes is not None else None
+ segmentation, segments = compute_segments(
+ mask_probs=mask_probs_item,
+ pred_scores=pred_scores_item,
+ pred_labels=pred_labels_item,
+ mask_threshold=mask_threshold,
+ overlap_mask_area_threshold=overlap_mask_area_threshold,
+ label_ids_to_fuse=label_ids_to_fuse,
+ target_size=target_size,
+ )
+
+ results.append({"segmentation": segmentation, "segments_info": segments})
+ return results
+
+
+__all__ = ["OneFormerImageProcessor"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/oneformer/image_processing_pil_oneformer.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/oneformer/image_processing_pil_oneformer.py
new file mode 100644
index 0000000000000000000000000000000000000000..bed17ab5f4eb0fbf2f15483efb226c6bc0d4c8b7
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/oneformer/image_processing_pil_oneformer.py
@@ -0,0 +1,1008 @@
+# Copyright 2025 SHI Labs and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Image processor class for OneFormer."""
+
+import json
+import os
+
+import numpy as np
+
+from ...image_processing_backends import PilBackend
+from ...image_processing_utils import BatchFeature
+from ...image_transforms import PaddingMode
+from ...image_transforms import pad as np_pad
+from ...image_utils import (
+ IMAGENET_DEFAULT_MEAN,
+ IMAGENET_DEFAULT_STD,
+ ChannelDimension,
+ ImageInput,
+ PILImageResampling,
+ SizeDict,
+ get_image_size,
+ get_max_height_width,
+)
+from ...processing_utils import ImagesKwargs, Unpack
+from ...utils import TensorType, auto_docstring, is_torch_available, is_torchvision_available, logging
+from ...utils.import_utils import requires
+
+
+logger = logging.get_logger(__name__)
+
+if is_torch_available():
+ import torch
+ from torch import nn
+
+if is_torchvision_available():
+ import torchvision.transforms.v2.functional as tvF
+
+try:
+ from huggingface_hub import hf_hub_download
+ from huggingface_hub.utils import RepositoryNotFoundError
+except ImportError:
+ hf_hub_download = None
+ RepositoryNotFoundError = None
+
+
+def make_pixel_mask(image: np.ndarray, output_size: tuple[int, int]) -> np.ndarray:
+ """
+ Make a pixel mask for the image, where 1 indicates a valid pixel and 0 indicates padding.
+
+ Args:
+ image (`np.ndarray`):
+ Image to make the pixel mask for.
+ output_size (`Tuple[int, int]`):
+ Output size of the mask.
+ """
+ input_height, input_width = get_image_size(image, channel_dim=ChannelDimension.FIRST)
+ mask = np.zeros(output_size, dtype=np.int64)
+ mask[:input_height, :input_width] = 1
+ return mask
+
+
+# Adapted from transformers.models.oneformer.image_processing_oneformer.OneFormerImageProcessorKwargs
+class OneFormerImageProcessorKwargs(ImagesKwargs, total=False):
+ r"""
+ repo_path (`str`, *optional*, defaults to `shi-labs/oneformer_demo`):
+ Path to a local directory or HuggingFace Hub repository containing model metadata.
+ class_info_file (`str`, *optional*):
+ Path to the JSON file within the repository that contains class metadata.
+ num_text (`int`, *optional*):
+ Number of text queries for the text encoder, used as task-guiding prompts.
+ num_labels (`int`, *optional*):
+ Number of semantic classes for segmentation, determining the output layer's size.
+ ignore_index (`int`, *optional*):
+ Label to ignore in segmentation maps, often used for padding.
+ do_reduce_labels (`bool`, *optional*, defaults to `False`):
+ Whether to decrement all label values by 1, mapping the background class to `ignore_index`.
+ """
+
+ repo_path: str | None
+ class_info_file: str | None
+ num_text: int | None
+ num_labels: int | None
+ ignore_index: int | None
+ do_reduce_labels: bool
+
+
+# Adapted from transformers.models.oneformer.image_processing_oneformer.binary_mask_to_rle
+def binary_mask_to_rle(mask):
+ """
+ Converts given binary mask of shape `(height, width)` to the run-length encoding (RLE) format.
+
+ Args:
+ mask (`torch.Tensor` or `numpy.array`):
+ A binary mask tensor of shape `(height, width)` where 0 denotes background and 1 denotes the target
+ segment_id or class_id.
+ Returns:
+ `List`: Run-length encoded list of the binary mask. Refer to COCO API for more information about the RLE
+ format.
+ """
+ from ...utils import is_torch_tensor
+
+ if is_torch_tensor(mask):
+ mask = mask.numpy()
+
+ pixels = mask.flatten()
+ pixels = np.concatenate([[0], pixels, [0]])
+ runs = np.where(pixels[1:] != pixels[:-1])[0] + 1
+ runs[1::2] -= runs[::2]
+ return list(runs)
+
+
+# Adapted from transformers.models.oneformer.image_processing_oneformer.check_segment_validity
+def check_segment_validity(mask_labels, mask_probs, k, mask_threshold=0.5, overlap_mask_area_threshold=0.8):
+ # Get the mask associated with the k class
+ mask_k = mask_labels == k
+ mask_k_area = mask_k.sum()
+
+ # Compute the area of all the stuff in query k
+ original_area = (mask_probs[k] >= mask_threshold).sum()
+ mask_exists = mask_k_area > 0 and original_area > 0
+
+ # Eliminate disconnected tiny segments
+ if mask_exists:
+ area_ratio = mask_k_area / original_area
+ if not area_ratio.item() > overlap_mask_area_threshold:
+ mask_exists = False
+
+ return mask_exists, mask_k
+
+
+# Adapted from transformers.models.oneformer.image_processing_oneformer.compute_segments
+def compute_segments(
+ mask_probs,
+ pred_scores,
+ pred_labels,
+ mask_threshold: float = 0.5,
+ overlap_mask_area_threshold: float = 0.8,
+ label_ids_to_fuse: set[int] | None = None,
+ target_size: tuple[int, int] | None = None,
+):
+ height = mask_probs.shape[1] if target_size is None else target_size[0]
+ width = mask_probs.shape[2] if target_size is None else target_size[1]
+
+ segmentation = torch.zeros((height, width), dtype=torch.int32, device=mask_probs.device)
+ segments: list[dict] = []
+
+ if target_size is not None:
+ mask_probs = tvF.resize(
+ mask_probs.unsqueeze(0),
+ size=target_size,
+ interpolation=tvF.InterpolationMode.BILINEAR,
+ )[0]
+
+ current_segment_id = 0
+
+ mask_probs *= pred_scores.view(-1, 1, 1)
+ mask_labels = mask_probs.argmax(0) # [height, width]
+
+ stuff_memory_list: dict[str, int] = {}
+ for k in range(pred_labels.shape[0]):
+ pred_class = pred_labels[k].item()
+ should_fuse = pred_class in label_ids_to_fuse
+
+ mask_exists, mask_k = check_segment_validity(
+ mask_labels, mask_probs, k, mask_threshold, overlap_mask_area_threshold
+ )
+
+ if mask_exists:
+ if pred_class in stuff_memory_list:
+ current_segment_id = stuff_memory_list[pred_class]
+ else:
+ current_segment_id += 1
+
+ segmentation[mask_k] = current_segment_id
+ segment_score = round(pred_scores[k].item(), 6)
+ segments.append(
+ {
+ "id": current_segment_id,
+ "label_id": pred_class,
+ "was_fused": should_fuse,
+ "score": segment_score,
+ }
+ )
+ if should_fuse:
+ stuff_memory_list[pred_class] = current_segment_id
+
+ return segmentation, segments
+
+
+# Adapted from transformers.models.oneformer.image_processing_oneformer.convert_segmentation_to_rle
+def convert_segmentation_to_rle(segmentation):
+ """
+ Converts given segmentation map of shape `(height, width)` to the run-length encoding (RLE) format.
+
+ Args:
+ segmentation (`torch.Tensor` or `numpy.array`):
+ A segmentation map of shape `(height, width)` where each value denotes a segment or class id.
+ Returns:
+ `List[List]`: A list of lists, where each list is the run-length encoding of a segment / class id.
+ """
+ segment_ids = torch.unique(segmentation)
+
+ run_length_encodings = []
+ for idx in segment_ids:
+ mask = torch.where(segmentation == idx, 1, 0)
+ rle = binary_mask_to_rle(mask)
+ run_length_encodings.append(rle)
+
+ return run_length_encodings
+
+
+# Adapted from transformers.models.oneformer.image_processing_oneformer.load_metadata
+def load_metadata(repo_id, class_info_file):
+ fname = os.path.join("" if repo_id is None else repo_id, class_info_file)
+
+ if not os.path.exists(fname) or not os.path.isfile(fname):
+ if repo_id is None:
+ raise ValueError(f"Could not file {fname} locally. repo_id must be defined if loading from the hub")
+ if hf_hub_download is None:
+ raise ImportError(
+ "huggingface_hub is required to download metadata files. Install it with `pip install huggingface_hub`"
+ )
+ # We try downloading from a dataset by default for backward compatibility
+ try:
+ fname = hf_hub_download(repo_id, class_info_file, repo_type="dataset")
+ except RepositoryNotFoundError:
+ fname = hf_hub_download(repo_id, class_info_file)
+
+ with open(fname, "r") as f:
+ class_info = json.load(f)
+
+ return class_info
+
+
+# Adapted from transformers.models.oneformer.image_processing_oneformer.prepare_metadata
+def prepare_metadata(class_info):
+ metadata = {}
+ class_names = []
+ thing_ids = []
+ for key, info in class_info.items():
+ metadata[key] = info["name"]
+ class_names.append(info["name"])
+ if info["isthing"]:
+ thing_ids.append(int(key))
+ metadata["thing_ids"] = thing_ids
+ metadata["class_names"] = class_names
+ return metadata
+
+
+# Adapted from transformers.models.oneformer.image_processing_oneformer.remove_low_and_no_objects
+def remove_low_and_no_objects(masks, scores, labels, object_mask_threshold, num_labels):
+ """
+ Binarize the given masks using `object_mask_threshold`, it returns the associated values of `masks`, `scores` and
+ `labels`.
+
+ Args:
+ masks (`torch.Tensor`):
+ A tensor of shape `(num_queries, height, width)`.
+ scores (`torch.Tensor`):
+ A tensor of shape `(num_queries)`.
+ labels (`torch.Tensor`):
+ A tensor of shape `(num_queries)`.
+ object_mask_threshold (`float`):
+ A number between 0 and 1 used to binarize the masks.
+ Raises:
+ `ValueError`: Raised when the first dimension doesn't match in all input tensors.
+ Returns:
+ `Tuple[`torch.Tensor`, `torch.Tensor`, `torch.Tensor`]`: The `masks`, `scores` and `labels` without the region
+ < `object_mask_threshold`.
+ """
+ if not (masks.shape[0] == scores.shape[0] == labels.shape[0]):
+ raise ValueError("mask, scores and labels must have the same shape!")
+
+ to_keep = labels.ne(num_labels) & (scores > object_mask_threshold)
+
+ return masks[to_keep], scores[to_keep], labels[to_keep]
+
+
+@auto_docstring
+@requires(backends=("torch",))
+class OneFormerImageProcessorPil(PilBackend):
+ resample = PILImageResampling.BILINEAR
+ image_mean = IMAGENET_DEFAULT_MEAN
+ image_std = IMAGENET_DEFAULT_STD
+ size = {"shortest_edge": 800, "longest_edge": 1333}
+ crop_size = None
+ do_resize = True
+ do_rescale = True
+ do_normalize = True
+ default_to_square = False
+ do_center_crop = False
+ do_convert_rgb = True
+ rescale_factor = 1 / 255
+ ignore_index = None
+ do_reduce_labels = False
+ repo_path = "shi-labs/oneformer_demo"
+ class_info_file = None
+ num_text = None
+ num_labels = None
+ valid_kwargs = OneFormerImageProcessorKwargs
+ model_input_names = ["pixel_values", "pixel_mask", "task_inputs"]
+
+ def __init__(self, **kwargs: Unpack[OneFormerImageProcessorKwargs]):
+ super().__init__(**kwargs)
+ if self.class_info_file:
+ self.metadata = prepare_metadata(load_metadata(self.repo_path, self.class_info_file))
+
+ @auto_docstring
+ def preprocess(
+ self,
+ images: ImageInput,
+ task_inputs: list[str] | None = None,
+ segmentation_maps: ImageInput | None = None,
+ instance_id_to_semantic_id: list[dict[int, int]] | dict[int, int] | None = None,
+ **kwargs: Unpack[OneFormerImageProcessorKwargs],
+ ) -> BatchFeature:
+ r"""
+ task_inputs (`list[str]`, *optional*):
+ List of tasks (`"panoptic"`, `"instance"`, `"semantic"`) for each image in the batch.
+ segmentation_maps (`ImageInput`, *optional*):
+ The segmentation maps.
+ instance_id_to_semantic_id (`Union[list[dict[int, int]], dict[int, int]]`, *optional*):
+ A mapping from instance IDs to semantic IDs.
+ """
+ return super().preprocess(images, task_inputs, segmentation_maps, instance_id_to_semantic_id, **kwargs)
+
+ def _preprocess_image_like_inputs(
+ self,
+ images: ImageInput,
+ task_inputs: list[str] | None,
+ segmentation_maps: ImageInput,
+ instance_id_to_semantic_id: list[dict[int, int]] | dict[int, int] | None,
+ do_convert_rgb: bool,
+ input_data_format: ChannelDimension,
+ **kwargs: Unpack[OneFormerImageProcessorKwargs],
+ ) -> BatchFeature:
+ """
+ Preprocess image-like inputs.
+ To be overridden by subclasses when image-like inputs other than images should be processed.
+ It can be used for segmentation maps, depth maps, etc.
+ """
+ # Prepare input images
+ images = self._prepare_image_like_inputs(
+ images=images, do_convert_rgb=do_convert_rgb, input_data_format=input_data_format
+ )
+ if segmentation_maps is not None:
+ segmentation_maps = self._prepare_image_like_inputs(
+ images=segmentation_maps,
+ expected_ndims=2,
+ do_convert_rgb=False,
+ input_data_format=ChannelDimension.FIRST,
+ )
+ return self._preprocess(images, task_inputs, segmentation_maps, instance_id_to_semantic_id, **kwargs)
+
+ def _preprocess(
+ self,
+ images: list[np.ndarray],
+ task_inputs: list[str] | None,
+ segmentation_maps: list[np.ndarray],
+ instance_id_to_semantic_id: list[dict[int, int]] | dict[int, int] | None,
+ do_resize: bool,
+ size: SizeDict,
+ resample: PILImageResampling | None,
+ do_rescale: bool,
+ rescale_factor: float,
+ do_normalize: bool,
+ image_mean: float | list[float] | None,
+ image_std: float | list[float] | None,
+ ignore_index: int | None,
+ do_reduce_labels: bool | None,
+ return_tensors: str | TensorType | None,
+ **kwargs,
+ ) -> BatchFeature:
+ # Process images one by one (no batching in PIL backend)
+ processed_images = []
+ processed_segmentation_maps = None
+ if segmentation_maps is not None:
+ processed_segmentation_maps = []
+
+ for idx, image in enumerate(images):
+ if do_resize:
+ image = self.resize(image=image, size=size, resample=resample)
+ if do_rescale:
+ image = self.rescale(image, rescale_factor)
+ if do_normalize:
+ image = self.normalize(image, image_mean, image_std)
+ processed_images.append(image)
+
+ if segmentation_maps is not None:
+ seg_map = segmentation_maps[idx]
+ if do_resize:
+ seg_map = self.resize(image=seg_map, size=size, resample=PILImageResampling.NEAREST)
+ processed_segmentation_maps.append(seg_map)
+
+ encoded_inputs = self.encode_inputs(
+ processed_images,
+ task_inputs,
+ segmentation_maps=processed_segmentation_maps,
+ instance_id_to_semantic_id=instance_id_to_semantic_id,
+ ignore_index=ignore_index,
+ do_reduce_labels=do_reduce_labels,
+ return_tensors=return_tensors,
+ )
+
+ return encoded_inputs
+
+ def _pad_image(self, image: np.ndarray, output_size: tuple[int, int], constant_values: float = 0) -> np.ndarray:
+ """
+ Pad an image with zeros to the given size using numpy operations.
+
+ Args:
+ image (`np.ndarray`):
+ Image array in channel-first format (C, H, W) or (H, W).
+ output_size (`tuple[int, int]`):
+ Target output size (height, width).
+ constant_values (`float`, *optional*, defaults to 0):
+ The value to use for padding.
+
+ Returns:
+ `np.ndarray`: The padded image.
+ """
+ input_height, input_width = get_image_size(image, channel_dim=ChannelDimension.FIRST)
+ output_height, output_width = output_size
+
+ pad_bottom = output_height - input_height
+ pad_right = output_width - input_width
+
+ # For 2D arrays (masks), use np.pad directly
+ # For 3D arrays (images), use np_pad which handles channel dimension
+ if image.ndim == 2:
+ padding = ((0, pad_bottom), (0, pad_right))
+ padded_image = np.pad(image, padding, mode="constant", constant_values=constant_values)
+ else:
+ padding = ((0, pad_bottom), (0, pad_right))
+ padded_image = np_pad(
+ image,
+ padding,
+ mode=PaddingMode.CONSTANT,
+ constant_values=constant_values,
+ data_format=ChannelDimension.FIRST,
+ input_data_format=ChannelDimension.FIRST,
+ )
+
+ return padded_image
+
+ def pad(
+ self, images: list[np.ndarray], return_pixel_mask: bool = True, return_tensors: str | TensorType | None = None
+ ) -> BatchFeature:
+ """
+ Pad a batch of images to the same size using numpy operations.
+
+ Args:
+ images (`List[np.ndarray]`):
+ List of image arrays in channel-first format.
+ return_pixel_mask (`bool`, *optional*, defaults to `True`):
+ Whether to return pixel masks.
+ return_tensors (`str` or `TensorType`, *optional*):
+ The type of tensors to return.
+
+ Returns:
+ `BatchFeature`: Padded images and optional pixel masks.
+ """
+ pad_size = get_max_height_width(images, input_data_format=ChannelDimension.FIRST)
+
+ padded_images = []
+ pixel_masks = []
+ for image in images:
+ padded_image = self._pad_image(image, pad_size, constant_values=0)
+ padded_images.append(padded_image)
+ if return_pixel_mask:
+ pixel_mask = make_pixel_mask(image, pad_size)
+ pixel_masks.append(pixel_mask)
+
+ if return_tensors == "pt":
+ padded_images = [torch.from_numpy(img) for img in padded_images]
+ padded_images = torch.stack(padded_images, dim=0)
+ if return_pixel_mask:
+ pixel_masks = [torch.from_numpy(mask) for mask in pixel_masks]
+ pixel_masks = torch.stack(pixel_masks, dim=0)
+
+ data = {"pixel_values": padded_images}
+ if return_pixel_mask:
+ data["pixel_mask"] = pixel_masks
+
+ return BatchFeature(data=data, tensor_type=return_tensors)
+
+ def convert_segmentation_map_to_binary_masks(
+ self,
+ segmentation_map: np.ndarray,
+ instance_id_to_semantic_id: dict[int, int] | None = None,
+ ignore_index: int | None = None,
+ do_reduce_labels: bool = False,
+ ):
+ """Convert segmentation map to binary masks using NumPy operations."""
+ if do_reduce_labels and ignore_index is None:
+ raise ValueError("If `do_reduce_labels` is True, `ignore_index` must be provided.")
+
+ if do_reduce_labels:
+ segmentation_map = np.where(segmentation_map == 0, ignore_index, segmentation_map - 1)
+
+ all_labels = np.unique(segmentation_map)
+
+ if ignore_index is not None:
+ all_labels = all_labels[all_labels != ignore_index]
+
+ binary_masks = [(segmentation_map == i) for i in all_labels]
+ if binary_masks:
+ binary_masks = np.stack(binary_masks, axis=0)
+ else:
+ binary_masks = np.zeros((0, *segmentation_map.shape), dtype=np.float32)
+
+ # Convert instance ids to class ids
+ if instance_id_to_semantic_id is not None:
+ labels = np.zeros(all_labels.shape[0], dtype=np.int64)
+
+ for i, label in enumerate(all_labels):
+ class_id = instance_id_to_semantic_id[(int(label) + 1 if do_reduce_labels else int(label))]
+ labels[i] = class_id - 1 if do_reduce_labels else class_id
+ else:
+ labels = all_labels.astype(np.int64)
+ return binary_masks.astype(np.float32), labels
+
+ def get_semantic_annotations(self, label, num_class_obj):
+ annotation_classes = label["classes"]
+ annotation_masks = label["masks"]
+
+ texts = ["a semantic photo"] * self.num_text
+ classes = []
+ masks = []
+
+ for idx in range(len(annotation_classes)):
+ class_id = annotation_classes[idx]
+ mask = annotation_masks[idx]
+ if not np.all(mask == 0):
+ if class_id not in classes:
+ cls_name = self.metadata[str(class_id)]
+ classes.append(class_id)
+ masks.append(mask)
+ num_class_obj[cls_name] += 1
+ else:
+ idx = classes.index(class_id)
+ masks[idx] += mask
+ masks[idx] = np.clip(masks[idx], 0, 1)
+
+ num = 0
+ for i, cls_name in enumerate(self.metadata["class_names"]):
+ if num_class_obj[cls_name] > 0:
+ for _ in range(num_class_obj[cls_name]):
+ if num >= len(texts):
+ break
+ texts[num] = f"a photo with a {cls_name}"
+ num += 1
+
+ classes = np.array(classes) if classes else np.array([], dtype=np.int64)
+ # Stack masks into a 3D array (num_masks, H, W) to match torchvision version
+ if masks:
+ masks = np.stack(masks, axis=0)
+ else:
+ # Empty masks - use shape from first annotation mask if available
+ if annotation_masks and len(annotation_masks) > 0:
+ mask_shape = annotation_masks[0].shape[-2:] if hasattr(annotation_masks[0], "shape") else (0, 0)
+ else:
+ mask_shape = (0, 0)
+ masks = np.zeros((0, *mask_shape), dtype=np.float32)
+ return classes, masks, texts
+
+ def get_instance_annotations(self, label, num_class_obj):
+ annotation_classes = label["classes"]
+ annotation_masks = label["masks"]
+
+ texts = ["an instance photo"] * self.num_text
+ classes = []
+ masks = []
+
+ for idx in range(len(annotation_classes)):
+ class_id = annotation_classes[idx]
+ mask = annotation_masks[idx]
+
+ if class_id in self.metadata["thing_ids"]:
+ if not np.all(mask == 0):
+ cls_name = self.metadata[str(class_id)]
+ classes.append(class_id)
+ masks.append(mask)
+ num_class_obj[cls_name] += 1
+
+ num = 0
+ for i, cls_name in enumerate(self.metadata["class_names"]):
+ if num_class_obj[cls_name] > 0:
+ for _ in range(num_class_obj[cls_name]):
+ if num >= len(texts):
+ break
+ texts[num] = f"a photo with a {cls_name}"
+ num += 1
+
+ classes = np.array(classes) if classes else np.array([], dtype=np.int64)
+ # Stack masks into a 3D array (num_masks, H, W) to match torchvision version
+ if masks:
+ masks = np.stack(masks, axis=0)
+ else:
+ # Empty masks - use shape from first annotation mask if available
+ if annotation_masks and len(annotation_masks) > 0:
+ mask_shape = annotation_masks[0].shape[-2:] if hasattr(annotation_masks[0], "shape") else (0, 0)
+ else:
+ mask_shape = (0, 0)
+ masks = np.zeros((0, *mask_shape), dtype=np.float32)
+ return classes, masks, texts
+
+ def get_panoptic_annotations(self, label, num_class_obj):
+ annotation_classes = label["classes"]
+ annotation_masks = label["masks"]
+
+ texts = ["an panoptic photo"] * self.num_text
+ classes = []
+ masks = []
+ for idx in range(len(annotation_classes)):
+ class_id = annotation_classes[idx]
+ mask = annotation_masks[idx] if hasattr(annotation_masks[idx], "data") else annotation_masks[idx]
+ if not np.all(mask == 0):
+ cls_name = self.metadata[str(class_id)]
+ classes.append(class_id)
+ masks.append(mask)
+ num_class_obj[cls_name] += 1
+
+ num = 0
+ for i, cls_name in enumerate(self.metadata["class_names"]):
+ if num_class_obj[cls_name] > 0:
+ for _ in range(num_class_obj[cls_name]):
+ if num >= len(texts):
+ break
+ texts[num] = f"a photo with a {cls_name}"
+ num += 1
+
+ classes = np.array(classes) if classes else np.array([], dtype=np.int64)
+ # Stack masks into a 3D array (num_masks, H, W) to match torchvision version
+ if masks:
+ masks = np.stack(masks, axis=0)
+ else:
+ # Empty masks - use shape from first annotation mask if available
+ if annotation_masks and len(annotation_masks) > 0:
+ mask_shape = annotation_masks[0].shape[-2:] if hasattr(annotation_masks[0], "shape") else (0, 0)
+ else:
+ mask_shape = (0, 0)
+ masks = np.zeros((0, *mask_shape), dtype=np.float32)
+ return classes, masks, texts
+
+ def encode_inputs(
+ self,
+ pixel_values_list: list[np.ndarray],
+ task_inputs: list[str] | None = None,
+ segmentation_maps: list[np.ndarray] | None = None,
+ instance_id_to_semantic_id: list[dict[int, int]] | dict[int, int] | None = None,
+ ignore_index: int | None = None,
+ do_reduce_labels: bool = False,
+ return_tensors: str | TensorType | None = None,
+ ) -> BatchFeature:
+ ignore_index = self.ignore_index if ignore_index is None else ignore_index
+ do_reduce_labels = self.do_reduce_labels if do_reduce_labels is None else do_reduce_labels
+ if task_inputs is None:
+ task_inputs = ["panoptic"]
+ pixel_values_list = self._prepare_image_like_inputs(
+ pixel_values_list, input_data_format=ChannelDimension.FIRST
+ )
+ if segmentation_maps is not None:
+ segmentation_maps = self._prepare_image_like_inputs(
+ images=segmentation_maps,
+ expected_ndims=2,
+ do_convert_rgb=False,
+ input_data_format=ChannelDimension.FIRST,
+ )
+ pad_size = get_max_height_width(pixel_values_list, input_data_format=ChannelDimension.FIRST)
+ encoded_inputs = self.pad(pixel_values_list, return_tensors=return_tensors)
+
+ annotations = None
+ if segmentation_maps is not None:
+ annotations = []
+ for idx, segmentation_map in enumerate(segmentation_maps):
+ # Use instance2class_id mapping per image
+ if isinstance(instance_id_to_semantic_id, list):
+ instance_id = instance_id_to_semantic_id[idx]
+ else:
+ instance_id = instance_id_to_semantic_id
+
+ # Squeeze channel dimension if present
+ if segmentation_map.ndim == 3 and segmentation_map.shape[0] == 1:
+ segmentation_map = segmentation_map.squeeze(0)
+
+ # Convert segmentation map to binary masks using numpy operations
+ masks, classes = self.convert_segmentation_map_to_binary_masks(
+ segmentation_map, instance_id, ignore_index=ignore_index, do_reduce_labels=do_reduce_labels
+ )
+
+ annotations.append({"masks": masks, "classes": classes})
+
+ if annotations is not None:
+ mask_labels = []
+ class_labels = []
+ text_inputs = []
+ num_class_obj = dict.fromkeys(self.metadata["class_names"], 0)
+
+ for i, label in enumerate(annotations):
+ task = task_inputs[i]
+
+ if task == "semantic":
+ classes, masks, texts = self.get_semantic_annotations(label, num_class_obj)
+ elif task == "instance":
+ classes, masks, texts = self.get_instance_annotations(label, num_class_obj)
+ elif task == "panoptic":
+ classes, masks, texts = self.get_panoptic_annotations(label, num_class_obj)
+ else:
+ raise ValueError(f"{task} was not expected, expected `semantic`, `instance` or `panoptic`")
+ # Pad masks to max size using numpy operations
+ # masks is a 3D array (num_masks, H, W), iterate to get 2D slices
+ padded_masks = [
+ self._pad_image(image=mask, output_size=pad_size, constant_values=ignore_index) for mask in masks
+ ]
+ # Stack padded masks back into 3D array (num_masks, padded_H, padded_W)
+ padded_masks = (
+ np.stack(padded_masks, axis=0) if padded_masks else np.zeros((0, *pad_size), dtype=np.float32)
+ )
+ mask_labels.append(padded_masks)
+ class_labels.append(classes)
+ text_inputs.append(texts)
+
+ encoded_inputs["mask_labels"] = [
+ torch.from_numpy(mask_label) if return_tensors == "pt" else mask_label for mask_label in mask_labels
+ ]
+ encoded_inputs["class_labels"] = [
+ torch.from_numpy(class_label) if return_tensors == "pt" else class_label
+ for class_label in class_labels
+ ]
+ encoded_inputs["text_inputs"] = text_inputs
+
+ encoded_inputs["task_inputs"] = [f"the task is {task_input}" for task_input in task_inputs]
+ return encoded_inputs
+
+ def post_process_semantic_segmentation(
+ self, outputs, target_sizes: list[tuple[int, int]] | None = None
+ ) -> "torch.Tensor":
+ """
+ Converts the output of [`MaskFormerForInstanceSegmentation`] into semantic segmentation maps. Only supports
+ PyTorch.
+
+ Args:
+ outputs ([`MaskFormerForInstanceSegmentation`]):
+ Raw outputs of the model.
+ target_sizes (`List[Tuple[int, int]]`, *optional*):
+ List of length (batch_size), where each list item (`Tuple[int, int]]`) corresponds to the requested
+ final size (height, width) of each prediction. If left to None, predictions will not be resized.
+ Returns:
+ `List[torch.Tensor]`:
+ A list of length `batch_size`, where each item is a semantic segmentation map of shape (height, width)
+ corresponding to the target_sizes entry (if `target_sizes` is specified). Each entry of each
+ `torch.Tensor` correspond to a semantic class id.
+ """
+ class_queries_logits = outputs.class_queries_logits # [batch_size, num_queries, num_classes+1]
+ masks_queries_logits = outputs.masks_queries_logits # [batch_size, num_queries, height, width]
+
+ # Remove the null class `[..., :-1]`
+ masks_classes = class_queries_logits.softmax(dim=-1)[..., :-1]
+ masks_probs = masks_queries_logits.sigmoid() # [batch_size, num_queries, height, width]
+
+ # Semantic segmentation logits of shape (batch_size, num_classes, height, width)
+ segmentation = torch.einsum("bqc, bqhw -> bchw", masks_classes, masks_probs)
+ batch_size = class_queries_logits.shape[0]
+
+ # Resize logits and compute semantic segmentation maps
+ if target_sizes is not None:
+ if batch_size != len(target_sizes):
+ raise ValueError(
+ "Make sure that you pass in as many target sizes as the batch dimension of the logits"
+ )
+
+ semantic_segmentation = []
+ for idx in range(batch_size):
+ resized_logits = torch.nn.functional.interpolate(
+ segmentation[idx].unsqueeze(dim=0), size=target_sizes[idx], mode="bilinear", align_corners=False
+ )
+ semantic_map = resized_logits[0].argmax(dim=0)
+ semantic_segmentation.append(semantic_map)
+ else:
+ semantic_segmentation = segmentation.argmax(dim=1)
+ semantic_segmentation = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0])]
+
+ return semantic_segmentation
+
+ def post_process_instance_segmentation(
+ self,
+ outputs,
+ task_type: str = "instance",
+ is_demo: bool = True,
+ threshold: float = 0.5,
+ mask_threshold: float = 0.5,
+ overlap_mask_area_threshold: float = 0.8,
+ target_sizes: list[tuple[int, int]] | None = None,
+ return_coco_annotation: bool | None = False,
+ ):
+ """
+ Converts the output of [`OneFormerForUniversalSegmentationOutput`] into image instance segmentation
+ predictions. Only supports PyTorch.
+
+ Args:
+ outputs ([`OneFormerForUniversalSegmentationOutput`]):
+ The outputs from [`OneFormerForUniversalSegmentationOutput`].
+ task_type (`str`, *optional*, defaults to "instance"):
+ The post processing depends on the task token input. If the `task_type` is "panoptic", we need to
+ ignore the stuff predictions.
+ is_demo (`bool`, *optional)*, defaults to `True`):
+ Whether the model is in demo mode. If true, use threshold to predict final masks.
+ threshold (`float`, *optional*, defaults to 0.5):
+ The probability score threshold to keep predicted instance masks.
+ mask_threshold (`float`, *optional*, defaults to 0.5):
+ Threshold to use when turning the predicted masks into binary values.
+ overlap_mask_area_threshold (`float`, *optional*, defaults to 0.8):
+ The overlap mask area threshold to merge or discard small disconnected parts within each binary
+ instance mask.
+ target_sizes (`List[Tuple]`, *optional*):
+ List of length (batch_size), where each list item (`Tuple[int, int]]`) corresponds to the requested
+ final size (height, width) of each prediction in batch. If left to None, predictions will not be
+ resized.
+ return_coco_annotation (`bool`, *optional)*, defaults to `False`):
+ Whether to return predictions in COCO format.
+
+ Returns:
+ `List[Dict]`: A list of dictionaries, one per image, each dictionary containing two keys:
+ - **segmentation** -- a tensor of shape `(height, width)` where each pixel represents a `segment_id`, set
+ to `None` if no mask if found above `threshold`. If `target_sizes` is specified, segmentation is resized
+ to the corresponding `target_sizes` entry.
+ - **segments_info** -- A dictionary that contains additional information on each segment.
+ - **id** -- an integer representing the `segment_id`.
+ - **label_id** -- An integer representing the label / semantic class id corresponding to `segment_id`.
+ - **was_fused** -- a boolean, `True` if `label_id` was in `label_ids_to_fuse`, `False` otherwise.
+ Multiple instances of the same class / label were fused and assigned a single `segment_id`.
+ - **score** -- Prediction score of segment with `segment_id`.
+ """
+ class_queries_logits = outputs.class_queries_logits # [batch_size, num_queries, num_classes+1]
+ masks_queries_logits = outputs.masks_queries_logits # [batch_size, num_queries, height, width]
+
+ device = masks_queries_logits.device
+ batch_size = class_queries_logits.shape[0]
+ num_queries = class_queries_logits.shape[1]
+ num_classes = class_queries_logits.shape[-1] - 1
+
+ # Loop over items in batch size
+ results: list[dict[str, torch.Tensor]] = []
+
+ for i in range(batch_size):
+ # [Q, K]
+ scores = nn.functional.softmax(class_queries_logits[i], dim=-1)[:, :-1]
+ labels = torch.arange(num_classes, device=device).unsqueeze(0).repeat(num_queries, 1).flatten(0, 1)
+
+ # scores_per_image, topk_indices = scores.flatten(0, 1).topk(self.num_queries, sorted=False)
+ scores_per_image, topk_indices = scores.flatten(0, 1).topk(num_queries, sorted=False)
+ labels_per_image = labels[topk_indices]
+
+ topk_indices = torch.div(topk_indices, num_classes, rounding_mode="floor")
+ # mask_pred = mask_pred.unsqueeze(1).repeat(1, self.sem_seg_head.num_classes, 1).flatten(0, 1)
+ mask_pred = masks_queries_logits[i][topk_indices]
+
+ # Only consider scores with confidence over [threshold] for demo
+ if is_demo:
+ keep = scores_per_image > threshold
+ scores_per_image = scores_per_image[keep]
+ labels_per_image = labels_per_image[keep]
+ mask_pred = mask_pred[keep]
+
+ # if this is panoptic segmentation, we only keep the "thing" classes
+ if task_type == "panoptic":
+ keep = torch.zeros_like(scores_per_image).bool()
+ for j, lab in enumerate(labels_per_image):
+ keep[j] = lab in self.metadata["thing_ids"]
+
+ scores_per_image = scores_per_image[keep]
+ labels_per_image = labels_per_image[keep]
+ mask_pred = mask_pred[keep]
+
+ if mask_pred.shape[0] <= 0:
+ height, width = target_sizes[i] if target_sizes is not None else mask_pred.shape[1:]
+ segmentation = torch.zeros((height, width)) - 1
+ results.append({"segmentation": segmentation, "segments_info": []})
+ continue
+
+ if "ade20k" in self.class_info_file and not is_demo and "instance" in task_type:
+ for j in range(labels_per_image.shape[0]):
+ labels_per_image[j] = self.metadata["thing_ids"].index(labels_per_image[j].item())
+
+ # Get segmentation map and segment information of batch item
+ target_size = target_sizes[i] if target_sizes is not None else None
+ segmentation, segments = compute_segments(
+ mask_pred,
+ scores_per_image,
+ labels_per_image,
+ mask_threshold,
+ overlap_mask_area_threshold,
+ set(),
+ target_size,
+ )
+
+ # Return segmentation map in run-length encoding (RLE) format
+ if return_coco_annotation:
+ segmentation = convert_segmentation_to_rle(segmentation)
+
+ results.append({"segmentation": segmentation, "segments_info": segments})
+ return results
+
+ # Adapted from transformers.models.maskformer.image_processing_maskformer.MaskFormerImageProcessor.post_process_panoptic_segmentation
+ def post_process_panoptic_segmentation(
+ self,
+ outputs,
+ threshold: float = 0.5,
+ mask_threshold: float = 0.5,
+ overlap_mask_area_threshold: float = 0.8,
+ label_ids_to_fuse: set[int] | None = None,
+ target_sizes: list[tuple[int, int]] | None = None,
+ ) -> list[dict]:
+ """
+ Converts the output of [`MaskFormerForInstanceSegmentationOutput`] into image panoptic segmentation
+ predictions. Only supports PyTorch.
+
+ Args:
+ outputs ([`MaskFormerForInstanceSegmentationOutput`]):
+ The outputs from [`MaskFormerForInstanceSegmentation`].
+ threshold (`float`, *optional*, defaults to 0.5):
+ The probability score threshold to keep predicted instance masks.
+ mask_threshold (`float`, *optional*, defaults to 0.5):
+ Threshold to use when turning the predicted masks into binary values.
+ overlap_mask_area_threshold (`float`, *optional*, defaults to 0.8):
+ The overlap mask area threshold to merge or discard small disconnected parts within each binary
+ instance mask.
+ label_ids_to_fuse (`Set[int]`, *optional*):
+ The labels in this state will have all their instances be fused together. For instance we could say
+ there can only be one sky in an image, but several persons, so the label ID for sky would be in that
+ set, but not the one for person.
+ target_sizes (`list[Tuple]`, *optional*):
+ List of length (batch_size), where each list item (`tuple[int, int]]`) corresponds to the requested
+ final size (height, width) of each prediction in batch. If left to None, predictions will not be
+ resized.
+
+ Returns:
+ `list[Dict]`: A list of dictionaries, one per image, each dictionary containing two keys:
+ - **segmentation** -- a tensor of shape `(height, width)` where each pixel represents a `segment_id`, set
+ to `None` if no mask if found above `threshold`. If `target_sizes` is specified, segmentation is resized
+ to the corresponding `target_sizes` entry.
+ - **segments_info** -- A dictionary that contains additional information on each segment.
+ - **id** -- an integer representing the `segment_id`.
+ - **label_id** -- An integer representing the label / semantic class id corresponding to `segment_id`.
+ - **was_fused** -- a boolean, `True` if `label_id` was in `label_ids_to_fuse`, `False` otherwise.
+ Multiple instances of the same class / label were fused and assigned a single `segment_id`.
+ - **score** -- Prediction score of segment with `segment_id`.
+ """
+
+ if label_ids_to_fuse is None:
+ logger.warning("`label_ids_to_fuse` unset. No instance will be fused.")
+ label_ids_to_fuse = set()
+
+ class_queries_logits = outputs.class_queries_logits # [batch_size, num_queries, num_classes+1]
+ masks_queries_logits = outputs.masks_queries_logits # [batch_size, num_queries, height, width]
+
+ batch_size = class_queries_logits.shape[0]
+ num_labels = class_queries_logits.shape[-1] - 1
+
+ mask_probs = masks_queries_logits.sigmoid() # [batch_size, num_queries, height, width]
+
+ # Predicted label and score of each query (batch_size, num_queries)
+ pred_scores, pred_labels = nn.functional.softmax(class_queries_logits, dim=-1).max(-1)
+
+ # Loop over items in batch size
+ results: list[dict[str, TensorType]] = []
+
+ for i in range(batch_size):
+ mask_probs_item, pred_scores_item, pred_labels_item = remove_low_and_no_objects(
+ mask_probs[i], pred_scores[i], pred_labels[i], threshold, num_labels
+ )
+
+ # No mask found
+ if mask_probs_item.shape[0] <= 0:
+ height, width = target_sizes[i] if target_sizes is not None else mask_probs_item.shape[1:]
+ segmentation = torch.zeros((height, width)) - 1
+ results.append({"segmentation": segmentation, "segments_info": []})
+ continue
+
+ # Get segmentation map and segment information of batch item
+ target_size = target_sizes[i] if target_sizes is not None else None
+ segmentation, segments = compute_segments(
+ mask_probs=mask_probs_item,
+ pred_scores=pred_scores_item,
+ pred_labels=pred_labels_item,
+ mask_threshold=mask_threshold,
+ overlap_mask_area_threshold=overlap_mask_area_threshold,
+ label_ids_to_fuse=label_ids_to_fuse,
+ target_size=target_size,
+ )
+
+ results.append({"segmentation": segmentation, "segments_info": segments})
+ return results
+
+
+__all__ = ["OneFormerImageProcessorPil"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/oneformer/modeling_oneformer.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/oneformer/modeling_oneformer.py
new file mode 100644
index 0000000000000000000000000000000000000000..ab40445ed9e3d28aa5e5a2e9c45301b1e6a477f2
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/oneformer/modeling_oneformer.py
@@ -0,0 +1,3203 @@
+# Copyright 2022 SHI Labs and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch OneFormer model."""
+
+import copy
+import math
+import warnings
+from dataclasses import dataclass
+
+import numpy as np
+import torch
+from torch import Tensor, nn
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...backbone_utils import load_backbone
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import BaseModelOutput
+from ...modeling_utils import PreTrainedModel
+from ...pytorch_utils import compile_compatible_method_lru_cache
+from ...utils import (
+ ModelOutput,
+ auto_docstring,
+ is_accelerate_available,
+ is_scipy_available,
+ logging,
+ requires_backends,
+ torch_compilable_check,
+)
+from ...utils.generic import maybe_autocast
+from .configuration_oneformer import OneFormerConfig
+
+
+if is_accelerate_available():
+ from accelerate import PartialState
+ from accelerate.utils import reduce
+
+logger = logging.get_logger(__name__)
+
+
+if is_scipy_available():
+ from scipy.optimize import linear_sum_assignment
+
+
+def _get_clones(module, N):
+ return nn.ModuleList([copy.deepcopy(module) for i in range(N)])
+
+
+def multi_scale_deformable_attention(
+ value: Tensor,
+ value_spatial_shapes: Tensor | list[tuple],
+ sampling_locations: Tensor,
+ attention_weights: Tensor,
+) -> Tensor:
+ batch_size, _, num_heads, hidden_dim = value.shape
+ _, num_queries, num_heads, num_levels, num_points, _ = sampling_locations.shape
+ value_list = value.split([height * width for height, width in value_spatial_shapes], dim=1)
+ sampling_grids = 2 * sampling_locations - 1
+ sampling_value_list = []
+ for level_id, (height, width) in enumerate(value_spatial_shapes):
+ # batch_size, height*width, num_heads, hidden_dim
+ # -> batch_size, height*width, num_heads*hidden_dim
+ # -> batch_size, num_heads*hidden_dim, height*width
+ # -> batch_size*num_heads, hidden_dim, height, width
+ value_l_ = (
+ value_list[level_id].flatten(2).transpose(1, 2).reshape(batch_size * num_heads, hidden_dim, height, width)
+ )
+ # batch_size, num_queries, num_heads, num_points, 2
+ # -> batch_size, num_heads, num_queries, num_points, 2
+ # -> batch_size*num_heads, num_queries, num_points, 2
+ sampling_grid_l_ = sampling_grids[:, :, :, level_id].transpose(1, 2).flatten(0, 1)
+ # batch_size*num_heads, hidden_dim, num_queries, num_points
+ sampling_value_l_ = nn.functional.grid_sample(
+ value_l_, sampling_grid_l_, mode="bilinear", padding_mode="zeros", align_corners=False
+ )
+ sampling_value_list.append(sampling_value_l_)
+ # (batch_size, num_queries, num_heads, num_levels, num_points)
+ # -> (batch_size, num_heads, num_queries, num_levels, num_points)
+ # -> (batch_size, num_heads, 1, num_queries, num_levels*num_points)
+ attention_weights = attention_weights.transpose(1, 2).reshape(
+ batch_size * num_heads, 1, num_queries, num_levels * num_points
+ )
+ output = (
+ (torch.stack(sampling_value_list, dim=-2).flatten(-2) * attention_weights)
+ .sum(-1)
+ .view(batch_size, num_heads * hidden_dim, num_queries)
+ )
+ return output.transpose(1, 2).contiguous()
+
+
+# Copied from transformers.models.maskformer.modeling_maskformer.dice_loss
+def dice_loss(inputs: Tensor, labels: Tensor, num_masks: int) -> Tensor:
+ r"""
+ Compute the DICE loss, similar to generalized IOU for masks as follows:
+
+ $$ \mathcal{L}_{\text{dice}(x, y) = 1 - \frac{2 * x \cap y }{x \cup y + 1}} $$
+
+ In practice, since `labels` is a binary mask, (only 0s and 1s), dice can be computed as follow
+
+ $$ \mathcal{L}_{\text{dice}(x, y) = 1 - \frac{2 * x * y }{x + y + 1}} $$
+
+ Args:
+ inputs (`torch.Tensor`):
+ A tensor representing a mask.
+ labels (`torch.Tensor`):
+ A tensor with the same shape as inputs. Stores the binary classification labels for each element in inputs
+ (0 for the negative class and 1 for the positive class).
+ num_masks (`int`):
+ The number of masks present in the current batch, used for normalization.
+
+ Returns:
+ `torch.Tensor`: The computed loss.
+ """
+ probs = inputs.sigmoid().flatten(1)
+ numerator = 2 * (probs * labels).sum(-1)
+ denominator = probs.sum(-1) + labels.sum(-1)
+ loss = 1 - (numerator + 1) / (denominator + 1)
+ loss = loss.sum() / num_masks
+ return loss
+
+
+# Copied from transformers.models.mask2former.modeling_mask2former.sigmoid_cross_entropy_loss
+def sigmoid_cross_entropy_loss(inputs: torch.Tensor, labels: torch.Tensor, num_masks: int) -> torch.Tensor:
+ r"""
+ Args:
+ inputs (`torch.Tensor`):
+ A float tensor of arbitrary shape.
+ labels (`torch.Tensor`):
+ A tensor with the same shape as inputs. Stores the binary classification labels for each element in inputs
+ (0 for the negative class and 1 for the positive class).
+
+ Returns:
+ loss (`torch.Tensor`): The computed loss.
+ """
+ criterion = nn.BCEWithLogitsLoss(reduction="none")
+ cross_entropy_loss = criterion(inputs, labels)
+
+ loss = cross_entropy_loss.mean(1).sum() / num_masks
+ return loss
+
+
+# Copied from transformers.models.maskformer.modeling_maskformer.pair_wise_dice_loss
+def pair_wise_dice_loss(inputs: Tensor, labels: Tensor) -> Tensor:
+ """
+ A pair wise version of the dice loss, see `dice_loss` for usage.
+
+ Args:
+ inputs (`torch.Tensor`):
+ A tensor representing a mask
+ labels (`torch.Tensor`):
+ A tensor with the same shape as inputs. Stores the binary classification labels for each element in inputs
+ (0 for the negative class and 1 for the positive class).
+
+ Returns:
+ `torch.Tensor`: The computed loss between each pairs.
+ """
+ inputs = inputs.sigmoid().flatten(1)
+ numerator = 2 * torch.matmul(inputs, labels.T)
+ # using broadcasting to get a [num_queries, NUM_CLASSES] matrix
+ denominator = inputs.sum(-1)[:, None] + labels.sum(-1)[None, :]
+ loss = 1 - (numerator + 1) / (denominator + 1)
+ return loss
+
+
+# Copied from transformers.models.mask2former.modeling_mask2former.pair_wise_sigmoid_cross_entropy_loss
+def pair_wise_sigmoid_cross_entropy_loss(inputs: torch.Tensor, labels: torch.Tensor) -> torch.Tensor:
+ r"""
+ A pair wise version of the cross entropy loss, see `sigmoid_cross_entropy_loss` for usage.
+
+ Args:
+ inputs (`torch.Tensor`):
+ A tensor representing a mask.
+ labels (`torch.Tensor`):
+ A tensor with the same shape as inputs. Stores the binary classification labels for each element in inputs
+ (0 for the negative class and 1 for the positive class).
+
+ Returns:
+ loss (`torch.Tensor`): The computed loss between each pairs.
+ """
+
+ height_and_width = inputs.shape[1]
+
+ criterion = nn.BCEWithLogitsLoss(reduction="none")
+ cross_entropy_loss_pos = criterion(inputs, torch.ones_like(inputs))
+ cross_entropy_loss_neg = criterion(inputs, torch.zeros_like(inputs))
+
+ loss_pos = torch.matmul(cross_entropy_loss_pos / height_and_width, labels.T)
+ loss_neg = torch.matmul(cross_entropy_loss_neg / height_and_width, (1 - labels).T)
+ loss = loss_pos + loss_neg
+ return loss
+
+
+# Copied from transformers.models.mask2former.modeling_mask2former.sample_point
+def sample_point(
+ input_features: torch.Tensor, point_coordinates: torch.Tensor, add_dim=False, **kwargs
+) -> torch.Tensor:
+ """
+ A wrapper around `torch.nn.functional.grid_sample` to support 3D point_coordinates tensors.
+
+ Args:
+ input_features (`torch.Tensor` of shape (batch_size, channels, height, width)):
+ A tensor that contains features map on a height * width grid
+ point_coordinates (`torch.Tensor` of shape (batch_size, num_points, 2) or (batch_size, grid_height, grid_width,:
+ 2)):
+ A tensor that contains [0, 1] * [0, 1] normalized point coordinates
+ add_dim (`bool`):
+ boolean value to keep track of added dimension
+
+ Returns:
+ point_features (`torch.Tensor` of shape (batch_size, channels, num_points) or (batch_size, channels,
+ height_grid, width_grid):
+ A tensor that contains features for points in `point_coordinates`.
+ """
+ if point_coordinates.dim() == 3:
+ add_dim = True
+ point_coordinates = point_coordinates.unsqueeze(2)
+
+ # use nn.function.grid_sample to get features for points in `point_coordinates` via bilinear interpolation
+ point_features = torch.nn.functional.grid_sample(input_features, 2.0 * point_coordinates - 1.0, **kwargs)
+ if add_dim:
+ point_features = point_features.squeeze(3)
+
+ return point_features
+
+
+# Refactored from https://github.com/SHI-Labs/OneFormer/blob/33ebb56ed34f970a30ae103e786c0cb64c653d9a/oneformer/modeling/matcher.py#L93
+class OneFormerHungarianMatcher(nn.Module):
+ def __init__(
+ self, cost_class: float = 1.0, cost_mask: float = 1.0, cost_dice: float = 1.0, num_points: int = 12544
+ ):
+ """This class computes an assignment between the labels and the predictions of the network.
+
+ For efficiency reasons, the labels don't include the no_object. Because of this, in general, there are more
+ predictions than labels. In this case, we do a 1-to-1 matching of the best predictions, while the others are
+ un-matched (and thus treated as non-objects).
+
+ Params:
+ cost_class (float, *optional*, defaults to 1.0):
+ This is the relative weight of the classification error in the matching cost.
+ cost_mask (float, *optional*, defaults to 1.0):
+ This is the relative weight of the sigmoid ce loss of the binary mask in the matching cost.
+ cost_dice (float, *optional*, defaults to 1.0):
+ This is the relative weight of the dice loss of the binary mask in the matching cost
+ num_points (int, *optional*, defaults to 12544):
+ Number of points to be sampled for dice and mask loss matching cost.
+ """
+ super().__init__()
+ if cost_class == 0 and cost_mask == 0 and cost_dice == 0:
+ raise ValueError("All costs can't be 0")
+ self.cost_class = cost_class
+ self.cost_mask = cost_mask
+ self.cost_dice = cost_dice
+ self.num_points = num_points
+
+ @torch.no_grad()
+ def forward(self, masks_queries_logits, class_queries_logits, mask_labels, class_labels) -> list[tuple[Tensor]]:
+ """Performs the matching
+
+ Params:
+ masks_queries_logits (`torch.Tensor`):
+ A tensor` of dim `batch_size, num_queries, num_labels` with the
+ classification logits.
+ class_queries_logits (`torch.Tensor`):
+ A tensor` of dim `batch_size, num_queries, height, width` with the
+ predicted masks.
+
+ class_labels (`torch.Tensor`):
+ A tensor` of dim `num_target_boxes` (where num_target_boxes is the number
+ of ground-truth objects in the target) containing the class labels.
+ mask_labels (`torch.Tensor`):
+ A tensor` of dim `num_target_boxes, height, width` containing the target
+ masks.
+
+ Returns:
+ `list[tuple[Tensor]]`: A list of size batch_size, containing tuples of (index_i, index_j) where:
+ - index_i is the indices of the selected predictions (in order)
+ - index_j is the indices of the corresponding selected labels (in order)
+ For each batch element, it holds:
+ len(index_i) = len(index_j) = min(num_queries, num_targets).
+ """
+ indices: list[tuple[np.array]] = []
+
+ num_queries = class_queries_logits.shape[1]
+
+ preds_masks = masks_queries_logits
+ preds_probs = class_queries_logits
+ # iterate through batch size
+ for pred_probs, pred_mask, target_mask, labels in zip(preds_probs, preds_masks, mask_labels, class_labels):
+ pred_probs = pred_probs.softmax(-1)
+ # Compute the classification cost. Contrary to the loss, we don't use the NLL,
+ # but approximate it in 1 - proba[target class].
+ # The 1 is a constant that doesn't change the matching, it can be omitted.
+ cost_class = -pred_probs[:, labels]
+
+ pred_mask = pred_mask[:, None]
+ target_mask = target_mask[:, None].to(pred_mask.device)
+
+ # all masks share the same set of points for efficient matching!
+ point_coords = torch.rand(1, self.num_points, 2, device=pred_mask.device)
+
+ # get ground truth labels
+ target_mask = sample_point(
+ target_mask,
+ point_coords.repeat(target_mask.shape[0], 1, 1),
+ align_corners=False,
+ ).squeeze(1)
+
+ pred_mask = sample_point(
+ pred_mask,
+ point_coords.repeat(pred_mask.shape[0], 1, 1),
+ align_corners=False,
+ ).squeeze(1)
+
+ with maybe_autocast(device_type="cuda", enabled=False):
+ pred_mask = pred_mask.float()
+ target_mask = target_mask.float()
+
+ # compute the sigmoid ce loss
+ cost_mask = pair_wise_sigmoid_cross_entropy_loss(pred_mask, target_mask)
+ # Compute the dice loss
+ cost_dice = pair_wise_dice_loss(pred_mask, target_mask)
+ # final cost matrix
+ cost_matrix = self.cost_mask * cost_mask + self.cost_class * cost_class + self.cost_dice * cost_dice
+ cost_matrix = cost_matrix.reshape(num_queries, -1).cpu()
+ # do the assigmented using the hungarian algorithm in scipy
+ assigned_indices: tuple[np.array] = linear_sum_assignment(cost_matrix.cpu())
+ indices.append(assigned_indices)
+
+ # It could be stacked in one tensor
+ matched_indices = [
+ (torch.as_tensor(i, dtype=torch.int64), torch.as_tensor(j, dtype=torch.int64)) for i, j in indices
+ ]
+ return matched_indices
+
+
+class OneFormerLoss(nn.Module):
+ def __init__(
+ self,
+ num_classes: int,
+ matcher: OneFormerHungarianMatcher,
+ weight_dict: dict[str, float],
+ eos_coef: float,
+ num_points: int,
+ oversample_ratio: float,
+ importance_sample_ratio: float,
+ contrastive_temperature: float | None = None,
+ ):
+ """
+ This class computes the losses using the class predictions, mask predictions and the contrastive queries.
+
+ Oneformer calculates the classification CE loss on the class predictions. Mask predictions are used for
+ calculating the binary CE loss and dice loss. The contrastive queries are used for calculating the contrastive
+ loss.
+
+ Args:
+ num_labels (`int`):
+ The number of classes.
+ matcher (`OneFormerHungarianMatcher`):
+ A torch module that computes the assignments between the predictions and labels.
+ weight_dict (`dict[str, float]`):
+ A dictionary of weights to be applied to the different losses.
+ eos_coef (`float`):
+ Weight to apply to the null class.
+ num_points (`int`):
+ Number of points to be sampled for dice and mask loss calculations.
+ oversample_ratio (`float`):
+ Required for pointwise loss calculation.
+ importance_sample_ratio (`float`):
+ Required for pointwise loss calculation.
+ contrastive_temperature (`float`):
+ Temperature for scaling the contrastive logits.
+ """
+ requires_backends(self, ["scipy"])
+ super().__init__()
+ self.num_classes = num_classes
+ self.matcher = matcher
+ self.weight_dict = weight_dict
+ self.eos_coef = eos_coef
+ empty_weight = torch.ones(self.num_classes + 1)
+ empty_weight[-1] = self.eos_coef
+ self.register_buffer("empty_weight", empty_weight)
+
+ # pointwise mask loss parameters
+ self.num_points = num_points
+ self.oversample_ratio = oversample_ratio
+ self.importance_sample_ratio = importance_sample_ratio
+ self.contrastive_temperature = contrastive_temperature
+ if self.contrastive_temperature is not None:
+ self.logit_scale = nn.Parameter(torch.tensor(np.log(1 / contrastive_temperature)))
+
+ def _max_by_axis(self, the_list: list[list[int]]) -> list[int]:
+ maxes = the_list[0]
+ for sublist in the_list[1:]:
+ for index, item in enumerate(sublist):
+ maxes[index] = max(maxes[index], item)
+ return maxes
+
+ def _pad_images_to_max_in_batch(self, tensors: list[Tensor]) -> tuple[Tensor, Tensor]:
+ # get the maximum size in the batch
+ max_size = self._max_by_axis([list(tensor.shape) for tensor in tensors])
+ batch_size = len(tensors)
+ # compute finel size
+ batch_shape = [batch_size] + max_size
+ b, _, h, w = batch_shape
+ # get metadata
+ dtype = tensors[0].dtype
+ device = tensors[0].device
+ padded_tensors = torch.zeros(batch_shape, dtype=dtype, device=device)
+ padding_masks = torch.ones((b, h, w), dtype=torch.bool, device=device)
+ # pad the tensors to the size of the biggest one
+ for tensor, padded_tensor, padding_mask in zip(tensors, padded_tensors, padding_masks):
+ padded_tensor[: tensor.shape[0], : tensor.shape[1], : tensor.shape[2]].copy_(tensor)
+ padding_mask[: tensor.shape[1], : tensor.shape[2]] = False
+
+ return padded_tensors, padding_masks
+
+ def loss_contrastive(self, contrastive_queries_logits: Tensor, text_queries: Tensor):
+ """Compute the query-text contrastive loss.
+
+ Args:
+ contrastive_queries_logits (`torch.Tensor`):
+ A tensor of shape `batch_size, num_queries, hidden_dim`
+ text_queries (`torch.Tensor`):
+ A tensor of shape `batch_size, num_queries, hidden_dim`
+ Returns:
+ `dict[str, Tensor]`: A dict of `torch.Tensor` containing the following key:
+ - **loss_contrastive** -- The query-text contrastive loss computed using task-guided queries
+ and text queries derived from input text list.
+ """
+
+ image_queries = contrastive_queries_logits.float()
+
+ # [batch_size, hidden_dim]
+ image_queries = nn.functional.normalize(image_queries.flatten(1), dim=-1)
+ text_queries = nn.functional.normalize(text_queries.flatten(1), dim=-1)
+
+ logit_scale = torch.clamp(self.logit_scale.exp(), max=100)
+
+ logits_per_text = torch.matmul(text_queries, image_queries.t()) * logit_scale
+ logits_per_img = logits_per_text.t()
+
+ loss_img = nn.functional.cross_entropy(
+ logits_per_img, torch.arange(len(logits_per_img), device=logits_per_text.device)
+ )
+ loss_text = nn.functional.cross_entropy(
+ logits_per_text, torch.arange(len(logits_per_text), device=logits_per_text.device)
+ )
+
+ loss_contrastive = loss_img + loss_text
+
+ losses = {"loss_contrastive": loss_contrastive}
+ return losses
+
+ def loss_labels(
+ self, class_queries_logits: Tensor, class_labels: list[Tensor], indices: tuple[np.array]
+ ) -> dict[str, Tensor]:
+ """Compute the losses related to the labels using cross entropy.
+
+ Args:
+ class_queries_logits (`torch.Tensor`):
+ A tensor of shape `batch_size, num_queries, num_labels`
+ class_labels (`list[torch.Tensor]`):
+ List of class labels of shape `(labels)`.
+ indices (`tuple[np.array])`:
+ The indices computed by the Hungarian matcher.
+
+ Returns:
+ `dict[str, Tensor]`: A dict of `torch.Tensor` containing the following key:
+ - **loss_cross_entropy** -- The loss computed using cross entropy on the predicted and ground truth labels.
+ """
+ pred_logits = class_queries_logits
+ batch_size, num_queries, _ = pred_logits.shape
+ criterion = nn.CrossEntropyLoss(weight=self.empty_weight)
+ idx = self._get_predictions_permutation_indices(indices)
+
+ # shape = (batch_size, num_queries)
+ target_classes_o = torch.cat([target[j] for target, (_, j) in zip(class_labels, indices)])
+ # shape = (batch_size, num_queries)
+ target_classes = torch.full(
+ (batch_size, num_queries), fill_value=self.num_classes, dtype=torch.int64, device=pred_logits.device
+ )
+ target_classes[idx] = target_classes_o
+ # permute pred_logits (batch_size, num_queries, num_labels) -> (batch_size, num_labels, num_queries)
+ pred_logits_transposed = pred_logits.transpose(1, 2)
+ loss_ce = criterion(pred_logits_transposed, target_classes)
+ losses = {"loss_cross_entropy": loss_ce}
+ return losses
+
+ def loss_masks(
+ self, masks_queries_logits: Tensor, mask_labels: list[Tensor], indices: tuple[np.array], num_masks: int
+ ) -> dict[str, Tensor]:
+ """Compute the losses related to the masks using focal and dice loss.
+
+ Args:
+ masks_queries_logits (`torch.Tensor`):
+ A tensor of shape `batch_size, num_queries, height, width`
+ mask_labels (`torch.Tensor`):
+ List of mask labels of shape `(labels, height, width)`.
+ indices (`tuple[np.array])`:
+ The indices computed by the Hungarian matcher.
+ num_masks (`int)`:
+ The number of masks, used for normalization.
+
+ Returns:
+ `dict[str, Tensor]`: A dict of `torch.Tensor` containing two keys:
+ - **loss_mask** -- The loss computed using sigmoid ce loss on the predicted and ground truth masks.
+ - **loss_dice** -- The loss computed using dice loss on the predicted on the predicted and ground truth
+ masks.
+ """
+ src_idx = self._get_predictions_permutation_indices(indices)
+ tgt_idx = self._get_targets_permutation_indices(indices)
+ # shape (batch_size * num_queries, height, width)
+ pred_masks = masks_queries_logits[src_idx]
+ # shape (batch_size, num_queries, height, width)
+ # pad all and stack the targets to the num_labels dimension
+ # upsample predictions to the target size, we have to add one dim to use interpolate
+ target_masks, _ = self._pad_images_to_max_in_batch(mask_labels)
+ target_masks = target_masks[tgt_idx]
+
+ pred_masks = pred_masks[:, None]
+ target_masks = target_masks[:, None]
+
+ with torch.no_grad():
+ # sample point_coords
+ point_coords = self.sample_points_using_uncertainty(
+ pred_masks,
+ self.calculate_uncertainty,
+ self.num_points,
+ self.oversample_ratio,
+ self.importance_sample_ratio,
+ )
+ # get ground-truth labels
+ point_labels = sample_point(target_masks, point_coords, align_corners=False).squeeze(1)
+
+ point_logits = sample_point(pred_masks, point_coords, align_corners=False).squeeze(1)
+
+ losses = {
+ "loss_mask": sigmoid_cross_entropy_loss(point_logits, point_labels, num_masks),
+ "loss_dice": dice_loss(point_logits, point_labels, num_masks),
+ }
+
+ del pred_masks
+ del target_masks
+ return losses
+
+ # Copied from transformers.models.mask2former.modeling_mask2former.Mask2FormerLoss.calculate_uncertainty
+ def calculate_uncertainty(self, logits: torch.Tensor) -> torch.Tensor:
+ """
+ In Mask2Former paper, uncertainty is estimated as L1 distance between 0.0 and the logit prediction in 'logits'
+ for the foreground class in `classes`.
+
+ Args:
+ logits (`torch.Tensor`):
+ A tensor of shape (R, 1, ...) for class-specific or class-agnostic, where R is the total number of predicted masks in all images and C is:
+ the number of foreground classes. The values are logits.
+
+ Returns:
+ scores (`torch.Tensor`): A tensor of shape (R, 1, ...) that contains uncertainty scores with the most
+ uncertain locations having the highest uncertainty score.
+ """
+ uncertainty_scores = -(torch.abs(logits))
+ return uncertainty_scores
+
+ # Copied from transformers.models.mask2former.modeling_mask2former.Mask2FormerLoss.sample_points_using_uncertainty
+ def sample_points_using_uncertainty(
+ self,
+ logits: torch.Tensor,
+ uncertainty_function,
+ num_points: int,
+ oversample_ratio: int,
+ importance_sample_ratio: float,
+ ) -> torch.Tensor:
+ """
+ This function is meant for sampling points in [0, 1] * [0, 1] coordinate space based on their uncertainty. The
+ uncertainty is calculated for each point using the passed `uncertainty function` that takes points logit
+ prediction as input.
+
+ Args:
+ logits (`float`):
+ Logit predictions for P points.
+ uncertainty_function:
+ A function that takes logit predictions for P points and returns their uncertainties.
+ num_points (`int`):
+ The number of points P to sample.
+ oversample_ratio (`int`):
+ Oversampling parameter.
+ importance_sample_ratio (`float`):
+ Ratio of points that are sampled via importance sampling.
+
+ Returns:
+ point_coordinates (`torch.Tensor`):
+ Coordinates for P sampled points.
+ """
+
+ num_boxes = logits.shape[0]
+ num_points_sampled = int(num_points * oversample_ratio)
+
+ # Get random point coordinates
+ point_coordinates = torch.rand(num_boxes, num_points_sampled, 2, device=logits.device)
+ # Get sampled prediction value for the point coordinates
+ point_logits = sample_point(logits, point_coordinates, align_corners=False)
+ # Calculate the uncertainties based on the sampled prediction values of the points
+ point_uncertainties = uncertainty_function(point_logits)
+
+ num_uncertain_points = int(importance_sample_ratio * num_points)
+ num_random_points = num_points - num_uncertain_points
+
+ idx = torch.topk(point_uncertainties[:, 0, :], k=num_uncertain_points, dim=1)[1]
+ shift = num_points_sampled * torch.arange(num_boxes, dtype=torch.long, device=logits.device)
+ idx += shift[:, None]
+ point_coordinates = point_coordinates.view(-1, 2)[idx.view(-1), :].view(num_boxes, num_uncertain_points, 2)
+
+ if num_random_points > 0:
+ point_coordinates = torch.cat(
+ [point_coordinates, torch.rand(num_boxes, num_random_points, 2, device=logits.device)],
+ dim=1,
+ )
+ return point_coordinates
+
+ def _get_predictions_permutation_indices(self, indices):
+ # permute predictions following indices
+ batch_indices = torch.cat([torch.full_like(src, i) for i, (src, _) in enumerate(indices)])
+ predictions_indices = torch.cat([src for (src, _) in indices])
+ return batch_indices, predictions_indices
+
+ def _get_targets_permutation_indices(self, indices):
+ # permute labels following indices
+ batch_indices = torch.cat([torch.full_like(tgt, i) for i, (_, tgt) in enumerate(indices)])
+ target_indices = torch.cat([tgt for (_, tgt) in indices])
+ return batch_indices, target_indices
+
+ def forward(
+ self,
+ masks_queries_logits: Tensor,
+ class_queries_logits: Tensor,
+ contrastive_queries_logits: Tensor,
+ mask_labels: list[Tensor],
+ class_labels: list[Tensor],
+ text_queries: Tensor,
+ auxiliary_predictions: dict[str, Tensor] | None = None,
+ calculate_contrastive_loss: bool = True,
+ ) -> dict[str, Tensor]:
+ """
+ This performs the loss computation.
+
+ Args:
+ masks_queries_logits (`torch.Tensor`):
+ A tensor of shape `batch_size, num_queries, height, width`
+ class_queries_logits (`torch.Tensor`):
+ A tensor of shape `batch_size, num_queries, num_labels`
+ contrastive_queries_logits (`torch.Tensor`):
+ A tensor of shape `batch_size, num_queries, hidden_dim`
+ mask_labels (`torch.Tensor`):
+ List of mask labels of shape `(labels, height, width)`.
+ class_labels (`list[torch.Tensor]`):
+ List of class labels of shape `(labels)`.
+ text_queries (`torch.Tensor`):
+ A tensor of shape `batch_size, num_queries, hidden_dim`
+ auxiliary_predictions (`dict[str, torch.Tensor]`, *optional*):
+ if `use_auxiliary_loss` was set to `true` in [`OneFormerConfig`], then it contains the logits from the
+ inner layers of the Detr's Decoder.
+ calculate_contrastive_loss (`bool`, *optional*, defaults to `True`):
+ Whether or not to calculate the contrastive loss.
+
+ Returns:
+ `dict[str, Tensor]`: A dict of `torch.Tensor` containing two keys:
+ - **loss_cross_entropy** -- The loss computed using cross entropy on the predicted and ground truth labels.
+ - **loss_mask** -- The loss computed using sigmoid ce loss on the predicted and ground truth masks.
+ - **loss_dice** -- The loss computed using dice loss on the predicted on the predicted and ground truth
+ masks.
+ - **loss_contrastive** -- The query-text contrstive loss computed using object and text queries.
+ if `use_auxiliary_loss` was set to `true` in [`OneFormerConfig`], the dictionary contains additional losses
+ for each auxiliary predictions.
+ """
+
+ # retrieve the matching between the outputs of the last layer and the labels
+ indices = self.matcher(masks_queries_logits, class_queries_logits, mask_labels, class_labels)
+ # compute the average number of target masks for normalization purposes
+ num_masks = self.get_num_masks(class_labels, device=class_labels[0].device)
+ # get all the losses
+ losses: dict[str, Tensor] = {
+ **self.loss_masks(masks_queries_logits, mask_labels, indices, num_masks),
+ **self.loss_labels(class_queries_logits, class_labels, indices),
+ }
+ if calculate_contrastive_loss:
+ losses = {**losses, **self.loss_contrastive(contrastive_queries_logits, text_queries)}
+
+ # in case of auxiliary losses, we repeat this process with the output of each intermediate layer.
+ if auxiliary_predictions is not None:
+ for idx, aux_outputs in enumerate(auxiliary_predictions):
+ masks_queries_logits = aux_outputs["masks_queries_logits"]
+ class_queries_logits = aux_outputs["class_queries_logits"]
+ loss_dict = self.forward(
+ masks_queries_logits,
+ class_queries_logits,
+ None,
+ mask_labels,
+ class_labels,
+ None,
+ calculate_contrastive_loss=False,
+ )
+ loss_dict = {f"{key}_{idx}": value for key, value in loss_dict.items()}
+ losses.update(loss_dict)
+
+ return losses
+
+ def get_num_masks(self, class_labels: torch.Tensor, device: torch.device) -> torch.Tensor:
+ """
+ Computes the average number of target masks across the batch, for normalization purposes.
+ """
+ num_masks = sum(len(classes) for classes in class_labels)
+ num_masks = torch.as_tensor([num_masks], dtype=torch.float, device=device)
+ world_size = 1
+ if is_accelerate_available():
+ if PartialState._shared_state != {}:
+ num_masks = reduce(num_masks)
+ world_size = PartialState().num_processes
+
+ num_masks = torch.clamp(num_masks / world_size, min=1)
+ return num_masks
+
+
+@auto_docstring(
+ custom_intro="""
+ Base class for outputs of the Transformer decoder. This class adds attributes for class predictions, mask
+ predictions and contrastive logits to BaseModelOutputWithCrossAttentions.
+ """
+)
+@dataclass
+class OneFormerTransformerDecoderOutput(BaseModelOutput):
+ r"""
+ object_queries (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_dim)`):
+ Queries representation for the region proposals.
+ contrastive_logits (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_dim)`):
+ Queries representation for the contrastive loss.
+ prediction_masks (`torch.FloatTensor` of shape `(batch_size, num_queries, height, width)`):
+ Mask predictions from last layer of the transformer decoder.
+ prediction_class (`torch.FloatTensor` of shape `(batch_size, num_queries, num_classes+1)`):
+ Class predictions from last layer of the transformer decoder.
+ auxiliary_predictions (Tuple of Dict of `str, torch.FloatTensor`, *optional*):
+ Tuple of class and mask predictions from each layer of the transformer decoder.
+ """
+
+ object_queries: torch.FloatTensor | None = None
+ contrastive_logits: torch.FloatTensor | None = None
+ prediction_masks: torch.FloatTensor | None = None
+ prediction_class: torch.FloatTensor | None = None
+ auxiliary_predictions: tuple[dict[str, torch.FloatTensor]] | None = None
+
+
+@auto_docstring(
+ custom_intro="""
+ OneFormer's pixel decoder module output, practically a Multi-Scale Deformable Attention based decoder. It returns
+ the mask features and the multiscale features.
+ """
+)
+@dataclass
+# Copied from transformers.models.mask2former.modeling_mask2former.Mask2FormerPixelDecoderOutput with Mask2->One
+class OneFormerPixelDecoderOutput(ModelOutput):
+ r"""
+ multi_scale_features (`tuple(torch.FloatTensor)`):
+ Tuple of multi-scale features of scales [1/8, 1/16, 1/32] and shape `(batch_size, num_channels, height,
+ width)`from the Multi-Scale Deformable Attenntion based Pixel Decoder.
+ mask_features (`torch.FloatTensor`):
+ Tensor of shape `(batch_size, num_channels, height, width)`, 1/4 scale features from the last Pixel Decoder
+ Layer.
+ attentions (`tuple(torch.FloatTensor)`, *optional*):
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
+ sequence_length)`. Attentions weights from pixel decoder. Returned when `output_attentions=True` is passed
+ or when `config.output_attentions=True`
+ """
+
+ multi_scale_features: tuple[torch.FloatTensor] | None = None
+ mask_features: torch.FloatTensor | None = None
+ attentions: tuple[torch.FloatTensor] | None = None
+
+
+@auto_docstring(
+ custom_intro="""
+ OneFormer's pixel level module output. It returns both the last and (optionally) the hidden states from the
+ `encoder` and `decoder`. By default, the `encoder` is a Swin/Dinat Backbone and the `decoder` is a Multi-Scale
+ Deformable Attention based decoder.
+ """
+)
+@dataclass
+class OneFormerPixelLevelModuleOutput(ModelOutput):
+ r"""
+ encoder_features (List of `(torch.FloatTensor)`):
+ List of `torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`. Hidden-states (also
+ called feature maps) of the model at the output of each stage.
+ decoder_features (List of `(torch.FloatTensor)`):
+ List of `torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`. Hidden-states (also
+ called feature maps) of the model at the output of each stage.
+ decoder_last_feature (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)):
+ 1/4 scale features from the last Pixel Decoder Layer.
+ """
+
+ encoder_features: list[torch.FloatTensor] | None = None
+ decoder_features: list[torch.FloatTensor] | None = None
+ decoder_last_feature: torch.FloatTensor | None = None
+
+
+@auto_docstring(
+ custom_intro="""
+ Class for outputs of [`OneFormerModel`]. This class returns all the needed hidden states to compute the logits.
+ """
+)
+@dataclass
+class OneFormerModelOutput(ModelOutput):
+ r"""
+ encoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
+ shape `(batch_size, num_channels, height, width)`. Hidden-states (also called feature maps) of the encoder
+ model at the output of each stage.
+ pixel_decoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
+ shape `(batch_size, num_channels, height, width)`. Hidden-states (also called feature maps) of the pixel
+ decoder model at the output of each stage.
+ transformer_decoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
+ shape `(batch_size, sequence_length, hidden_size)`. Hidden-states (also called feature maps) of the
+ transformer decoder at the output of each stage.
+ transformer_decoder_object_queries (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_dim)`):
+ Output object queries from the last layer in the transformer decoder.
+ transformer_decoder_contrastive_queries (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_dim)`):
+ Contrastive queries from the transformer decoder.
+ transformer_decoder_mask_predictions (`torch.FloatTensor` of shape `(batch_size, num_queries, height, width)`):
+ Mask Predictions from the last layer in the transformer decoder.
+ transformer_decoder_class_predictions (`torch.FloatTensor` of shape `(batch_size, num_queries, num_classes+1)`):
+ Class Predictions from the last layer in the transformer decoder.
+ transformer_decoder_auxiliary_predictions (Tuple of Dict of `str, torch.FloatTensor`, *optional*):
+ Tuple of class and mask predictions from each layer of the transformer decoder.
+ text_queries (`torch.FloatTensor`, *optional* of shape `(batch_size, num_queries, hidden_dim)`):
+ Text queries derived from the input text list used for calculating contrastive loss during training.
+ task_token (`torch.FloatTensor` of shape `(batch_size, hidden_dim)`):
+ 1D task token to condition the queries.
+ attentions (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
+ Tuple of `tuple(torch.FloatTensor)` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
+ sequence_length)`. Self and Cross Attentions weights from transformer decoder.
+ """
+
+ encoder_hidden_states: tuple[torch.FloatTensor] | None = None
+ pixel_decoder_hidden_states: tuple[torch.FloatTensor] | None = None
+ transformer_decoder_hidden_states: torch.FloatTensor | None = None
+ transformer_decoder_object_queries: torch.FloatTensor | None = None
+ transformer_decoder_contrastive_queries: torch.FloatTensor | None = None
+ transformer_decoder_mask_predictions: torch.FloatTensor | None = None
+ transformer_decoder_class_predictions: torch.FloatTensor | None = None
+ transformer_decoder_auxiliary_predictions: tuple[dict[str, torch.FloatTensor]] | None = None
+ text_queries: torch.FloatTensor | None = None
+ task_token: torch.FloatTensor | None = None
+ attentions: tuple[torch.FloatTensor] | None = None
+
+
+@auto_docstring(
+ custom_intro="""
+ Class for outputs of [`OneFormerForUniversalSegmentationOutput`].
+
+ This output can be directly passed to [`~OneFormerImageProcessor.post_process_semantic_segmentation`] or
+ [`~OneFormerImageProcessor.post_process_instance_segmentation`] or
+ [`~OneFormerImageProcessor.post_process_panoptic_segmentation`] depending on the task. Please, see
+ [`~OneFormerImageProcessor] for details regarding usage.
+ """
+)
+@dataclass
+class OneFormerForUniversalSegmentationOutput(ModelOutput):
+ r"""
+ loss (`torch.Tensor`, *optional*):
+ The computed loss, returned when labels are present.
+ class_queries_logits (`torch.FloatTensor`):
+ A tensor of shape `(batch_size, num_queries, num_labels + 1)` representing the proposed classes for each
+ query. Note the `+ 1` is needed because we incorporate the null class.
+ masks_queries_logits (`torch.FloatTensor`):
+ A tensor of shape `(batch_size, num_queries, height, width)` representing the proposed masks for each
+ query.
+ auxiliary_predictions (List of Dict of `str, torch.FloatTensor`, *optional*):
+ List of class and mask predictions from each layer of the transformer decoder.
+ encoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
+ shape `(batch_size, num_channels, height, width)`. Hidden-states (also called feature maps) of the encoder
+ model at the output of each stage.
+ pixel_decoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
+ shape `(batch_size, num_channels, height, width)`. Hidden-states (also called feature maps) of the pixel
+ decoder model at the output of each stage.
+ transformer_decoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
+ shape `(batch_size, sequence_length, hidden_size)`. Hidden-states (also called feature maps) of the
+ transformer decoder at the output of each stage.
+ transformer_decoder_object_queries (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_dim)`):
+ Output object queries from the last layer in the transformer decoder.
+ transformer_decoder_contrastive_queries (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_dim)`):
+ Contrastive queries from the transformer decoder.
+ transformer_decoder_mask_predictions (`torch.FloatTensor` of shape `(batch_size, num_queries, height, width)`):
+ Mask Predictions from the last layer in the transformer decoder.
+ transformer_decoder_class_predictions (`torch.FloatTensor` of shape `(batch_size, num_queries, num_classes+1)`):
+ Class Predictions from the last layer in the transformer decoder.
+ transformer_decoder_auxiliary_predictions (List of Dict of `str, torch.FloatTensor`, *optional*):
+ List of class and mask predictions from each layer of the transformer decoder.
+ text_queries (`torch.FloatTensor`, *optional* of shape `(batch_size, num_queries, hidden_dim)`):
+ Text queries derived from the input text list used for calculating contrastive loss during training.
+ task_token (`torch.FloatTensor` of shape `(batch_size, hidden_dim)`):
+ 1D task token to condition the queries.
+ attentions (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
+ Tuple of `tuple(torch.FloatTensor)` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
+ sequence_length)`. Self and Cross Attentions weights from transformer decoder.
+ """
+
+ loss: torch.FloatTensor | None = None
+ class_queries_logits: torch.FloatTensor | None = None
+ masks_queries_logits: torch.FloatTensor | None = None
+ auxiliary_predictions: list[dict[str, torch.FloatTensor]] = None
+ encoder_hidden_states: tuple[torch.FloatTensor] | None = None
+ pixel_decoder_hidden_states: list[torch.FloatTensor] | None = None
+ transformer_decoder_hidden_states: torch.FloatTensor | None = None
+ transformer_decoder_object_queries: torch.FloatTensor | None = None
+ transformer_decoder_contrastive_queries: torch.FloatTensor | None = None
+ transformer_decoder_mask_predictions: torch.FloatTensor | None = None
+ transformer_decoder_class_predictions: torch.FloatTensor | None = None
+ transformer_decoder_auxiliary_predictions: list[dict[str, torch.FloatTensor]] | None = None
+ text_queries: torch.FloatTensor | None = None
+ task_token: torch.FloatTensor | None = None
+ attentions: tuple[tuple[torch.FloatTensor]] | None = None
+
+
+# Modified from transformers.models.detr.modeling_deformable_detr.DeformableDetrMultiscaleDeformableAttention with DeformableDetr->OneFormerPixelDecoderEncoder
+class OneFormerPixelDecoderEncoderMultiscaleDeformableAttention(nn.Module):
+ """
+ Multiscale deformable attention as proposed in Deformable DETR.
+ """
+
+ def __init__(self, embed_dim: int, num_heads: int, n_levels: int, n_points: int):
+ super().__init__()
+ if embed_dim % num_heads != 0:
+ raise ValueError(
+ f"embed_dim (d_model) must be divisible by num_heads, but got {embed_dim} and {num_heads}"
+ )
+ dim_per_head = embed_dim // num_heads
+ # check if dim_per_head is power of 2
+ if not ((dim_per_head & (dim_per_head - 1) == 0) and dim_per_head != 0):
+ warnings.warn(
+ "You'd better set embed_dim (d_model) in DeformableDetrMultiscaleDeformableAttention to make the"
+ " dimension of each attention head a power of 2 which is more efficient in the authors' CUDA"
+ " implementation."
+ )
+
+ self.im2col_step = 128
+
+ self.d_model = embed_dim
+ self.n_levels = n_levels
+ self.n_heads = num_heads
+ self.n_points = n_points
+
+ self.sampling_offsets = nn.Linear(embed_dim, num_heads * n_levels * n_points * 2)
+ self.attention_weights = nn.Linear(embed_dim, num_heads * n_levels * n_points)
+ self.value_proj = nn.Linear(embed_dim, embed_dim)
+ self.output_proj = nn.Linear(embed_dim, embed_dim)
+
+ def with_pos_embed(self, tensor: torch.Tensor, position_embeddings: Tensor | None):
+ return tensor if position_embeddings is None else tensor + position_embeddings
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor | None = None,
+ encoder_hidden_states=None,
+ encoder_attention_mask=None,
+ position_embeddings: torch.Tensor | None = None,
+ reference_points=None,
+ spatial_shapes=None,
+ level_start_index=None,
+ output_attentions: bool = False,
+ ):
+ # add position embeddings to the hidden states before projecting to queries and keys
+ if position_embeddings is not None:
+ hidden_states = self.with_pos_embed(hidden_states, position_embeddings)
+
+ batch_size, num_queries, _ = hidden_states.shape
+ batch_size, sequence_length, _ = encoder_hidden_states.shape
+ torch_compilable_check(
+ (spatial_shapes[:, 0] * spatial_shapes[:, 1]).sum() == sequence_length,
+ "Make sure to align the spatial shapes with the sequence length of the encoder hidden states",
+ )
+
+ value = self.value_proj(encoder_hidden_states)
+ if attention_mask is not None:
+ # we invert the attention_mask
+ value = value.masked_fill(attention_mask[..., None], float(0))
+ value = value.view(batch_size, sequence_length, self.n_heads, self.d_model // self.n_heads)
+ sampling_offsets = self.sampling_offsets(hidden_states).view(
+ batch_size, num_queries, self.n_heads, self.n_levels, self.n_points, 2
+ )
+ attention_weights = self.attention_weights(hidden_states).view(
+ batch_size, num_queries, self.n_heads, self.n_levels * self.n_points
+ )
+ attention_weights = nn.functional.softmax(attention_weights, -1).view(
+ batch_size, num_queries, self.n_heads, self.n_levels, self.n_points
+ )
+ # batch_size, num_queries, n_heads, n_levels, n_points, 2
+ if reference_points.shape[-1] == 2:
+ offset_normalizer = torch.stack([spatial_shapes[..., 1], spatial_shapes[..., 0]], -1)
+ sampling_locations = (
+ reference_points[:, :, None, :, None, :]
+ + sampling_offsets / offset_normalizer[None, None, None, :, None, :]
+ )
+ elif reference_points.shape[-1] == 4:
+ sampling_locations = (
+ reference_points[:, :, None, :, None, :2]
+ + sampling_offsets / self.n_points * reference_points[:, :, None, :, None, 2:] * 0.5
+ )
+ else:
+ raise ValueError(f"Last dim of reference_points must be 2 or 4, but got {reference_points.shape[-1]}")
+ # PyTorch implementation
+ output = multi_scale_deformable_attention(value, spatial_shapes, sampling_locations, attention_weights)
+ output = self.output_proj(output)
+
+ return output, attention_weights
+
+
+class OneFormerPixelDecoderEncoderLayer(nn.Module):
+ def __init__(self, config: OneFormerConfig):
+ super().__init__()
+ self.embed_dim = config.conv_dim
+ self.self_attn = OneFormerPixelDecoderEncoderMultiscaleDeformableAttention(
+ embed_dim=self.embed_dim,
+ num_heads=config.num_attention_heads,
+ n_levels=3,
+ n_points=4,
+ )
+
+ self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
+ self.dropout = config.dropout
+ self.activation_fn = nn.functional.relu
+ self.activation_dropout = config.dropout
+ self.fc1 = nn.Linear(self.embed_dim, config.encoder_feedforward_dim)
+ self.fc2 = nn.Linear(config.encoder_feedforward_dim, self.embed_dim)
+ self.final_layer_norm = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
+
+ self.is_training = config.is_training
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor,
+ position_embeddings: torch.Tensor | None = None,
+ reference_points=None,
+ spatial_shapes=None,
+ level_start_index=None,
+ output_attentions: bool = False,
+ ):
+ """
+ Args:
+ hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
+ Input to the layer.
+ attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
+ Attention mask.
+ position_embeddings (`torch.FloatTensor`, *optional*):
+ Position embeddings, to be added to `hidden_states`.
+ reference_points (`torch.FloatTensor`, *optional*):
+ Reference points.
+ spatial_shapes (`torch.LongTensor`, *optional*):
+ Spatial shapes of the backbone feature maps.
+ level_start_index (`torch.LongTensor`, *optional*):
+ Level start index.
+ output_attentions (`bool`, *optional*):
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
+ returned tensors for more detail.
+ """
+ residual = hidden_states
+
+ # Apply Multi-scale Deformable Attention Module on the multi-scale feature maps.
+ hidden_states, attn_weights = self.self_attn(
+ hidden_states=hidden_states,
+ attention_mask=attention_mask,
+ encoder_hidden_states=hidden_states,
+ encoder_attention_mask=attention_mask,
+ position_embeddings=position_embeddings,
+ reference_points=reference_points,
+ spatial_shapes=spatial_shapes,
+ level_start_index=level_start_index,
+ output_attentions=output_attentions,
+ )
+
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.is_training)
+ hidden_states = residual + hidden_states
+ hidden_states = self.self_attn_layer_norm(hidden_states)
+
+ residual = hidden_states
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
+ hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.is_training)
+
+ hidden_states = self.fc2(hidden_states)
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.is_training)
+
+ hidden_states = residual + hidden_states
+ hidden_states = self.final_layer_norm(hidden_states)
+
+ if self.is_training:
+ if not torch.isfinite(hidden_states).all():
+ clamp_value = torch.finfo(hidden_states.dtype).max - 1000
+ hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
+
+ outputs = (hidden_states,)
+
+ if output_attentions:
+ outputs += (attn_weights,)
+
+ return outputs
+
+
+# Modified from from transformers.models.detr.modeling_deformable_detr.DeformableDetrEncoder with DeformableDetrEncoder->OneFormerPixelDecoderEncoderOnly
+class OneFormerPixelDecoderEncoderOnly(nn.Module):
+ """
+ Transformer encoder consisting of *config.encoder_layers* deformable attention layers. Each layer is a
+ [`OneFormerPixelDecoderEncoderLayer`].
+
+ The encoder updates the flattened multi-scale feature maps through multiple deformable attention layers.
+
+ Args:
+ config: OneFormerConfig
+ """
+
+ def __init__(self, config: OneFormerConfig):
+ super().__init__()
+
+ self.config = config
+ self.dropout = config.dropout
+ self.layers = nn.ModuleList([OneFormerPixelDecoderEncoderLayer(config) for _ in range(config.encoder_layers)])
+
+ @staticmethod
+ def get_reference_points(spatial_shapes, valid_ratios, device):
+ """
+ Get reference points for each feature map. Used in decoder.
+
+ Args:
+ spatial_shapes (`torch.LongTensor` of shape `(num_feature_levels, 2)`):
+ Spatial shapes of each feature map.
+ valid_ratios (`torch.FloatTensor` of shape `(batch_size, num_feature_levels, 2)`):
+ Valid ratios of each feature map.
+ device (`torch.device`):
+ Device on which to create the tensors.
+ Returns:
+ `torch.FloatTensor` of shape `(batch_size, num_queries, num_feature_levels, 2)`
+ """
+ reference_points_list = []
+ for lvl, (height, width) in enumerate(spatial_shapes):
+ ref_y, ref_x = torch.meshgrid(
+ torch.linspace(0.5, height - 0.5, height, dtype=valid_ratios.dtype, device=device),
+ torch.linspace(0.5, width - 0.5, width, dtype=valid_ratios.dtype, device=device),
+ indexing="ij",
+ )
+ ref_y = ref_y.reshape(-1)[None] / (valid_ratios[:, None, lvl, 1] * height)
+ ref_x = ref_x.reshape(-1)[None] / (valid_ratios[:, None, lvl, 0] * width)
+ ref = torch.stack((ref_x, ref_y), -1)
+ reference_points_list.append(ref)
+ reference_points = torch.cat(reference_points_list, 1)
+ reference_points = reference_points[:, :, None] * valid_ratios[:, None]
+ return reference_points
+
+ def forward(
+ self,
+ inputs_embeds=None,
+ attention_mask=None,
+ position_embeddings=None,
+ spatial_shapes=None,
+ level_start_index=None,
+ valid_ratios=None,
+ output_attentions=None,
+ output_hidden_states=None,
+ return_dict=None,
+ ):
+ r"""
+ Args:
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
+ Flattened feature map (output of the backbone + projection layer) that is passed to the encoder.
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Mask to avoid performing attention on padding pixel features. Mask values selected in `[0, 1]`:
+ - 1 for pixel features that are real (i.e. **not masked**),
+ - 0 for pixel features that are padding (i.e. **masked**).
+ [What are attention masks?](../glossary#attention-mask)
+ position_embeddings (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
+ Position embeddings that are added to the queries and keys in each self-attention layer.
+ spatial_shapes (`torch.LongTensor` of shape `(num_feature_levels, 2)`):
+ Spatial shapes of each feature map.
+ level_start_index (`torch.LongTensor` of shape `(num_feature_levels)`):
+ Starting index of each feature map.
+ valid_ratios (`torch.FloatTensor` of shape `(batch_size, num_feature_levels, 2)`):
+ Ratio of valid area in each feature level.
+ output_attentions (`bool`, *optional*):
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
+ returned tensors for more detail.
+ output_hidden_states (`bool`, *optional*):
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
+ for more detail.
+ return_dict (`bool`, *optional*):
+ Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple.
+ """
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ hidden_states = inputs_embeds
+ reference_points = self.get_reference_points(spatial_shapes, valid_ratios, device=inputs_embeds.device)
+
+ encoder_states = () if output_hidden_states else None
+ all_attentions = () if output_attentions else None
+ for i, encoder_layer in enumerate(self.layers):
+ if output_hidden_states:
+ encoder_states = encoder_states + (hidden_states,)
+ layer_outputs = encoder_layer(
+ hidden_states,
+ attention_mask,
+ position_embeddings=position_embeddings,
+ reference_points=reference_points,
+ spatial_shapes=spatial_shapes,
+ level_start_index=level_start_index,
+ output_attentions=output_attentions,
+ )
+
+ hidden_states = layer_outputs[0]
+
+ if output_attentions:
+ all_attentions = all_attentions + (layer_outputs[1],)
+
+ if output_hidden_states:
+ encoder_states = encoder_states + (hidden_states,)
+
+ return BaseModelOutput(
+ last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
+ )
+
+
+# Modified from from transformers.models.mask2former.modeling_mask2former.Mask2FormerPixelDecoder with Mask2->One
+class OneFormerPixelDecoder(nn.Module):
+ def __init__(self, config: OneFormerConfig, feature_channels):
+ super().__init__()
+
+ self.config = config
+
+ # positional encoding
+ self.position_embedding = OneFormerSinePositionEmbedding(
+ num_position_features=config.conv_dim // 2, normalize=True
+ )
+ self.num_feature_levels = 3
+ transformer_in_channels = feature_channels[-self.num_feature_levels :]
+ self.transformer_feature_strides = config.strides[-self.num_feature_levels :]
+ self.feature_channels = feature_channels
+ self.level_embed = nn.Parameter(torch.Tensor(self.num_feature_levels, config.conv_dim))
+
+ # Create input projection layers
+ if self.num_feature_levels > 1:
+ input_projections_list = []
+ for in_channels in transformer_in_channels[::-1]:
+ input_projections_list.append(
+ nn.Sequential(
+ nn.Conv2d(in_channels, config.conv_dim, kernel_size=1),
+ nn.GroupNorm(32, config.conv_dim),
+ )
+ )
+ self.input_projections = nn.ModuleList(input_projections_list)
+ else:
+ self.input_projections = nn.ModuleList(
+ [
+ nn.Sequential(
+ nn.Conv2d(transformer_in_channels[-1], config.conv_dim, kernel_size=1),
+ nn.GroupNorm(32, config.conv_dim),
+ )
+ ]
+ )
+
+ self.encoder = OneFormerPixelDecoderEncoderOnly(config)
+
+ self.mask_projection = nn.Conv2d(
+ config.conv_dim,
+ config.mask_dim,
+ kernel_size=1,
+ stride=1,
+ padding=0,
+ )
+
+ self.common_stride = config.common_stride
+
+ # extra fpn levels
+ stride = min(self.transformer_feature_strides)
+ self.num_fpn_levels = int(np.log2(stride) - np.log2(self.common_stride))
+
+ lateral_convs = []
+ output_convs = []
+
+ for idx, in_channels in enumerate(self.feature_channels[: self.num_fpn_levels]):
+ lateral_conv = nn.Sequential(
+ nn.Conv2d(
+ in_channels,
+ config.conv_dim,
+ kernel_size=1,
+ bias=False,
+ ),
+ nn.GroupNorm(32, config.conv_dim),
+ )
+ output_conv = nn.Sequential(
+ nn.Conv2d(
+ config.conv_dim,
+ config.conv_dim,
+ kernel_size=3,
+ stride=1,
+ padding=1,
+ bias=False,
+ ),
+ nn.GroupNorm(32, config.conv_dim),
+ nn.ReLU(),
+ )
+ self.add_module(f"adapter_{idx + 1}", lateral_conv)
+ self.add_module(f"layer_{idx + 1}", output_conv)
+
+ lateral_convs.append(lateral_conv)
+ output_convs.append(output_conv)
+ # Place convs into top-down order (from low to high resolution)
+ # to make the top-down computation in forward clearer.
+ self.lateral_convs = lateral_convs[::-1]
+ self.output_convs = output_convs[::-1]
+
+ def get_valid_ratio(self, mask, dtype=torch.float32):
+ """Get the valid ratio of all feature maps."""
+
+ _, height, width = mask.shape
+ valid_height = torch.sum(~mask[:, :, 0], 1)
+ valid_width = torch.sum(~mask[:, 0, :], 1)
+ valid_ratio_height = valid_height.to(dtype) / height
+ valid_ratio_width = valid_width.to(dtype) / width
+ valid_ratio = torch.stack([valid_ratio_width, valid_ratio_height], -1)
+ return valid_ratio
+
+ def forward(
+ self,
+ features,
+ encoder_outputs=None,
+ output_attentions=None,
+ output_hidden_states=None,
+ return_dict=None,
+ ):
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+
+ # Then, apply 1x1 convolution to reduce the channel dimension to d_model (256 by default)
+ sources = []
+ position_embeddings_list = []
+ for level, source in enumerate(features[::-1][: self.num_feature_levels]):
+ sources.append(self.input_projections[level](source))
+ position_embeddings_list.append(self.position_embedding(source.shape, source.device, source.dtype))
+
+ masks = [torch.zeros((x.size(0), x.size(2), x.size(3)), device=x.device, dtype=torch.bool) for x in sources]
+
+ # Prepare encoder inputs (by flattening)
+ source_flatten = []
+ mask_flatten = []
+ lvl_pos_embed_flatten = []
+ spatial_shapes = []
+ for level, (source, mask, pos_embed) in enumerate(zip(sources, masks, position_embeddings_list)):
+ batch_size, num_channels, height, width = source.shape
+ spatial_shape = (height, width)
+ spatial_shapes.append(spatial_shape)
+ source = source.flatten(2).transpose(1, 2)
+ mask = mask.flatten(1)
+ pos_embed = pos_embed.flatten(2).transpose(1, 2)
+ lvl_pos_embed = pos_embed + self.level_embed[level].view(1, 1, -1)
+ lvl_pos_embed_flatten.append(lvl_pos_embed)
+ source_flatten.append(source)
+ mask_flatten.append(mask)
+ source_flatten = torch.cat(source_flatten, 1)
+ mask_flatten = torch.cat(mask_flatten, 1)
+ lvl_pos_embed_flatten = torch.cat(lvl_pos_embed_flatten, 1)
+ spatial_shapes = torch.as_tensor(spatial_shapes, dtype=torch.long, device=source_flatten.device)
+ level_start_index = torch.cat((spatial_shapes.new_zeros((1,)), spatial_shapes.prod(1).cumsum(0)[:-1]))
+ valid_ratios = torch.stack([self.get_valid_ratio(m, dtype=source_flatten.dtype) for m in masks], 1)
+
+ # Fourth, sent source_flatten + mask_flatten + lvl_pos_embed_flatten (backbone + proj layer output) through encoder
+ # Also provide spatial_shapes, level_start_index and valid_ratios
+ if encoder_outputs is None:
+ encoder_outputs = self.encoder(
+ inputs_embeds=source_flatten,
+ attention_mask=mask_flatten,
+ position_embeddings=lvl_pos_embed_flatten,
+ spatial_shapes=spatial_shapes,
+ level_start_index=level_start_index,
+ valid_ratios=valid_ratios,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ y = encoder_outputs.last_hidden_state
+ bs = y.shape[0]
+
+ split_size_or_sections = [None] * self.num_feature_levels
+ for i in range(self.num_feature_levels):
+ if i < self.num_feature_levels - 1:
+ split_size_or_sections[i] = level_start_index[i + 1] - level_start_index[i]
+ else:
+ split_size_or_sections[i] = y.shape[1] - level_start_index[i]
+ y = torch.split(y, split_size_or_sections, dim=1)
+
+ out = []
+ multi_scale_features = []
+ num_cur_levels = 0
+ for i, z in enumerate(y):
+ out.append(z.transpose(1, 2).view(bs, -1, spatial_shapes[i][0], spatial_shapes[i][1]))
+
+ # append `out` with extra FPN levels
+ # Reverse feature maps into top-down order (from low to high resolution)
+ for idx, feats in enumerate(features[: self.num_fpn_levels][::-1]):
+ lateral_conv = self.lateral_convs[idx]
+ output_conv = self.output_convs[idx]
+ cur_fpn = lateral_conv(feats)
+ # Following FPN implementation, we use nearest upsampling here
+ y = cur_fpn + nn.functional.interpolate(
+ out[-1], size=cur_fpn.shape[-2:], mode="bilinear", align_corners=False
+ )
+ y = output_conv(y)
+ out.append(y)
+
+ for o in out:
+ if num_cur_levels < self.num_feature_levels:
+ multi_scale_features.append(o)
+ num_cur_levels += 1
+
+ return OneFormerPixelDecoderOutput(
+ mask_features=self.mask_projection(out[-1]),
+ multi_scale_features=multi_scale_features,
+ attentions=encoder_outputs.attentions,
+ )
+
+
+# Modified from from transformers.models.mask2former.modeling_mask2former.Mask2FormerPixelLevelModule with Mask2->One
+class OneFormerPixelLevelModule(nn.Module):
+ def __init__(self, config: OneFormerConfig):
+ """
+ Pixel Level Module proposed in [Masked-attention Mask Transformer for Universal Image
+ Segmentation](https://huggingface.co/papers/2112.01527). It runs the input image through a backbone and a pixel
+ decoder, generating multi-scale feature maps and pixel embeddings.
+
+ Args:
+ config ([`OneFormerConfig`]):
+ The configuration used to instantiate this model.
+ """
+ super().__init__()
+ self.encoder = load_backbone(config)
+ self.decoder = OneFormerPixelDecoder(config, feature_channels=self.encoder.channels)
+
+ def forward(self, pixel_values: Tensor, output_hidden_states: bool = False) -> OneFormerPixelLevelModuleOutput:
+ features: list[Tensor] = self.encoder(pixel_values).feature_maps
+ decoder_output: OneFormerPixelDecoderOutput = self.decoder(features, output_hidden_states=output_hidden_states)
+ return OneFormerPixelLevelModuleOutput(
+ encoder_features=tuple(features),
+ decoder_features=decoder_output.multi_scale_features,
+ decoder_last_feature=decoder_output.mask_features,
+ )
+
+
+# Modified from transformers.models.detr.modeling_detr.DetrAttention with Detr->OneFormer
+class OneFormerAttention(nn.Module):
+ """
+ Multi-headed attention from 'Attention Is All You Need' paper. Here, we add position embeddings to the queries and
+ keys (as explained in the DETR paper).
+ """
+
+ def __init__(
+ self,
+ embed_dim: int,
+ num_heads: int,
+ dropout: float = 0.0,
+ is_decoder: bool = False,
+ bias: bool = True,
+ ):
+ super().__init__()
+ self.embed_dim = embed_dim
+ self.num_heads = num_heads
+ self.dropout = dropout
+ self.head_dim = embed_dim // num_heads
+ if self.head_dim * num_heads != self.embed_dim:
+ raise ValueError(
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
+ f" {num_heads})."
+ )
+ self.scaling = self.head_dim**-0.5
+
+ self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
+ self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
+
+ def _shape(self, tensor: torch.Tensor, seq_len: int, batch_size: int):
+ return tensor.view(batch_size, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
+
+ def with_pos_embed(self, tensor: torch.Tensor, position_embeddings: Tensor | None):
+ return tensor if position_embeddings is None else tensor + position_embeddings
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor | None = None,
+ position_embeddings: torch.Tensor | None = None,
+ key_value_states: torch.Tensor | None = None,
+ key_value_position_embeddings: torch.Tensor | None = None,
+ output_attentions: bool = False,
+ ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
+ """Input shape: Batch x Time x Channel"""
+
+ hidden_states = hidden_states.permute(1, 0, 2) if hidden_states is not None else None
+ position_embeddings = position_embeddings.permute(1, 0, 2) if position_embeddings is not None else None
+ key_value_states = key_value_states.permute(1, 0, 2) if key_value_states is not None else None
+ key_value_position_embeddings = (
+ key_value_position_embeddings.permute(1, 0, 2) if key_value_position_embeddings is not None else None
+ )
+
+ # if key_value_states are provided this layer is used as a cross-attention layer
+ # for the decoder
+ is_cross_attention = key_value_states is not None
+ batch_size, target_len, embed_dim = hidden_states.size()
+
+ # add position embeddings to the hidden states before projecting to queries and keys
+ if position_embeddings is not None:
+ hidden_states_original = hidden_states
+ hidden_states = self.with_pos_embed(hidden_states, position_embeddings)
+
+ # add key-value position embeddings to the key value states
+ if key_value_position_embeddings is not None:
+ key_value_states_original = key_value_states
+ key_value_states = self.with_pos_embed(key_value_states, key_value_position_embeddings)
+
+ # get query proj
+ query_states = self.q_proj(hidden_states) * self.scaling
+ # get key, value proj
+ if is_cross_attention:
+ # cross_attentions
+ key_states = self._shape(self.k_proj(key_value_states), -1, batch_size)
+ value_states = self._shape(self.v_proj(key_value_states_original), -1, batch_size)
+ else:
+ # self_attention
+ key_states = self._shape(self.k_proj(hidden_states), -1, batch_size)
+ value_states = self._shape(self.v_proj(hidden_states_original), -1, batch_size)
+
+ proj_shape = (batch_size * self.num_heads, -1, self.head_dim)
+ query_states = self._shape(query_states, target_len, batch_size).view(*proj_shape)
+ key_states = key_states.view(*proj_shape)
+ value_states = value_states.view(*proj_shape)
+
+ source_len = key_states.size(1)
+
+ attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
+
+ if attn_weights.size() != (batch_size * self.num_heads, target_len, source_len):
+ raise ValueError(
+ f"Attention weights should be of size {(batch_size * self.num_heads, target_len, source_len)}, but is"
+ f" {attn_weights.size()}"
+ )
+
+ if attention_mask is not None:
+ if attention_mask.size() != (batch_size * self.num_heads, target_len, source_len):
+ raise ValueError(
+ f"Attention mask should be of size {(target_len, batch_size * self.num_heads, source_len)}, but is"
+ f" {attention_mask.size()}"
+ )
+ attn_weights += attention_mask
+
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
+
+ if output_attentions:
+ # this operation is a bit awkward, but it's required to
+ # make sure that attn_weights keeps its gradient.
+ # In order to do so, attn_weights have to reshaped
+ # twice and have to be reused in the following
+ attn_weights_reshaped = attn_weights.view(batch_size, self.num_heads, target_len, source_len)
+ attn_weights = attn_weights_reshaped.view(batch_size * self.num_heads, target_len, source_len)
+ else:
+ attn_weights_reshaped = None
+
+ attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
+
+ attn_output = torch.bmm(attn_probs, value_states)
+
+ if attn_output.size() != (batch_size * self.num_heads, target_len, self.head_dim):
+ raise ValueError(
+ f"`attn_output` should be of size {(batch_size, self.num_heads, target_len, self.head_dim)}, but is"
+ f" {attn_output.size()}"
+ )
+
+ attn_output = attn_output.view(batch_size, self.num_heads, target_len, self.head_dim)
+ attn_output = attn_output.transpose(1, 2)
+ attn_output = attn_output.reshape(batch_size, target_len, embed_dim)
+
+ attn_output = self.out_proj(attn_output).permute(1, 0, 2)
+
+ return attn_output, attn_weights_reshaped
+
+
+class OneFormerTransformerDecoderSelfAttentionLayer(nn.Module):
+ def __init__(
+ self, embed_dim, num_heads, dropout=0.0, activation="relu", normalize_before=False, layer_norm_eps=1e-05
+ ):
+ super().__init__()
+ self.self_attn = OneFormerAttention(embed_dim=embed_dim, num_heads=num_heads, dropout=dropout, is_decoder=True)
+
+ self.norm = nn.LayerNorm(embed_dim, eps=layer_norm_eps)
+ self.dropout = nn.Dropout(dropout)
+
+ self.activation = ACT2FN[activation]
+ self.normalize_before = normalize_before
+
+ def with_pos_embed(self, tensor, pos: Tensor | None):
+ return tensor if pos is None else tensor + pos
+
+ def forward_post(
+ self,
+ output,
+ output_mask: Tensor | None = None,
+ output_key_padding_mask: Tensor | None = None,
+ query_pos: Tensor | None = None,
+ ):
+ output2, attention_weights = self.self_attn(
+ hidden_states=output, position_embeddings=query_pos, attention_mask=output_mask, output_attentions=True
+ )
+ output = output + self.dropout(output2)
+ output = self.norm(output)
+
+ return output, attention_weights
+
+ def forward_pre(
+ self,
+ output,
+ output_mask: Tensor | None = None,
+ output_key_padding_mask: Tensor | None = None,
+ query_pos: Tensor | None = None,
+ ):
+ output2 = self.norm(output)
+ output2, attention_weights = self.self_attn(
+ hidden_states=output2, position_embeddings=query_pos, attention_mask=output_mask, output_attentions=True
+ )
+ output = output + self.dropout(output2)
+
+ return output, attention_weights
+
+ def forward(
+ self,
+ output,
+ output_mask: Tensor | None = None,
+ output_key_padding_mask: Tensor | None = None,
+ query_pos: Tensor | None = None,
+ ):
+ if self.normalize_before:
+ return self.forward_pre(output, output_mask, output_key_padding_mask, query_pos)
+ return self.forward_post(output, output_mask, output_key_padding_mask, query_pos)
+
+
+class OneFormerTransformerDecoderCrossAttentionLayer(nn.Module):
+ def __init__(
+ self, embed_dim, num_heads, dropout=0.0, activation="relu", normalize_before=False, layer_norm_eps=1e-05
+ ):
+ super().__init__()
+ self.multihead_attn = nn.MultiheadAttention(embed_dim, num_heads, dropout=dropout)
+
+ self.norm = nn.LayerNorm(embed_dim, eps=layer_norm_eps)
+ self.dropout = nn.Dropout(dropout)
+
+ self.activation = ACT2FN[activation]
+ self.normalize_before = normalize_before
+
+ def with_pos_embed(self, tensor, pos: Tensor | None):
+ return tensor if pos is None else tensor + pos
+
+ def forward_post(
+ self,
+ output,
+ memory,
+ memory_mask: Tensor | None = None,
+ memory_key_padding_mask: Tensor | None = None,
+ pos: Tensor | None = None,
+ query_pos: Tensor | None = None,
+ ):
+ output2, attention_weights = self.multihead_attn(
+ query=self.with_pos_embed(output, query_pos),
+ key=self.with_pos_embed(memory, pos),
+ value=memory,
+ attn_mask=memory_mask,
+ key_padding_mask=memory_key_padding_mask,
+ )
+ output = output + self.dropout(output2)
+ output = self.norm(output)
+
+ return output, attention_weights
+
+ def forward_pre(
+ self,
+ output,
+ memory,
+ memory_mask: Tensor | None = None,
+ memory_key_padding_mask: Tensor | None = None,
+ pos: Tensor | None = None,
+ query_pos: Tensor | None = None,
+ ):
+ output2 = self.norm(output)
+ output2, attention_weights = self.multihead_attn(
+ query=self.with_pos_embed(output2, query_pos),
+ key=self.with_pos_embed(memory, pos),
+ value=memory,
+ attn_mask=memory_mask,
+ key_padding_mask=memory_key_padding_mask,
+ )
+ output = output + self.dropout(output2)
+
+ return output, attention_weights
+
+ def forward(
+ self,
+ output,
+ memory,
+ memory_mask: Tensor | None = None,
+ memory_key_padding_mask: Tensor | None = None,
+ pos: Tensor | None = None,
+ query_pos: Tensor | None = None,
+ ):
+ if self.normalize_before:
+ return self.forward_pre(output, memory, memory_mask, memory_key_padding_mask, pos, query_pos)
+ return self.forward_post(output, memory, memory_mask, memory_key_padding_mask, pos, query_pos)
+
+
+class OneFormerTransformerDecoderFFNLayer(nn.Module):
+ def __init__(
+ self,
+ d_model,
+ dim_feedforward=2048,
+ dropout=0.0,
+ activation="relu",
+ normalize_before=False,
+ layer_norm_eps=1e-05,
+ ):
+ super().__init__()
+ # Implementation of Feedforward model
+ self.linear1 = nn.Linear(d_model, dim_feedforward)
+ self.dropout = nn.Dropout(dropout)
+ self.linear2 = nn.Linear(dim_feedforward, d_model)
+
+ self.norm = nn.LayerNorm(d_model, eps=layer_norm_eps)
+
+ self.activation = ACT2FN[activation]
+ self.normalize_before = normalize_before
+
+ def with_pos_embed(self, tensor, pos: Tensor | None):
+ return tensor if pos is None else tensor + pos
+
+ def forward_post(self, output):
+ output2 = self.linear2(self.dropout(self.activation(self.linear1(output))))
+ output = output + self.dropout(output2)
+ output = self.norm(output)
+ return output
+
+ def forward_pre(self, output):
+ output2 = self.norm(output)
+ output2 = self.linear2(self.dropout(self.activation(self.linear1(output2))))
+ output = output + self.dropout(output2)
+ return output
+
+ def forward(self, output):
+ if self.normalize_before:
+ return self.forward_pre(output)
+ return self.forward_post(output)
+
+
+class OneFormerMLPPredictionHead(nn.Module):
+ def __init__(self, input_dim: int, hidden_dim: int, output_dim: int, num_layers: int = 3):
+ """
+ A classic Multi Layer Perceptron (MLP).
+
+ Args:
+ input_dim (`int`):
+ The input dimensions.
+ hidden_dim (`int`):
+ The hidden dimensions.
+ output_dim (`int`):
+ The output dimensions.
+ num_layers (int, *optional*, defaults to 3):
+ The number of layers.
+ """
+ super().__init__()
+ in_dims = [input_dim] + [hidden_dim] * (num_layers - 1)
+ out_dims = [hidden_dim] * (num_layers - 1) + [output_dim]
+
+ layers = []
+ for i, (in_dim, out_dim) in enumerate(zip(in_dims, out_dims)):
+ layers.append(
+ PredictionBlock(in_dim, out_dim, activation=nn.ReLU() if i < num_layers - 1 else nn.Identity())
+ )
+
+ self.layers = nn.Sequential(*layers)
+
+ def forward(self, input: Tensor) -> Tensor:
+ return self.layers(input)
+
+
+# refactored from original implementation
+class OneFormerTransformerDecoderLayer(nn.Module):
+ def __init__(self, config: OneFormerConfig):
+ super().__init__()
+ self.embed_dim = config.hidden_dim
+ self.num_feature_levels = 3
+
+ self.cross_attn = OneFormerTransformerDecoderCrossAttentionLayer(
+ embed_dim=self.embed_dim,
+ num_heads=config.num_attention_heads,
+ dropout=0.0,
+ normalize_before=config.pre_norm,
+ layer_norm_eps=config.layer_norm_eps,
+ )
+
+ self.self_attn = OneFormerTransformerDecoderSelfAttentionLayer(
+ embed_dim=self.embed_dim,
+ num_heads=config.num_attention_heads,
+ dropout=0.0,
+ normalize_before=config.pre_norm,
+ layer_norm_eps=config.layer_norm_eps,
+ )
+
+ self.ffn = OneFormerTransformerDecoderFFNLayer(
+ d_model=self.embed_dim,
+ dim_feedforward=config.dim_feedforward,
+ dropout=0.0,
+ normalize_before=config.pre_norm,
+ layer_norm_eps=config.layer_norm_eps,
+ )
+
+ def forward(
+ self,
+ index: int,
+ output: torch.Tensor,
+ multi_stage_features: list[torch.Tensor],
+ multi_stage_positional_embeddings: list[torch.Tensor],
+ attention_mask: torch.Tensor | None = None,
+ query_embeddings: torch.Tensor | None = None,
+ output_attentions: bool | None = False,
+ ):
+ """
+ Args:
+ index (`int`): index of the layer in the Transformer decoder.
+ output (`torch.FloatTensor`): the object queries of shape `(N, batch, hidden_dim)`
+ multi_stage_features (`list[torch.Tensor]`): the multi-scale features from the pixel decoder.
+ multi_stage_positional_embeddings (`list[torch.Tensor]`):
+ positional embeddings for the multi_stage_features
+ attention_mask (`torch.FloatTensor`): attention mask for the masked cross attention layer
+ query_embeddings (`torch.FloatTensor`, *optional*):
+ position embeddings that are added to the queries and keys in the self-attention layer.
+ output_attentions (`bool`, *optional*):
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
+ returned tensors for more detail.
+ """
+
+ level_index = index % self.num_feature_levels
+ attention_mask[torch.where(attention_mask.sum(-1) == attention_mask.shape[-1])] = False
+
+ # Masked Cross Attention
+ output, cross_attn_weights = self.cross_attn(
+ output,
+ multi_stage_features[level_index],
+ memory_mask=attention_mask,
+ memory_key_padding_mask=None, # here we do not apply masking on padded region
+ pos=multi_stage_positional_embeddings[level_index],
+ query_pos=query_embeddings,
+ )
+
+ # Self Attention
+ output, self_attn_weights = self.self_attn(
+ output,
+ output_mask=None,
+ output_key_padding_mask=None,
+ query_pos=query_embeddings,
+ )
+
+ # Fully Connected
+ output = self.ffn(output)
+
+ outputs = (output,)
+
+ if output_attentions:
+ outputs += (self_attn_weights, cross_attn_weights)
+
+ return outputs
+
+
+class OneFormerTransformerDecoderQueryTransformerDecoder(nn.Module):
+ def __init__(self, decoder_layer, num_layers, norm=None, return_intermediate=False):
+ super().__init__()
+ self.layers = _get_clones(decoder_layer, num_layers)
+ self.num_layers = num_layers
+ self.norm = norm
+ self.return_intermediate = return_intermediate
+
+ def forward(
+ self,
+ output,
+ memory,
+ output_mask: Tensor | None = None,
+ memory_mask: Tensor | None = None,
+ output_key_padding_mask: Tensor | None = None,
+ memory_key_padding_mask: Tensor | None = None,
+ pos: Tensor | None = None,
+ query_pos: Tensor | None = None,
+ ):
+ intermediate = []
+
+ for layer in self.layers:
+ output = layer(
+ output,
+ memory,
+ output_mask=output_mask,
+ memory_mask=memory_mask,
+ output_key_padding_mask=output_key_padding_mask,
+ memory_key_padding_mask=memory_key_padding_mask,
+ pos=pos,
+ query_pos=query_pos,
+ )
+ if self.return_intermediate:
+ intermediate.append(self.norm(output))
+
+ if self.norm is not None:
+ output = self.norm(output)
+ if self.return_intermediate:
+ intermediate.pop()
+ intermediate.append(output)
+
+ if self.return_intermediate:
+ return torch.stack(intermediate)
+
+ return output.unsqueeze(0)
+
+
+class OneFormerTransformerDecoderQueryTransformerDecoderLayer(nn.Module):
+ def __init__(
+ self,
+ d_model,
+ nhead,
+ dim_feedforward=2048,
+ dropout=0.1,
+ activation="relu",
+ normalize_before=False,
+ layer_norm_eps=1e-05,
+ ):
+ super().__init__()
+ self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)
+ self.multihead_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)
+ # Implementation of Feedforward model
+ self.linear1 = nn.Linear(d_model, dim_feedforward)
+ self.dropout = nn.Dropout(dropout)
+ self.linear2 = nn.Linear(dim_feedforward, d_model)
+
+ self.norm1 = nn.LayerNorm(d_model, eps=layer_norm_eps)
+ self.norm2 = nn.LayerNorm(d_model, eps=layer_norm_eps)
+ self.norm3 = nn.LayerNorm(d_model, eps=layer_norm_eps)
+ self.dropout1 = nn.Dropout(dropout)
+ self.dropout2 = nn.Dropout(dropout)
+ self.dropout3 = nn.Dropout(dropout)
+
+ self.activation = ACT2FN[activation]
+ self.normalize_before = normalize_before
+
+ def with_pos_embed(self, tensor, pos: Tensor | None):
+ return tensor if pos is None else tensor + pos
+
+ def forward_post(
+ self,
+ output,
+ memory,
+ output_mask: Tensor | None = None,
+ memory_mask: Tensor | None = None,
+ output_key_padding_mask: Tensor | None = None,
+ memory_key_padding_mask: Tensor | None = None,
+ pos: Tensor | None = None,
+ query_pos: Tensor | None = None,
+ ):
+ q = k = self.with_pos_embed(output, query_pos)
+ output2 = self.self_attn(q, k, value=output, attn_mask=output_mask, key_padding_mask=output_key_padding_mask)
+ output2 = output2[0]
+ output = output + self.dropout1(output2)
+ output = self.norm1(output)
+ output2 = self.multihead_attn(
+ query=self.with_pos_embed(output, query_pos),
+ key=self.with_pos_embed(memory, pos),
+ value=memory,
+ attn_mask=memory_mask,
+ key_padding_mask=memory_key_padding_mask,
+ )
+ output2 = output2[0]
+ output = output + self.dropout2(output2)
+ output = self.norm2(output)
+ output2 = self.linear2(self.dropout(self.activation(self.linear1(output))))
+ output = output + self.dropout3(output2)
+ output = self.norm3(output)
+ return output
+
+ def forward_pre(
+ self,
+ output,
+ memory,
+ output_mask: Tensor | None = None,
+ memory_mask: Tensor | None = None,
+ output_key_padding_mask: Tensor | None = None,
+ memory_key_padding_mask: Tensor | None = None,
+ pos: Tensor | None = None,
+ query_pos: Tensor | None = None,
+ ):
+ output2 = self.norm1(output)
+ q = k = self.with_pos_embed(output2, query_pos)
+ output2 = self.self_attn(q, k, value=output2, attn_mask=output_mask, key_padding_mask=output_key_padding_mask)
+ output2 = output2[0]
+ output = output + self.dropout1(output2)
+ output2 = self.norm2(output)
+ output2 = self.multihead_attn(
+ query=self.with_pos_embed(output2, query_pos),
+ key=self.with_pos_embed(memory, pos),
+ value=memory,
+ attn_mask=memory_mask,
+ key_padding_mask=memory_key_padding_mask,
+ )
+ output2 = output2[0]
+ output = output + self.dropout2(output2)
+ output2 = self.norm3(output)
+ output2 = self.linear2(self.dropout(self.activation(self.linear1(output2))))
+ output = output + self.dropout3(output2)
+ return output
+
+ def forward(
+ self,
+ output,
+ memory,
+ output_mask: Tensor | None = None,
+ memory_mask: Tensor | None = None,
+ output_key_padding_mask: Tensor | None = None,
+ memory_key_padding_mask: Tensor | None = None,
+ pos: Tensor | None = None,
+ query_pos: Tensor | None = None,
+ ):
+ if self.normalize_before:
+ return self.forward_pre(
+ output,
+ memory,
+ output_mask,
+ memory_mask,
+ output_key_padding_mask,
+ memory_key_padding_mask,
+ pos,
+ query_pos,
+ )
+ return self.forward_post(
+ output,
+ memory,
+ output_mask,
+ memory_mask,
+ output_key_padding_mask,
+ memory_key_padding_mask,
+ pos,
+ query_pos,
+ )
+
+
+class OneFormerTransformerDecoderQueryTransformer(nn.Module):
+ def __init__(
+ self,
+ d_model=512,
+ nhead=8,
+ num_decoder_layers=6,
+ dim_feedforward=2048,
+ dropout=0.1,
+ activation="relu",
+ normalize_before=False,
+ return_intermediate_dec=False,
+ layer_norm_eps=1e-05,
+ ):
+ super().__init__()
+
+ decoder_layer = OneFormerTransformerDecoderQueryTransformerDecoderLayer(
+ d_model, nhead, dim_feedforward, dropout, activation, normalize_before, layer_norm_eps
+ )
+ decoder_norm = nn.LayerNorm(d_model, eps=layer_norm_eps)
+ self.decoder = OneFormerTransformerDecoderQueryTransformerDecoder(
+ decoder_layer,
+ num_decoder_layers,
+ decoder_norm,
+ return_intermediate=return_intermediate_dec,
+ )
+
+ self.d_model = d_model
+ self.nhead = nhead
+
+ def forward(self, src, mask, query_embed, pos_embed, task_token=None):
+ batch_size = src.shape[0]
+ # flatten NxCxHxW to HWxNxC
+ src = src.flatten(2).permute(2, 0, 1)
+ pos_embed = pos_embed.flatten(2).permute(2, 0, 1)
+ query_embed = query_embed.unsqueeze(1).repeat(1, batch_size, 1)
+ if mask is not None:
+ mask = mask.flatten(1)
+
+ if task_token is None:
+ queries = torch.zeros_like(query_embed)
+ else:
+ queries = task_token.repeat(query_embed.shape[0], 1, 1)
+
+ queries = self.decoder(queries, src, memory_key_padding_mask=mask, pos=pos_embed, query_pos=query_embed)
+ return queries.transpose(1, 2)
+
+
+class OneFormerTransformerDecoder(nn.Module):
+ """
+ Transformer decoder
+ """
+
+ def __init__(self, in_channels: int, config: OneFormerConfig):
+ super().__init__()
+ self.config = config
+
+ self.dropout = config.dropout
+ self.num_heads = config.num_attention_heads
+ self.is_training = config.is_training
+ self.use_task_norm = config.use_task_norm
+ self.use_auxiliary_loss = config.use_auxiliary_loss
+
+ self.query_transformer = OneFormerTransformerDecoderQueryTransformer(
+ d_model=config.hidden_dim,
+ dropout=config.dropout,
+ nhead=config.num_attention_heads,
+ dim_feedforward=config.dim_feedforward,
+ num_decoder_layers=config.query_dec_layers,
+ normalize_before=config.pre_norm,
+ return_intermediate_dec=False,
+ layer_norm_eps=config.layer_norm_eps,
+ )
+
+ self.decoder_norm = nn.LayerNorm(config.hidden_dim, eps=config.layer_norm_eps)
+
+ self.num_feature_levels = 3
+
+ self.layers = nn.ModuleList(
+ [OneFormerTransformerDecoderLayer(config) for _ in range(config.decoder_layers - 1)]
+ )
+
+ self.query_input_projection = nn.Conv2d(in_channels, config.hidden_dim, kernel_size=1)
+
+ self.class_embed = nn.Linear(config.hidden_dim, config.num_labels + 1)
+ self.mask_embed = OneFormerMLPPredictionHead(
+ config.hidden_dim,
+ config.hidden_dim,
+ config.mask_dim,
+ 3,
+ )
+
+ def forward(
+ self,
+ task_token=None,
+ multi_stage_features=None,
+ multi_stage_positional_embeddings=None,
+ mask_features=None,
+ query_features=None,
+ query_embeddings=None,
+ query_embedder=None,
+ size_list=None,
+ output_attentions=None,
+ ):
+ if self.use_task_norm:
+ task_token = self.decoder_norm(task_token)
+
+ object_queries = self.query_transformer(
+ query_features,
+ None,
+ query_embedder.weight[:-1],
+ self.query_input_projection(mask_features),
+ task_token if self.use_task_norm else None,
+ )
+
+ object_queries = object_queries[0].permute(1, 0, 2)
+
+ queries = torch.cat([object_queries, task_token], dim=0)
+
+ output = queries.clone()
+
+ intermediate_class_predictions = []
+ intermediate_mask_predictions = []
+
+ # prediction heads on learnable query features
+ outputs_class, outputs_mask, attention_mask = self.forward_prediction_heads(
+ output, mask_features, attention_mask_target_size=size_list[0]
+ )
+ intermediate_class_predictions.append(outputs_class)
+ intermediate_mask_predictions.append(outputs_mask)
+
+ attentions = ()
+
+ for index, layer in enumerate(self.layers):
+ layer_outputs = layer(
+ index=index,
+ output=output,
+ multi_stage_features=multi_stage_features,
+ multi_stage_positional_embeddings=multi_stage_positional_embeddings,
+ attention_mask=attention_mask,
+ query_embeddings=query_embeddings,
+ output_attentions=output_attentions,
+ )
+
+ output = layer_outputs[0]
+ attentions += (layer_outputs[1:],)
+
+ outputs_class, outputs_mask, attention_mask = self.forward_prediction_heads(
+ output, mask_features, attention_mask_target_size=size_list[(index + 1) % self.num_feature_levels]
+ )
+ intermediate_class_predictions.append(outputs_class)
+ intermediate_mask_predictions.append(outputs_mask)
+
+ if not len(intermediate_mask_predictions) == len(self.layers) + 1:
+ raise ValueError(
+ "Intermediate predictions in the transformer decoder must have the same number of elements as number"
+ " of layers"
+ )
+
+ object_queries = layer_outputs[0].permute(1, 0, 2)
+
+ contrastive_logits = queries.permute(1, 0, 2)
+
+ return OneFormerTransformerDecoderOutput(
+ object_queries=object_queries,
+ contrastive_logits=contrastive_logits,
+ prediction_masks=intermediate_mask_predictions[-1],
+ prediction_class=intermediate_class_predictions[-1],
+ auxiliary_predictions=self._get_aux_predictions(
+ intermediate_class_predictions, intermediate_mask_predictions
+ )
+ if self.use_auxiliary_loss
+ else None,
+ attentions=attentions,
+ )
+
+ def forward_prediction_heads(self, output, mask_features, attention_mask_target_size):
+ decoder_output = self.decoder_norm(output)
+ decoder_output = decoder_output.transpose(0, 1)
+ outputs_class = self.class_embed(decoder_output)
+ mask_embed = self.mask_embed(decoder_output)
+ outputs_mask = torch.einsum("bqc,bchw->bqhw", mask_embed, mask_features)
+
+ attention_mask = nn.functional.interpolate(
+ outputs_mask, size=attention_mask_target_size, mode="bilinear", align_corners=False
+ )
+
+ # must use bool type
+ # If a BoolTensor is provided, positions with ``True`` are not allowed to attend while ``False`` values will be unchanged.
+ attention_mask = (
+ attention_mask.sigmoid().flatten(2).unsqueeze(1).repeat(1, self.num_heads, 1, 1).flatten(0, 1) < 0.5
+ ).bool()
+ attention_mask = attention_mask.detach()
+
+ return outputs_class, outputs_mask, attention_mask
+
+ def _get_aux_predictions(self, outputs_class, outputs_seg_masks):
+ aux_list = [
+ {"class_queries_logits": a, "masks_queries_logits": b}
+ for a, b in zip(outputs_class[:-1], outputs_seg_masks[:-1])
+ ]
+ return tuple(aux_list)
+
+
+class OneFormerTransformerModule(nn.Module):
+ """
+ The OneFormer's transformer module.
+ """
+
+ def __init__(self, in_features: int, config: OneFormerConfig):
+ super().__init__()
+ hidden_dim = config.hidden_dim
+ self.num_feature_levels = 3
+ self.position_embedder = OneFormerSinePositionEmbedding(num_position_features=hidden_dim // 2, normalize=True)
+ self.queries_embedder = nn.Embedding(config.num_queries, hidden_dim)
+ self.input_projections = []
+
+ for _ in range(self.num_feature_levels):
+ if in_features != hidden_dim or config.enforce_input_proj:
+ self.input_projections.append(nn.Conv2d(in_features, hidden_dim, kernel_size=1))
+ else:
+ self.input_projections.append(nn.Sequential())
+
+ self.decoder = OneFormerTransformerDecoder(in_channels=in_features, config=config)
+ self.level_embed = nn.Embedding(self.num_feature_levels, hidden_dim)
+
+ def forward(
+ self,
+ multi_scale_features: list[Tensor],
+ mask_features: Tensor,
+ task_token: Tensor,
+ output_attentions: bool = False,
+ ) -> OneFormerTransformerDecoderOutput:
+ if not len(multi_scale_features) == self.num_feature_levels:
+ raise ValueError(
+ f"Number of elements in multi_scale_features ({len(multi_scale_features)}) and num_feature_levels"
+ f" ({self.num_feature_levels}) do not match!"
+ )
+ multi_stage_features = []
+ multi_stage_positional_embeddings = []
+ size_list = []
+
+ for i in range(self.num_feature_levels):
+ size_list.append(multi_scale_features[i].shape[-2:])
+ # Flatten NxCxHxW to NxCxHW
+ multi_stage_positional_embeddings.append(
+ self.position_embedder(
+ multi_scale_features[i].shape, multi_scale_features[i].device, multi_scale_features[i].dtype, None
+ ).flatten(2)
+ )
+ multi_stage_features.append(
+ self.input_projections[i](multi_scale_features[i]).flatten(2)
+ + self.level_embed.weight[i][None, :, None]
+ )
+ # Permute NxCxHW to HWxNxC
+ multi_stage_positional_embeddings[-1] = multi_stage_positional_embeddings[-1].permute(2, 0, 1)
+ multi_stage_features[-1] = multi_stage_features[-1].permute(2, 0, 1)
+
+ _, batch_size, _ = multi_stage_features[0].shape
+
+ # QxNxC
+ query_embeddings = self.queries_embedder.weight.unsqueeze(1).repeat(1, batch_size, 1)
+ task_token = task_token.unsqueeze(0)
+
+ query_features = self.position_embedder(mask_features.shape, mask_features.device, mask_features.dtype, None)
+
+ return self.decoder(
+ task_token=task_token,
+ multi_stage_features=multi_stage_features,
+ multi_stage_positional_embeddings=multi_stage_positional_embeddings,
+ mask_features=mask_features,
+ query_features=query_features,
+ query_embeddings=query_embeddings,
+ query_embedder=self.queries_embedder,
+ size_list=size_list,
+ output_attentions=output_attentions,
+ )
+
+
+# Copied from transformers.models.maskformer.modeling_maskformer.MaskFormerSinePositionEmbedding with Mask->One
+class OneFormerSinePositionEmbedding(nn.Module):
+ """
+ This is a more standard version of the position embedding, very similar to the one used by the Attention is all you
+ need paper, generalized to work on images.
+ """
+
+ def __init__(
+ self,
+ num_position_features: int = 64,
+ temperature: int = 10000,
+ normalize: bool = False,
+ scale: float | None = None,
+ ):
+ super().__init__()
+ if scale is not None and normalize is False:
+ raise ValueError("normalize should be True if scale is passed")
+ self.num_position_features = num_position_features
+ self.temperature = temperature
+ self.normalize = normalize
+ self.scale = 2 * math.pi if scale is None else scale
+
+ @staticmethod
+ @compile_compatible_method_lru_cache(maxsize=1)
+ def build_sine_position_embedding(
+ shape: torch.Size,
+ device: torch.device | str,
+ dtype: torch.dtype,
+ num_position_features: int,
+ normalize: bool = False,
+ scale: float | None = None,
+ temperature: int = 10000,
+ mask: torch.Tensor | None = None,
+ ) -> torch.Tensor:
+ if mask is None:
+ mask = torch.ones((shape[0], shape[2], shape[3]), device=device, dtype=torch.bool)
+ y_embed = mask.cumsum(1, dtype=dtype)
+ x_embed = mask.cumsum(2, dtype=dtype)
+ if normalize:
+ eps = 1e-6
+ y_embed = y_embed / (y_embed[:, -1:, :] + eps) * scale
+ x_embed = x_embed / (x_embed[:, :, -1:] + eps) * scale
+
+ dim_t = torch.arange(num_position_features, dtype=torch.int64, device=device).to(dtype)
+ dim_t = temperature ** (2 * torch.div(dim_t, 2, rounding_mode="floor") / num_position_features)
+
+ pos_x = x_embed[:, :, :, None] / dim_t
+ pos_y = y_embed[:, :, :, None] / dim_t
+ pos_x = torch.stack((pos_x[:, :, :, 0::2].sin(), pos_x[:, :, :, 1::2].cos()), dim=4).flatten(3)
+ pos_y = torch.stack((pos_y[:, :, :, 0::2].sin(), pos_y[:, :, :, 1::2].cos()), dim=4).flatten(3)
+ pos = torch.cat((pos_y, pos_x), dim=3).permute(0, 3, 1, 2)
+ return pos
+
+ def forward(
+ self,
+ shape: torch.Size,
+ device: torch.device | str,
+ dtype: torch.dtype,
+ mask: torch.Tensor | None = None,
+ ) -> torch.Tensor:
+ return self.build_sine_position_embedding(
+ shape, device, dtype, self.num_position_features, self.normalize, self.scale, self.temperature, mask
+ )
+
+
+# Copied from transformers.models.maskformer.modeling_maskformer.PredictionBlock
+class PredictionBlock(nn.Module):
+ def __init__(self, in_dim: int, out_dim: int, activation: nn.Module) -> None:
+ super().__init__()
+ self.layers = [nn.Linear(in_dim, out_dim), activation]
+ # Maintain submodule indexing as if part of a Sequential block
+ for i, layer in enumerate(self.layers):
+ self.add_module(str(i), layer)
+
+ def forward(self, input: Tensor) -> Tensor:
+ hidden_state = input
+ for layer in self.layers:
+ hidden_state = layer(hidden_state)
+ return hidden_state
+
+
+class OneFormerTextMapperAttention(nn.Module):
+ def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0.0, proj_drop=0.0):
+ super().__init__()
+ self.num_heads = num_heads
+ head_dim = dim // num_heads
+ # NOTE scale factor was wrong in my original version, can set manually to be compat with prev weights
+ self.scale = qk_scale or head_dim**-0.5
+
+ self.q_proj = nn.Linear(dim, dim, bias=qkv_bias)
+ self.k_proj = nn.Linear(dim, dim, bias=qkv_bias)
+ self.v_proj = nn.Linear(dim, dim, bias=qkv_bias)
+
+ self.attn_drop = nn.Dropout(attn_drop)
+ self.proj = nn.Linear(dim, dim)
+ self.proj_drop = nn.Dropout(proj_drop)
+
+ def forward(self, q, k, v):
+ batch_size, q_sequence_length, num_channels = q.shape
+ if not k.shape == v.shape:
+ raise ValueError(f"keys ({list(k.shape)}) and values ({list(v.shape)}) have different shapes!")
+ batch_size, k_sequence_length, num_channels = k.shape
+ q = self.q_proj(q).reshape(batch_size, q_sequence_length, self.num_heads, num_channels // self.num_heads)
+ k = self.k_proj(k).reshape(batch_size, k_sequence_length, self.num_heads, num_channels // self.num_heads)
+ v = self.v_proj(v).reshape(batch_size, k_sequence_length, self.num_heads, num_channels // self.num_heads)
+
+ attn = torch.einsum("bnkc,bmkc->bknm", q, k) * self.scale
+
+ attn = attn.softmax(dim=-1)
+
+ output = torch.einsum("bknm,bmkc->bnkc", attn, v).reshape(batch_size, q_sequence_length, num_channels)
+
+ output = self.proj(output)
+ output = self.proj_drop(output)
+ return output
+
+
+class OneFormerTextTransformerDecoderLayer(nn.Module):
+ def __init__(
+ self,
+ d_model,
+ nhead,
+ dropout=0.1,
+ layer_norm_eps=1e-05,
+ ):
+ super().__init__()
+ self.self_attn = OneFormerTextMapperAttention(d_model, nhead, proj_drop=dropout)
+ self.cross_attn = OneFormerTextMapperAttention(d_model, nhead, proj_drop=dropout)
+
+ self.norm1 = nn.LayerNorm(d_model, eps=layer_norm_eps)
+ self.norm2 = nn.LayerNorm(d_model, eps=layer_norm_eps)
+ self.norm3 = nn.LayerNorm(d_model, eps=layer_norm_eps)
+ self.dropout = nn.Dropout(dropout)
+
+ self.mlp = nn.Sequential(
+ nn.Linear(d_model, d_model * 4), nn.GELU(), nn.Dropout(dropout), nn.Linear(d_model * 4, d_model)
+ )
+
+ def forward(self, hidden_state, mem):
+ q = k = v = self.norm1(hidden_state)
+ hidden_state = hidden_state + self.self_attn(q, k, v)
+ q = self.norm2(hidden_state)
+ hidden_state = hidden_state + self.cross_attn(q, mem, mem)
+ hidden_state = hidden_state + self.dropout(self.mlp(self.norm3(hidden_state)))
+ return hidden_state
+
+
+class OneFormerTextContextDecoder(nn.Module):
+ def __init__(
+ self,
+ transformer_width=256,
+ transformer_heads=4,
+ transformer_layers=6,
+ visual_dim=1024,
+ dropout=0.1,
+ layer_norm_eps=1e-05,
+ **kwargs,
+ ):
+ super().__init__()
+
+ self.memory_proj = nn.Sequential(
+ nn.LayerNorm(visual_dim, eps=layer_norm_eps),
+ nn.Linear(visual_dim, transformer_width),
+ nn.LayerNorm(transformer_width, eps=layer_norm_eps),
+ )
+
+ self.text_proj = nn.Sequential(
+ nn.LayerNorm(visual_dim, eps=layer_norm_eps),
+ nn.Linear(visual_dim, transformer_width),
+ )
+
+ self.decoder = nn.ModuleList(
+ [
+ OneFormerTextTransformerDecoderLayer(transformer_width, transformer_heads, dropout, layer_norm_eps)
+ for _ in range(transformer_layers)
+ ]
+ )
+
+ self.out_proj = nn.Sequential(
+ nn.LayerNorm(transformer_width, eps=layer_norm_eps), nn.Linear(transformer_width, visual_dim)
+ )
+
+ def forward(self, text, visual):
+ visual = self.memory_proj(visual)
+ hidden_state = self.text_proj(text)
+
+ for layer in self.decoder:
+ hidden_state = layer(hidden_state, visual)
+
+ return self.out_proj(hidden_state)
+
+
+class OneFormerTextMLP(nn.Module):
+ def __init__(
+ self,
+ hidden_size: int | None = None,
+ intermediate_size: int | None = None,
+ output_size: int | None = None,
+ ):
+ super().__init__()
+ self.activation_fn = ACT2FN["quick_gelu"]
+ self.fc1 = nn.Linear(hidden_size, intermediate_size)
+ self.fc2 = nn.Linear(intermediate_size, output_size)
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.fc1(hidden_states)
+ hidden_states = self.activation_fn(hidden_states)
+ hidden_states = self.fc2(hidden_states)
+ return hidden_states
+
+
+class OneFormerTextTransformerLayer(GradientCheckpointingLayer):
+ def __init__(self, width: int, heads: int, attn_mask: torch.Tensor, layer_norm_eps=1e-05):
+ super().__init__()
+ self.self_attn = nn.MultiheadAttention(width, heads)
+ self.layer_norm1 = nn.LayerNorm(width, eps=layer_norm_eps)
+ self.mlp = OneFormerTextMLP(width, width * 4, width)
+ self.layer_norm2 = nn.LayerNorm(width, eps=layer_norm_eps)
+ self.attn_mask = attn_mask
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ key_padding_mask: torch.Tensor | None = None,
+ ) -> torch.FloatTensor:
+ residual = hidden_states
+
+ hidden_states = self.layer_norm1(hidden_states)
+ hidden_states = self.self_attn(
+ hidden_states,
+ hidden_states,
+ hidden_states,
+ need_weights=False,
+ key_padding_mask=key_padding_mask,
+ )[0]
+ hidden_states = residual + hidden_states
+
+ residual = hidden_states
+ hidden_states = self.layer_norm2(hidden_states)
+ hidden_states = self.mlp(hidden_states)
+ hidden_states = residual + hidden_states
+
+ return hidden_states
+
+
+class OneFormerTextTransformer(nn.Module):
+ def __init__(
+ self,
+ width: int,
+ layers: int,
+ heads: int,
+ attn_mask: torch.Tensor | None = None,
+ use_checkpoint=False,
+ layer_norm_eps=1e-05,
+ ):
+ super().__init__()
+ self.width = width
+ self.num_layers = layers
+ self.layers = nn.Sequential(
+ *[OneFormerTextTransformerLayer(width, heads, attn_mask, layer_norm_eps) for _ in range(layers)]
+ )
+ self.use_checkpoint = use_checkpoint
+
+ def forward(self, hidden_states: torch.Tensor):
+ for layer in self.layers:
+ hidden_states = layer(hidden_states)
+ return hidden_states
+
+
+class OneFormerTextEncoder(nn.Module):
+ def __init__(
+ self,
+ context_length: int,
+ width: int,
+ layers: int,
+ vocab_size,
+ use_checkpoint=False,
+ layer_norm_eps=1e-05,
+ ):
+ super().__init__()
+ heads = width // 64
+ self.context_length = context_length
+ self.width = width
+ self.transformer = OneFormerTextTransformer(
+ width=width,
+ layers=layers,
+ heads=heads,
+ attn_mask=self.build_attention_mask(),
+ use_checkpoint=use_checkpoint,
+ layer_norm_eps=layer_norm_eps,
+ )
+
+ self.positional_embedding = nn.Parameter(torch.empty(self.context_length, width))
+ self.ln_final = nn.LayerNorm(width, eps=layer_norm_eps)
+ self.token_embedding = nn.Embedding(vocab_size, width)
+
+ def build_attention_mask(self):
+ # lazily create causal attention mask, with full attention between the vision tokens
+ # pytorch uses additive attention mask; fill with -inf
+ mask = torch.empty(self.context_length, self.context_length)
+ mask.fill_(float("-inf"))
+ mask.triu_(1) # zero out the lower diagonal
+ return mask
+
+ def forward(self, text):
+ hidden_state = self.token_embedding(text)
+ hidden_state = hidden_state + self.positional_embedding
+ hidden_state = hidden_state.permute(1, 0, 2)
+ hidden_state = self.transformer(hidden_state)
+ hidden_state = hidden_state.permute(1, 0, 2)
+ hidden_state = self.ln_final(hidden_state)
+ hidden_state = hidden_state[torch.arange(hidden_state.shape[0]), text.argmax(dim=-1)]
+
+ return hidden_state
+
+
+class OneFormerTextMapper(nn.Module):
+ def __init__(self, config: OneFormerConfig):
+ super().__init__()
+ self.text_encoder = OneFormerTextEncoder(
+ context_length=config.text_encoder_context_length,
+ width=config.text_encoder_width,
+ layers=config.text_encoder_num_layers,
+ vocab_size=config.text_encoder_vocab_size,
+ layer_norm_eps=config.layer_norm_eps,
+ )
+
+ self.text_projector = OneFormerMLPPredictionHead(
+ config.text_encoder_width,
+ config.hidden_dim,
+ config.hidden_dim,
+ config.text_encoder_proj_layers,
+ )
+ if config.text_encoder_n_ctx > 0:
+ self.prompt_ctx = nn.Embedding(
+ config.text_encoder_n_ctx,
+ config.text_encoder_width,
+ )
+ else:
+ self.prompt_ctx = None
+
+ def forward(
+ self,
+ inputs: Tensor,
+ ) -> Tensor:
+ text_queries = self.encode_text(inputs)
+
+ return text_queries
+
+ def encode_text(self, text):
+ if text.ndim is None:
+ raise ValueError("text must not be NoneType")
+ if text.ndim not in [2, 3]:
+ raise ValueError("Number of dimensions in text must be 2 or 3")
+ squeeze_dim = False
+ num_text = 1
+ if text.ndim == 3:
+ num_text = text.shape[1]
+ batch_size, num_text, hidden_dim = text.shape
+ text = text.reshape(batch_size * num_text, hidden_dim)
+ squeeze_dim = True
+
+ # [batch_size, num_channels]
+ encoded_text = self.text_encoder(text)
+
+ text_queries = self.text_projector(encoded_text)
+
+ if squeeze_dim:
+ _, hidden_dim = text_queries.shape
+ text_queries = text_queries.reshape(batch_size, num_text, hidden_dim)
+ if self.prompt_ctx is not None:
+ text_queries_ctx = self.prompt_ctx.weight.unsqueeze(0).repeat(text_queries.shape[0], 1, 1)
+ text_queries = torch.cat([text_queries, text_queries_ctx], dim=1)
+
+ return text_queries
+
+
+class OneFormerTaskModel(nn.Module):
+ def __init__(self, config: OneFormerConfig):
+ super().__init__()
+ self.task_mlp = OneFormerMLPPredictionHead(
+ config.task_seq_len,
+ config.hidden_dim,
+ config.hidden_dim,
+ 2,
+ )
+
+ def forward(self, inputs: Tensor) -> Tensor:
+ task_tokens = self.task_mlp(inputs)
+ return task_tokens
+
+
+@auto_docstring
+class OneFormerPreTrainedModel(PreTrainedModel):
+ config: OneFormerConfig
+ base_model_prefix = "model"
+ main_input_name = "pixel_values"
+ input_modalities = ("image",)
+
+ @torch.no_grad()
+ def _init_weights(self, module: nn.Module):
+ xavier_std = self.config.init_xavier_std
+ std = self.config.init_std
+ if isinstance(module, OneFormerTransformerModule):
+ if module.input_projections is not None:
+ for input_projection in module.input_projections:
+ if not isinstance(input_projection, nn.Sequential):
+ init.xavier_uniform_(input_projection.weight, gain=xavier_std)
+ init.constant_(input_projection.bias, 0)
+ elif isinstance(module, OneFormerTransformerDecoder):
+ init.xavier_uniform_(module.query_input_projection.weight, gain=xavier_std)
+ init.constant_(module.query_input_projection.bias, 0)
+ elif isinstance(module, OneFormerPixelDecoderEncoderMultiscaleDeformableAttention):
+ init.constant_(module.sampling_offsets.weight, 0.0)
+ thetas = torch.arange(module.n_heads, dtype=torch.int64).float() * (2.0 * math.pi / module.n_heads)
+ grid_init = torch.stack([thetas.cos(), thetas.sin()], -1)
+ grid_init = (
+ (grid_init / grid_init.abs().max(-1, keepdim=True)[0])
+ .view(module.n_heads, 1, 1, 2)
+ .repeat(1, module.n_levels, module.n_points, 1)
+ )
+ for i in range(module.n_points):
+ grid_init[:, :, i, :] *= i + 1
+
+ init.copy_(module.sampling_offsets.bias, grid_init.view(-1))
+ init.constant_(module.attention_weights.weight, 0.0)
+ init.constant_(module.attention_weights.bias, 0.0)
+ init.xavier_uniform_(module.value_proj.weight)
+ init.constant_(module.value_proj.bias, 0.0)
+ init.xavier_uniform_(module.output_proj.weight)
+ init.constant_(module.output_proj.bias, 0.0)
+ elif isinstance(module, OneFormerPixelDecoder):
+ init.normal_(module.level_embed, std=0)
+ elif isinstance(module, (OneFormerTransformerDecoderLayer, OneFormerTransformerDecoderQueryTransformer)):
+ for p in module.parameters():
+ if p.dim() > 1:
+ init.xavier_uniform_(p, gain=xavier_std)
+ elif isinstance(module, OneFormerTextTransformer):
+ proj_std = (module.width**-0.5) * ((2 * module.num_layers) ** -0.5)
+ attn_std = module.width**-0.5
+ fc_std = (2 * module.width) ** -0.5
+ for layer in module.layers:
+ init.normal_(layer.self_attn.in_proj_weight, std=attn_std)
+ init.normal_(layer.self_attn.out_proj.weight, std=proj_std)
+ init.normal_(layer.mlp.fc1.weight, std=fc_std)
+ init.normal_(layer.mlp.fc2.weight, std=proj_std)
+ elif isinstance(module, OneFormerTextEncoder):
+ init.normal_(module.token_embedding.weight, std=0.02)
+ init.normal_(module.positional_embedding, std=0.01)
+ if hasattr(module, "reference_points"):
+ init.xavier_uniform_(module.reference_points.weight, gain=1.0)
+ init.constant_(module.reference_points.bias, 0.0)
+ elif isinstance(module, OneFormerMLPPredictionHead):
+ for submodule in module.modules():
+ if isinstance(submodule, nn.Linear):
+ init.xavier_uniform_(submodule.weight, gain=xavier_std)
+ init.constant_(submodule.bias, 0)
+ elif isinstance(module, nn.MultiheadAttention):
+ init.normal_(module.in_proj_weight, mean=0.0, std=std)
+ init.zeros_(module.in_proj_bias)
+ elif isinstance(module, (nn.Linear, nn.Conv2d, nn.BatchNorm2d)):
+ init.normal_(module.weight, mean=0.0, std=std)
+ if module.bias is not None:
+ init.zeros_(module.bias)
+ if getattr(module, "running_mean", None) is not None:
+ init.zeros_(module.running_mean)
+ init.ones_(module.running_var)
+ init.zeros_(module.num_batches_tracked)
+ elif isinstance(module, (nn.LayerNorm, nn.GroupNorm)):
+ init.ones_(module.weight)
+ init.zeros_(module.bias)
+ elif isinstance(module, nn.Embedding):
+ init.normal_(module.weight, mean=0.0, std=std)
+ # Here we need the check explicitly, as we slice the weight in the `zeros_` call, so it looses the flag
+ if module.padding_idx is not None and not getattr(module.weight, "_is_hf_initialized", False):
+ init.zeros_(module.weight[module.padding_idx])
+ elif isinstance(module, OneFormerLoss):
+ init.constant_(module.logit_scale, np.log(1 / self.config.contrastive_temperature))
+ empty_weight = torch.ones(module.num_classes + 1)
+ empty_weight[-1] = module.eos_coef
+ init.copy_(module.empty_weight, empty_weight)
+
+
+@auto_docstring
+class OneFormerModel(OneFormerPreTrainedModel):
+ main_input_name = ["pixel_values", "task_inputs"]
+
+ def __init__(self, config: OneFormerConfig):
+ super().__init__(config)
+ self.pixel_level_module = OneFormerPixelLevelModule(config)
+ self.transformer_module = OneFormerTransformerModule(in_features=config.conv_dim, config=config)
+ self.task_encoder = OneFormerTaskModel(config)
+ self.is_training = config.is_training
+
+ if self.is_training:
+ self.text_mapper = OneFormerTextMapper(config)
+ else:
+ self.text_mapper = None
+
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: Tensor,
+ task_inputs: Tensor,
+ text_inputs: Tensor | None = None,
+ pixel_mask: Tensor | None = None,
+ output_hidden_states: bool | None = None,
+ output_attentions: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> OneFormerModelOutput:
+ r"""
+ task_inputs (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
+ Task inputs. Task inputs can be obtained using [`AutoImageProcessor`]. See [`OneFormerProcessor.__call__`]
+ for details.
+ text_inputs (`list[torch.Tensor]`, *optional*):
+ Tensor of shape `(num_queries, sequence_length)` to be fed to a model
+
+ Example:
+
+ ```python
+ >>> import torch
+ >>> from PIL import Image
+ >>> import httpx
+ >>> from io import BytesIO
+ >>> from transformers import OneFormerProcessor, OneFormerModel
+
+ >>> # download texting image
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
+ >>> with httpx.stream("GET", url) as response:
+ ... image = Image.open(BytesIO(response.read()))
+
+ >>> # load processor for preprocessing the inputs
+ >>> processor = OneFormerProcessor.from_pretrained("shi-labs/oneformer_ade20k_swin_tiny")
+ >>> model = OneFormerModel.from_pretrained("shi-labs/oneformer_ade20k_swin_tiny")
+ >>> inputs = processor(image, ["semantic"], return_tensors="pt")
+
+ >>> with torch.no_grad():
+ ... outputs = model(**inputs)
+
+ >>> mask_predictions = outputs.transformer_decoder_mask_predictions
+ >>> class_predictions = outputs.transformer_decoder_class_predictions
+
+ >>> f"👉 Mask Predictions Shape: {list(mask_predictions.shape)}, Class Predictions Shape: {list(class_predictions.shape)}"
+ '👉 Mask Predictions Shape: [1, 150, 128, 171], Class Predictions Shape: [1, 150, 151]'
+ ```"""
+
+ if pixel_values is None:
+ raise ValueError("You have to specify pixel_values")
+
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ batch_size, _, height, width = pixel_values.shape
+
+ if pixel_mask is None:
+ pixel_mask = torch.ones((batch_size, height, width), device=pixel_values.device)
+
+ pixel_level_module_output = self.pixel_level_module(pixel_values, output_hidden_states)
+
+ multi_scale_features = pixel_level_module_output.decoder_features
+ mask_features = pixel_level_module_output.decoder_last_feature
+
+ task_token = self.task_encoder(task_inputs.to(self.dtype))
+
+ if self.is_training:
+ text_queries = self.text_mapper(text_inputs)
+ else:
+ text_queries = None
+
+ transformer_module_output = self.transformer_module(
+ multi_scale_features=multi_scale_features,
+ mask_features=mask_features,
+ task_token=task_token,
+ output_attentions=output_attentions,
+ )
+
+ queries = transformer_module_output.object_queries
+
+ encoder_hidden_states = None
+ pixel_decoder_hidden_states = None
+ transformer_decoder_hidden_states = None
+
+ if output_hidden_states:
+ encoder_hidden_states = pixel_level_module_output.encoder_features
+ pixel_decoder_hidden_states = (pixel_level_module_output.decoder_last_feature,)
+ for f in pixel_level_module_output.decoder_features:
+ pixel_decoder_hidden_states += (f,)
+ transformer_decoder_hidden_states = transformer_module_output.auxiliary_predictions
+
+ output = OneFormerModelOutput(
+ encoder_hidden_states=encoder_hidden_states,
+ pixel_decoder_hidden_states=pixel_decoder_hidden_states,
+ transformer_decoder_hidden_states=transformer_decoder_hidden_states,
+ transformer_decoder_object_queries=queries,
+ transformer_decoder_contrastive_queries=transformer_module_output.contrastive_logits,
+ transformer_decoder_mask_predictions=transformer_module_output.prediction_masks,
+ transformer_decoder_class_predictions=transformer_module_output.prediction_class,
+ transformer_decoder_auxiliary_predictions=transformer_module_output.auxiliary_predictions,
+ text_queries=text_queries,
+ task_token=task_token,
+ attentions=transformer_module_output.attentions,
+ )
+
+ if not return_dict:
+ output = tuple(v for v in output.values())
+
+ return output
+
+
+@auto_docstring(
+ custom_intro="""
+ OneFormer Model for instance, semantic and panoptic image segmentation.
+ """
+)
+class OneFormerForUniversalSegmentation(OneFormerPreTrainedModel):
+ main_input_name = ["pixel_values", "task_inputs"]
+
+ def __init__(self, config: OneFormerConfig):
+ super().__init__(config)
+ self.model = OneFormerModel(config)
+
+ self.matcher = OneFormerHungarianMatcher(
+ cost_class=config.class_weight,
+ cost_dice=config.dice_weight,
+ cost_mask=config.mask_weight,
+ num_points=config.train_num_points,
+ )
+
+ self.weight_dict: dict[str, float] = {
+ "loss_cross_entropy": config.class_weight,
+ "loss_mask": config.mask_weight,
+ "loss_dice": config.dice_weight,
+ "loss_contrastive": config.contrastive_weight,
+ }
+
+ self.criterion = OneFormerLoss(
+ num_classes=config.num_labels,
+ matcher=self.matcher,
+ weight_dict=self.weight_dict,
+ eos_coef=config.no_object_weight,
+ num_points=config.train_num_points,
+ oversample_ratio=config.oversample_ratio,
+ importance_sample_ratio=config.importance_sample_ratio,
+ contrastive_temperature=config.contrastive_temperature,
+ )
+
+ self.post_init()
+
+ def get_loss_dict(
+ self,
+ masks_queries_logits: Tensor,
+ class_queries_logits: Tensor,
+ contrastive_queries_logits: Tensor,
+ mask_labels: Tensor,
+ class_labels: Tensor,
+ text_queries: Tensor,
+ auxiliary_predictions: dict[str, Tensor],
+ calculate_contrastive_loss: bool,
+ ) -> dict[str, Tensor]:
+ loss_dict: dict[str, Tensor] = self.criterion(
+ masks_queries_logits=masks_queries_logits,
+ class_queries_logits=class_queries_logits,
+ contrastive_queries_logits=contrastive_queries_logits,
+ mask_labels=mask_labels,
+ class_labels=class_labels,
+ text_queries=text_queries,
+ auxiliary_predictions=auxiliary_predictions,
+ calculate_contrastive_loss=calculate_contrastive_loss,
+ )
+
+ # weight each loss by `self.weight_dict[]` including auxiliary losses
+ for key, weight in self.weight_dict.items():
+ for loss_key, loss in loss_dict.items():
+ if key in loss_key:
+ loss *= weight
+
+ return loss_dict
+
+ def get_loss(self, loss_dict: dict[str, Tensor]) -> Tensor:
+ return sum(loss_dict.values())
+
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: Tensor,
+ task_inputs: Tensor,
+ text_inputs: Tensor | None = None,
+ mask_labels: list[Tensor] | None = None,
+ class_labels: list[Tensor] | None = None,
+ pixel_mask: Tensor | None = None,
+ output_auxiliary_logits: bool | None = None,
+ output_hidden_states: bool | None = None,
+ output_attentions: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> OneFormerForUniversalSegmentationOutput:
+ r"""
+ task_inputs (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
+ Task inputs. Task inputs can be obtained using [`AutoImageProcessor`]. See [`OneFormerProcessor.__call__`]
+ for details.
+ text_inputs (`list[torch.Tensor]`, *optional*):
+ Tensor of shape `(num_queries, sequence_length)` to be fed to a model
+ mask_labels (`list[torch.Tensor]`, *optional*):
+ List of mask labels of shape `(num_labels, height, width)` to be fed to a model
+ class_labels (`list[torch.LongTensor]`, *optional*):
+ list of target class labels of shape `(num_labels, height, width)` to be fed to a model. They identify the
+ labels of `mask_labels`, e.g. the label of `mask_labels[i][j]` if `class_labels[i][j]`.
+ output_auxiliary_logits (`bool`, *optional*):
+ Whether or not to output auxiliary logits.
+
+ Example:
+
+ Universal segmentation example:
+
+ ```python
+ >>> from transformers import OneFormerProcessor, OneFormerForUniversalSegmentation
+ >>> from PIL import Image
+ >>> import httpx
+ >>> from io import BytesIO
+ >>> import torch
+
+ >>> # load OneFormer fine-tuned on ADE20k for universal segmentation
+ >>> processor = OneFormerProcessor.from_pretrained("shi-labs/oneformer_ade20k_swin_tiny")
+ >>> model = OneFormerForUniversalSegmentation.from_pretrained("shi-labs/oneformer_ade20k_swin_tiny")
+
+ >>> url = (
+ ... "https://huggingface.co/datasets/hf-internal-testing/fixtures_ade20k/resolve/main/ADE_val_00000001.jpg"
+ ... )
+ >>> with httpx.stream("GET", url) as response:
+ ... image = Image.open(BytesIO(response.read()))
+
+ >>> # Semantic Segmentation
+ >>> inputs = processor(image, ["semantic"], return_tensors="pt")
+
+ >>> with torch.no_grad():
+ ... outputs = model(**inputs)
+ >>> # model predicts class_queries_logits of shape `(batch_size, num_queries)`
+ >>> # and masks_queries_logits of shape `(batch_size, num_queries, height, width)`
+ >>> class_queries_logits = outputs.class_queries_logits
+ >>> masks_queries_logits = outputs.masks_queries_logits
+
+ >>> # you can pass them to processor for semantic postprocessing
+ >>> predicted_semantic_map = processor.post_process_semantic_segmentation(
+ ... outputs, target_sizes=[(image.height, image.width)]
+ ... )[0]
+ >>> f"👉 Semantic Predictions Shape: {list(predicted_semantic_map.shape)}"
+ '👉 Semantic Predictions Shape: [512, 683]'
+
+ >>> # Instance Segmentation
+ >>> inputs = processor(image, ["instance"], return_tensors="pt")
+
+ >>> with torch.no_grad():
+ ... outputs = model(**inputs)
+ >>> # model predicts class_queries_logits of shape `(batch_size, num_queries)`
+ >>> # and masks_queries_logits of shape `(batch_size, num_queries, height, width)`
+ >>> class_queries_logits = outputs.class_queries_logits
+ >>> masks_queries_logits = outputs.masks_queries_logits
+
+ >>> # you can pass them to processor for instance postprocessing
+ >>> predicted_instance_map = processor.post_process_instance_segmentation(
+ ... outputs, target_sizes=[(image.height, image.width)]
+ ... )[0]["segmentation"]
+ >>> f"👉 Instance Predictions Shape: {list(predicted_instance_map.shape)}"
+ '👉 Instance Predictions Shape: [512, 683]'
+
+ >>> # Panoptic Segmentation
+ >>> inputs = processor(image, ["panoptic"], return_tensors="pt")
+
+ >>> with torch.no_grad():
+ ... outputs = model(**inputs)
+ >>> # model predicts class_queries_logits of shape `(batch_size, num_queries)`
+ >>> # and masks_queries_logits of shape `(batch_size, num_queries, height, width)`
+ >>> class_queries_logits = outputs.class_queries_logits
+ >>> masks_queries_logits = outputs.masks_queries_logits
+
+ >>> # you can pass them to processor for panoptic postprocessing
+ >>> predicted_panoptic_map = processor.post_process_panoptic_segmentation(
+ ... outputs, target_sizes=[(image.height, image.width)]
+ ... )[0]["segmentation"]
+ >>> f"👉 Panoptic Predictions Shape: {list(predicted_panoptic_map.shape)}"
+ '👉 Panoptic Predictions Shape: [512, 683]'
+ ```
+ """
+
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ outputs = self.model(
+ pixel_values=pixel_values,
+ task_inputs=task_inputs,
+ text_inputs=text_inputs,
+ pixel_mask=pixel_mask,
+ output_hidden_states=output_hidden_states or self.config.use_auxiliary_loss,
+ output_attentions=output_attentions,
+ return_dict=True,
+ )
+
+ loss, loss_dict, auxiliary_predictions = None, None, None
+
+ class_queries_logits = outputs.transformer_decoder_class_predictions
+ masks_queries_logits = outputs.transformer_decoder_mask_predictions
+ contrastive_queries_logits = outputs.transformer_decoder_contrastive_queries
+ auxiliary_predictions = outputs.transformer_decoder_auxiliary_predictions
+ text_queries = outputs.text_queries
+
+ if mask_labels is not None and class_labels is not None:
+ loss_dict: dict[str, Tensor] = self.get_loss_dict(
+ masks_queries_logits=masks_queries_logits,
+ class_queries_logits=class_queries_logits,
+ contrastive_queries_logits=contrastive_queries_logits,
+ mask_labels=mask_labels,
+ class_labels=class_labels,
+ text_queries=text_queries,
+ auxiliary_predictions=auxiliary_predictions,
+ calculate_contrastive_loss=self.config.contrastive_temperature is not None,
+ )
+ loss = self.get_loss(loss_dict)
+
+ output_auxiliary_logits = (
+ self.config.output_auxiliary_logits if output_auxiliary_logits is None else output_auxiliary_logits
+ )
+ if not output_auxiliary_logits:
+ auxiliary_predictions = None
+
+ output = OneFormerForUniversalSegmentationOutput(
+ class_queries_logits=class_queries_logits,
+ masks_queries_logits=masks_queries_logits,
+ auxiliary_predictions=auxiliary_predictions,
+ loss=loss,
+ **outputs,
+ )
+
+ if not return_dict:
+ output = tuple(v for v in output.values())
+ if loss is not None:
+ output = (loss) + output
+ return output
+
+
+__all__ = ["OneFormerForUniversalSegmentation", "OneFormerModel", "OneFormerPreTrainedModel"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/oneformer/processing_oneformer.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/oneformer/processing_oneformer.py
new file mode 100644
index 0000000000000000000000000000000000000000..fef0b2c3b6803f728b9a952713afd96e0591dbef
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/oneformer/processing_oneformer.py
@@ -0,0 +1,181 @@
+# Copyright 2022 SHI Labs and The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""
+Image/Text processor class for OneFormer
+"""
+
+from ...processing_utils import ProcessorMixin
+from ...utils import auto_docstring, is_torch_available
+
+
+if is_torch_available():
+ import torch
+
+
+@auto_docstring
+class OneFormerProcessor(ProcessorMixin):
+ def __init__(
+ self, image_processor=None, tokenizer=None, max_seq_length: int = 77, task_seq_length: int = 77, **kwargs
+ ):
+ r"""
+ max_seq_length (`int`, *optional*, defaults to `77`):
+ Maximum sequence length for encoding class names and text inputs. This parameter controls the
+ maximum number of tokens used when tokenizing class names and other text inputs for the model.
+ task_seq_length (`int`, *optional*, defaults to `77`):
+ Maximum sequence length specifically for encoding task descriptions. Task descriptions (e.g.,
+ "the task is semantic") are tokenized with this length limit, which may differ from the general
+ text sequence length.
+ """
+ self.max_seq_length = max_seq_length
+ self.task_seq_length = task_seq_length
+
+ super().__init__(image_processor, tokenizer)
+
+ def _preprocess_text(self, text_list=None, max_length=77):
+ if text_list is None:
+ raise ValueError("tokens cannot be None.")
+
+ tokens = self.tokenizer(text_list, padding="max_length", max_length=max_length, truncation=True)
+
+ attention_masks, input_ids = tokens["attention_mask"], tokens["input_ids"]
+
+ token_inputs = []
+ for attn_mask, input_id in zip(attention_masks, input_ids):
+ token = torch.tensor(attn_mask) * torch.tensor(input_id)
+ token_inputs.append(token.unsqueeze(0))
+
+ token_inputs = torch.cat(token_inputs, dim=0)
+ return token_inputs
+
+ @auto_docstring
+ def __call__(self, images=None, task_inputs=None, segmentation_maps=None, **kwargs):
+ r"""
+ task_inputs (`str` or `list[str]`, *required*):
+ The task type(s) for segmentation. Must be one or more of `"semantic"`, `"instance"`, or `"panoptic"`.
+ Can be a single string for a single image, or a list of strings (one per image) for batch processing.
+ The task type determines which type of segmentation the model will perform on the input images.
+ segmentation_maps (`ImageInput`, *optional*):
+ The corresponding semantic segmentation maps with the pixel-wise annotations.
+
+ (`bool`, *optional*, defaults to `True`):
+ Whether or not to pad images up to the largest image in a batch and create a pixel mask.
+
+ If left to the default, will return a pixel mask that is:
+
+ - 1 for pixels that are real (i.e. **not masked**),
+ - 0 for pixels that are padding (i.e. **masked**).
+
+ Returns:
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
+ - **task_inputs** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
+ - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
+ """
+
+ if task_inputs is None:
+ raise ValueError("You have to specify the task_input. Found None.")
+ elif images is None:
+ raise ValueError("You have to specify the image. Found None.")
+
+ if not all(task in ["semantic", "instance", "panoptic"] for task in task_inputs):
+ raise ValueError("task_inputs must be semantic, instance, or panoptic.")
+
+ encoded_inputs = self.image_processor(images, task_inputs, segmentation_maps, **kwargs)
+
+ if isinstance(task_inputs, str):
+ task_inputs = [task_inputs]
+
+ if isinstance(task_inputs, list) and all(isinstance(task_input, str) for task_input in task_inputs):
+ task_token_inputs = []
+ for task in task_inputs:
+ task_input = f"the task is {task}"
+ task_token_inputs.append(task_input)
+ encoded_inputs["task_inputs"] = self._preprocess_text(task_token_inputs, max_length=self.task_seq_length)
+ else:
+ raise TypeError("Task Inputs should be a string or a list of strings.")
+
+ if hasattr(encoded_inputs, "text_inputs"):
+ texts_list = encoded_inputs.text_inputs
+
+ text_inputs = []
+ for texts in texts_list:
+ text_input_list = self._preprocess_text(texts, max_length=self.max_seq_length)
+ text_inputs.append(text_input_list.unsqueeze(0))
+
+ encoded_inputs["text_inputs"] = torch.cat(text_inputs, dim=0)
+
+ return encoded_inputs
+
+ def encode_inputs(self, images=None, task_inputs=None, segmentation_maps=None, **kwargs):
+ """
+ This method forwards all its arguments to [`OneFormerImageProcessor.encode_inputs`] and then tokenizes the
+ task_inputs. Please refer to the docstring of this method for more information.
+ """
+
+ if task_inputs is None:
+ raise ValueError("You have to specify the task_input. Found None.")
+ elif images is None:
+ raise ValueError("You have to specify the image. Found None.")
+
+ if not all(task in ["semantic", "instance", "panoptic"] for task in task_inputs):
+ raise ValueError("task_inputs must be semantic, instance, or panoptic.")
+
+ encoded_inputs = self.image_processor.encode_inputs(images, task_inputs, segmentation_maps, **kwargs)
+
+ if isinstance(task_inputs, str):
+ task_inputs = [task_inputs]
+
+ if isinstance(task_inputs, list) and all(isinstance(task_input, str) for task_input in task_inputs):
+ task_token_inputs = []
+ for task in task_inputs:
+ task_input = f"the task is {task}"
+ task_token_inputs.append(task_input)
+ encoded_inputs["task_inputs"] = self._preprocess_text(task_token_inputs, max_length=self.task_seq_length)
+ else:
+ raise TypeError("Task Inputs should be a string or a list of strings.")
+
+ if hasattr(encoded_inputs, "text_inputs"):
+ texts_list = encoded_inputs.text_inputs
+
+ text_inputs = []
+ for texts in texts_list:
+ text_input_list = self._preprocess_text(texts, max_length=self.max_seq_length)
+ text_inputs.append(text_input_list.unsqueeze(0))
+
+ encoded_inputs["text_inputs"] = torch.cat(text_inputs, dim=0)
+
+ return encoded_inputs
+
+ def post_process_semantic_segmentation(self, *args, **kwargs):
+ """
+ This method forwards all its arguments to [`OneFormerImageProcessor.post_process_semantic_segmentation`].
+ Please refer to the docstring of this method for more information.
+ """
+ return self.image_processor.post_process_semantic_segmentation(*args, **kwargs)
+
+ def post_process_instance_segmentation(self, *args, **kwargs):
+ """
+ This method forwards all its arguments to [`OneFormerImageProcessor.post_process_instance_segmentation`].
+ Please refer to the docstring of this method for more information.
+ """
+ return self.image_processor.post_process_instance_segmentation(*args, **kwargs)
+
+ def post_process_panoptic_segmentation(self, *args, **kwargs):
+ """
+ This method forwards all its arguments to [`OneFormerImageProcessor.post_process_panoptic_segmentation`].
+ Please refer to the docstring of this method for more information.
+ """
+ return self.image_processor.post_process_panoptic_segmentation(*args, **kwargs)
+
+
+__all__ = ["OneFormerProcessor"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/patchtst/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/patchtst/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..f1a045bfb1820424f77c9b798a3c027569eed3eb
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/patchtst/__init__.py
@@ -0,0 +1,27 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_patchtst import *
+ from .modeling_patchtst import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/patchtst/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/patchtst/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1cec1d66d0e48e91f6117ec658515a1d6000255f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/patchtst/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/patchtst/__pycache__/configuration_patchtst.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/patchtst/__pycache__/configuration_patchtst.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f81c62b05f9224b67bc3e3f297fc32502f60c928
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/patchtst/__pycache__/configuration_patchtst.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/patchtst/__pycache__/modeling_patchtst.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/patchtst/__pycache__/modeling_patchtst.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c3d52525e49e6c133671687d828a1b6210fdf2fb
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/patchtst/__pycache__/modeling_patchtst.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/patchtst/configuration_patchtst.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/patchtst/configuration_patchtst.py
new file mode 100644
index 0000000000000000000000000000000000000000..21e12276c89739f915105ca86aba523032df6b2b
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/patchtst/configuration_patchtst.py
@@ -0,0 +1,170 @@
+# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PatchTST model configuration"""
+
+from huggingface_hub.dataclasses import strict
+
+from transformers.configuration_utils import PreTrainedConfig
+from transformers.utils import auto_docstring
+
+
+@auto_docstring(checkpoint="ibm-granite/granite-timeseries-patchtst")
+@strict
+class PatchTSTConfig(PreTrainedConfig):
+ r"""
+ context_length (`int`, *optional*, defaults to 32):
+ The context length of the input sequence.
+ distribution_output (`str`, *optional*, defaults to `"student_t"`):
+ The distribution emission head for the model when loss is "nll". Could be either "student_t", "normal" or
+ "negative_binomial".
+ loss (`str`, *optional*, defaults to `"mse"`):
+ The loss function for the model corresponding to the `distribution_output` head. For parametric
+ distributions it is the negative log likelihood ("nll") and for point estimates it is the mean squared
+ error "mse".
+ patch_length (`int`, *optional*, defaults to 1):
+ Define the patch length of the patchification process.
+ patch_stride (`int`, *optional*, defaults to 1):
+ Define the stride of the patchification process.
+ num_attention_heads (`int`, *optional*, defaults to 4):
+ Number of attention heads for each attention layer in the Transformer encoder.
+ share_embedding (`bool`, *optional*, defaults to `True`):
+ Sharing the input embedding across all channels.
+ channel_attention (`bool`, *optional*, defaults to `False`):
+ Activate channel attention block in the Transformer to allow channels to attend each other.
+ ffn_dim (`int`, *optional*, defaults to 512):
+ Dimension of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
+ norm_type (`str` , *optional*, defaults to `"batchnorm"`):
+ Normalization at each Transformer layer. Can be `"batchnorm"` or `"layernorm"`.
+ norm_eps (`float`, *optional*, defaults to 1e-05):
+ A value added to the denominator for numerical stability of normalization.
+ positional_dropout (`float`, *optional*, defaults to 0.0):
+ The dropout probability in the positional embedding layer.
+ path_dropout (`float`, *optional*, defaults to 0.0):
+ The dropout path in the residual block.
+ ff_dropout (`float`, *optional*, defaults to 0.0):
+ The dropout probability used between the two layers of the feed-forward networks.
+ bias (`bool`, *optional*, defaults to `True`):
+ Whether to add bias in the feed-forward networks.
+ activation_function (`str`, *optional*, defaults to `"gelu"`):
+ The non-linear activation function (string) in the Transformer.`"gelu"` and `"relu"` are supported.
+ pre_norm (`bool`, *optional*, defaults to `True`):
+ Normalization is applied before self-attention if pre_norm is set to `True`. Otherwise, normalization is
+ applied after residual block.
+ positional_encoding_type (`str`, *optional*, defaults to `"sincos"`):
+ Positional encodings. Options `"random"` and `"sincos"` are supported.
+ use_cls_token (`bool`, *optional*, defaults to `False`):
+ Whether cls token is used.
+ init_std (`float`, *optional*, defaults to 0.02):
+ The standard deviation of the truncated normal weight initialization distribution.
+ share_projection (`bool`, *optional*, defaults to `True`):
+ Sharing the projection layer across different channels in the forecast head.
+ scaling (`Union`, *optional*, defaults to `"std"`):
+ Whether to scale the input targets via "mean" scaler, "std" scaler or no scaler if `None`. If `True`, the
+ scaler is set to "mean".
+ do_mask_input (`bool`, *optional*):
+ Apply masking during the pretraining.
+ mask_type (`str`, *optional*, defaults to `"random"`):
+ Masking type. Only `"random"` and `"forecast"` are currently supported.
+ random_mask_ratio (`float`, *optional*, defaults to 0.5):
+ Masking ratio applied to mask the input data during random pretraining.
+ num_forecast_mask_patches (`int` or `list`, *optional*, defaults to `[2]`):
+ Number of patches to be masked at the end of each batch sample. If it is an integer,
+ all the samples in the batch will have the same number of masked patches. If it is a list,
+ samples in the batch will be randomly masked by numbers defined in the list. This argument is only used
+ for forecast pretraining.
+ channel_consistent_masking (`bool`, *optional*, defaults to `False`):
+ If channel consistent masking is True, all the channels will have the same masking pattern.
+ unmasked_channel_indices (`list`, *optional*):
+ Indices of channels that are not masked during pretraining. Values in the list are number between 1 and
+ `num_input_channels`
+ mask_value (`int`, *optional*, defaults to 0):
+ Values in the masked patches will be filled by `mask_value`.
+ pooling_type (`str`, *optional*, defaults to `"mean"`):
+ Pooling of the embedding. `"mean"`, `"max"` and `None` are supported.
+ head_dropout (`float`, *optional*, defaults to 0.0):
+ The dropout probability for head.
+ prediction_length (`int`, *optional*, defaults to 24):
+ The prediction horizon that the model will output.
+ num_targets (`int`, *optional*, defaults to 1):
+ Number of targets for regression and classification tasks. For classification, it is the number of
+ classes.
+ output_range (`list`, *optional*):
+ Output range for regression task. The range of output values can be set to enforce the model to produce
+ values within a range.
+ num_parallel_samples (`int`, *optional*, defaults to 100):
+ The number of samples is generated in parallel for probabilistic prediction.
+
+ ```python
+ >>> from transformers import PatchTSTConfig, PatchTSTModel
+
+ >>> # Initializing an PatchTST configuration with 12 time steps for prediction
+ >>> configuration = PatchTSTConfig(prediction_length=12)
+
+ >>> # Randomly initializing a model (with random weights) from the configuration
+ >>> model = PatchTSTModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```
+ """
+
+ model_type = "patchtst"
+ attribute_map = {
+ "hidden_size": "d_model",
+ "num_attention_heads": "num_attention_heads",
+ "num_hidden_layers": "num_hidden_layers",
+ }
+
+ num_input_channels: int = 1
+ context_length: int = 32
+ distribution_output: str = "student_t"
+ loss: str | None = "mse"
+ patch_length: int = 1
+ patch_stride: int = 1
+ num_hidden_layers: int = 3
+ d_model: int = 128
+ num_attention_heads: int = 4
+ share_embedding: bool = True
+ channel_attention: bool = False
+ ffn_dim: int = 512
+ norm_type: str = "batchnorm"
+ norm_eps: float = 1e-05
+ attention_dropout: float | int = 0.0
+ positional_dropout: float | int = 0.0
+ path_dropout: float | int = 0.0
+ ff_dropout: float | int = 0.0
+ bias: bool = True
+ activation_function: str = "gelu"
+ pre_norm: bool = True
+ positional_encoding_type: str = "sincos"
+ use_cls_token: bool = False
+ init_std: float = 0.02
+ share_projection: bool = True
+ scaling: str | bool | None = "std"
+ do_mask_input: bool | None = None
+ mask_type: str = "random"
+ random_mask_ratio: float = 0.5
+ num_forecast_mask_patches: list[int] | tuple[int, ...] | int | None = (2,)
+ channel_consistent_masking: bool | None = False
+ unmasked_channel_indices: list[int] | None = None
+ mask_value: int = 0
+ pooling_type: str | None = "mean"
+ head_dropout: float | int = 0.0
+ prediction_length: int = 24
+ num_targets: int = 1
+ output_range: list | None = None
+ num_parallel_samples: int = 100
+
+
+__all__ = ["PatchTSTConfig"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/patchtst/modeling_patchtst.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/patchtst/modeling_patchtst.py
new file mode 100644
index 0000000000000000000000000000000000000000..1cdd3f381b58ada447343e077ef17a07465338fb
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/patchtst/modeling_patchtst.py
@@ -0,0 +1,1973 @@
+# Copyright 2023 IBM & Hugging Face. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch PatchTST model."""
+
+import math
+from collections.abc import Callable
+from dataclasses import dataclass
+
+import torch
+from torch import nn
+
+from ... import initialization as init
+from ...activations import ACT2CLS
+from ...integrations.deepspeed import is_deepspeed_zero3_enabled
+from ...modeling_flash_attention_utils import FlashAttentionKwargs
+from ...modeling_outputs import BaseModelOutput
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
+from ...processing_utils import Unpack
+from ...time_series_utils import NegativeBinomialOutput, NormalOutput, StudentTOutput
+from ...utils import ModelOutput, TransformersKwargs, auto_docstring, logging
+from .configuration_patchtst import PatchTSTConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+# Copied from transformers.models.bert.modeling_bert.eager_attention_forward
+def eager_attention_forward(
+ module: nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: torch.Tensor | None,
+ scaling: float | None = None,
+ dropout: float = 0.0,
+ **kwargs: Unpack[TransformersKwargs],
+):
+ if scaling is None:
+ scaling = query.size(-1) ** -0.5
+
+ # Take the dot product between "query" and "key" to get the raw attention scores.
+ attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
+
+ if attention_mask is not None:
+ attn_weights = attn_weights + attention_mask
+
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
+
+ attn_output = torch.matmul(attn_weights, value)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+
+ return attn_output, attn_weights
+
+
+# Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2Attention with Wav2Vec2->PatchTST
+class PatchTSTAttention(nn.Module):
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
+
+ def __init__(
+ self,
+ embed_dim: int,
+ num_heads: int,
+ dropout: float = 0.0,
+ is_decoder: bool = False,
+ bias: bool = True,
+ is_causal: bool = False,
+ config: PatchTSTConfig | None = None,
+ ):
+ super().__init__()
+ self.embed_dim = embed_dim
+ self.num_heads = num_heads
+ self.dropout = dropout
+ self.head_dim = embed_dim // num_heads
+ self.config = config
+
+ if (self.head_dim * num_heads) != self.embed_dim:
+ raise ValueError(
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
+ f" and `num_heads`: {num_heads})."
+ )
+ self.scaling = self.head_dim**-0.5
+ self.is_decoder = is_decoder
+ self.is_causal = is_causal
+
+ self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
+ self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ key_value_states: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ output_attentions: bool | None = False,
+ # TODO: we need a refactor so that the different attention modules can get their specific kwargs
+ # ATM, we have mixed things encoder, decoder, and encoder-decoder attn
+ **kwargs: Unpack[FlashAttentionKwargs],
+ ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
+ """Input shape: Batch x Time x Channel"""
+
+ # if key_value_states are provided this layer is used as a cross-attention layer
+ # for the decoder
+ is_cross_attention = key_value_states is not None
+
+ # determine input shapes
+ input_shape = hidden_states.shape[:-1]
+
+ hidden_shape = (*input_shape, -1, self.head_dim)
+
+ # get query proj
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+
+ current_states = key_value_states if is_cross_attention else hidden_states
+ kv_shape = (*current_states.shape[:-1], -1, self.head_dim)
+ key_states = self.k_proj(current_states).view(kv_shape).transpose(1, 2)
+ value_states = self.v_proj(current_states).view(kv_shape).transpose(1, 2)
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_states,
+ key_states,
+ value_states,
+ attention_mask,
+ dropout=0.0 if not self.training else self.dropout,
+ scaling=self.scaling,
+ output_attentions=output_attentions,
+ **kwargs,
+ )
+
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ attn_output = self.out_proj(attn_output)
+
+ return attn_output, attn_weights, None
+
+
+class PatchTSTBatchNorm(nn.Module):
+ """
+ Compute batch normalization over the sequence length (time) dimension.
+ """
+
+ def __init__(self, config: PatchTSTConfig):
+ super().__init__()
+ self.batchnorm = nn.BatchNorm1d(config.d_model, eps=config.norm_eps)
+
+ def forward(self, inputs: torch.Tensor):
+ """
+ Parameters:
+ inputs (`torch.Tensor` of shape `(batch_size, sequence_length, d_model)`):
+ input for Batch norm calculation
+ Returns:
+ `torch.Tensor` of shape `(batch_size, sequence_length, d_model)`
+ """
+ output = inputs.transpose(1, 2) # output: (batch_size, d_model, sequence_length)
+ output = self.batchnorm(output)
+ return output.transpose(1, 2)
+
+
+def random_masking(
+ inputs: torch.Tensor,
+ mask_ratio: float,
+ unmasked_channel_indices: list | None = None,
+ channel_consistent_masking: bool = False,
+ mask_value: int = 0,
+):
+ """random_masking: Mask the input considering the control variables.
+
+ Args:
+ inputs (`torch.Tensor` of shape `(batch_size, num_channels, sequence_length, num_features)`):
+ The input tensor to mask.
+ mask_ratio (`float`):
+ Masking ratio applied to mask the input data during random pretraining. It is the number between 0 and 1.
+ unmasked_channel_indices (list, *optional*):
+ Indices of channels that will not be masked.
+ channel_consistent_masking (bool, *optional*, defaults to `False`):
+ When true, masking will be same across all channels of a timeseries. Otherwise, masking positions will vary
+ across channels.
+ mask_value (int, *optional*, defaults to 0):
+ Define the value of masked patches for pretraining.
+
+ Returns:
+ `tuple(torch.Tensor)`: inputs_mask, masked input, same shape as input Tensor and mask tensor of shape [bs x c x
+ n]
+ """
+ if mask_ratio < 0 or mask_ratio >= 1:
+ raise ValueError(f"Mask ratio {mask_ratio} has to be between 0 and 1.")
+
+ batch_size, num_channels, sequence_length, num_features = inputs.shape
+ device = inputs.device
+
+ len_keep = int(sequence_length * (1 - mask_ratio))
+
+ if channel_consistent_masking:
+ noise = torch.rand(batch_size, 1, sequence_length, device=device) # noise in [0, 1], bs x 1 x L
+ noise = noise.repeat(1, num_channels, 1) # bs x num_channels x time
+ else:
+ # noise in [0, 1], bs x num_channels x L
+ noise = torch.rand(batch_size, num_channels, sequence_length, device=device)
+
+ # mask: [bs x num_channels x num_patch]
+ mask = torch.ones(batch_size, num_channels, sequence_length, device=device)
+ mask[:, :, :len_keep] = 0
+
+ # sort noise for each sample
+ ids_shuffle = torch.argsort(noise, dim=-1) # ascend: small is keep, large is remove
+ ids_restore = torch.argsort(ids_shuffle, dim=-1) # ids_restore: [bs x num_channels x L]
+
+ mask = torch.gather(mask, dim=-1, index=ids_restore)
+ mask = mask.unsqueeze(-1).repeat(1, 1, 1, num_features) # mask: [bs x num_channels x num_patches x patch_length]
+ if unmasked_channel_indices is not None:
+ mask[:, unmasked_channel_indices, :, :] = 0
+
+ inputs_mask = inputs.masked_fill(mask.bool(), mask_value)
+ return inputs_mask, mask[..., 0]
+
+
+def forecast_masking(
+ inputs: torch.Tensor,
+ num_forecast_mask_patches: list | int,
+ unmasked_channel_indices: list | None = None,
+ mask_value: int = 0,
+):
+ """Forecast masking that masks the last K patches where K is from the num_forecast_mask_patches.
+ If num_forecast_mask_patches is a list, samples in the batch will be randomly masked by numbers defined in the list.
+
+ Parameters:
+ inputs (`torch.Tensor`):
+ Input of shape `(bs, num_channels, num_patch, patch_length)`
+ num_forecast_mask_patches (`list`):
+ Number of patches to be masked at the end of each batch sample. e.g. 4 or [3, 5].
+ unmasked_channel_indices (`list`, *optional*):
+ Indices of channels that are not masked.
+ mask_value (`int`, *optional*, defaults to 0):
+ Values in the masked patches will be filled by `mask_value`.
+
+ Returns:
+ `tuple(torch.Tensor)`: inputs_mask, masked input, same shape as inputs Tensor and Mask tensor of shape `(bs,
+ num_channels , num_patch)` or `(bs, tsg1, tsg2, num_channels, num_patch)`
+ """
+
+ if isinstance(num_forecast_mask_patches, int):
+ num_forecast_mask_patches = [num_forecast_mask_patches]
+ forecast_mask_ratios = [1 for _ in num_forecast_mask_patches]
+
+ batch_size, num_channels, sequence_length, num_features = inputs.shape
+ mask = torch.zeros(batch_size, num_channels, sequence_length, device=inputs.device)
+
+ t_list = []
+ total_length = 0
+ total_ratio = sum(forecast_mask_ratios)
+
+ for patch_length, ratio in zip(num_forecast_mask_patches, forecast_mask_ratios):
+ if patch_length <= 0 or patch_length >= sequence_length:
+ raise ValueError(
+ f"num_forecast_mask_patches {patch_length} should be greater than 0 and less than total patches."
+ )
+ temp_len = int(batch_size * ratio / total_ratio)
+ t_list.append([patch_length, ratio, temp_len])
+ total_length += temp_len
+
+ t_list = sorted(t_list, key=lambda x: x[2])
+
+ if total_length < batch_size:
+ t_list[0][2] = t_list[0][2] + (batch_size - total_length)
+ elif total_length > batch_size:
+ t_list[-1][2] = t_list[-1][2] + (total_length - batch_size)
+
+ batch1 = 0
+ for patch_len, _, temp_len in t_list:
+ batch2 = batch1 + temp_len
+ mask[batch1:batch2, :, -patch_len:] = 1
+ batch1 = batch2
+
+ perm = torch.randperm(mask.shape[0])
+ mask = mask[perm]
+
+ mask = mask.unsqueeze(-1).repeat(1, 1, 1, num_features) # mask: [bs x num_channels x num_patch x patch_len]
+ if unmasked_channel_indices is not None:
+ mask[:, unmasked_channel_indices, :, :] = 0
+
+ inputs_mask = inputs.masked_fill(mask.bool(), mask_value)
+ return inputs_mask, mask[..., 0]
+
+
+class PatchTSTPatchify(nn.Module):
+ """
+ A class to patchify the time series sequence into different patches
+
+ Returns:
+ `torch.Tensor` of shape `(batch_size, num_channels, num_patches, patch_length)`
+ """
+
+ def __init__(self, config: PatchTSTConfig):
+ super().__init__()
+
+ self.sequence_length = config.context_length
+ self.patch_length = config.patch_length
+ self.patch_stride = config.patch_stride
+
+ if self.sequence_length <= self.patch_length:
+ raise ValueError(
+ f"Sequence length ({self.sequence_length}) has to be greater than the patch length ({self.patch_length})"
+ )
+
+ # get the number of patches
+ self.num_patches = (max(self.sequence_length, self.patch_length) - self.patch_length) // self.patch_stride + 1
+ new_sequence_length = self.patch_length + self.patch_stride * (self.num_patches - 1)
+ self.sequence_start = self.sequence_length - new_sequence_length
+
+ def forward(self, past_values: torch.Tensor):
+ """
+ Parameters:
+ past_values (`torch.Tensor` of shape `(batch_size, sequence_length, num_channels)`, *required*):
+ Input for patchification
+
+ Returns:
+ `torch.Tensor` of shape `(batch_size, num_channels, num_patches, patch_length)`
+ """
+ sequence_length = past_values.shape[-2]
+ if sequence_length != self.sequence_length:
+ raise ValueError(
+ f"Input sequence length ({sequence_length}) doesn't match model configuration ({self.sequence_length})."
+ )
+ # output: [bs x new_sequence_length x num_channels]
+ output = past_values[:, self.sequence_start :, :]
+ # output: [bs x num_patches x num_input_channels x patch_length]
+ output = output.unfold(dimension=-2, size=self.patch_length, step=self.patch_stride)
+ # output: [bs x num_input_channels x num_patches x patch_length]
+ output = output.transpose(-2, -3).contiguous()
+ return output
+
+
+class PatchTSTMasking(nn.Module):
+ """
+ Class to perform random or forecast masking.
+
+ Parameters:
+ config (`PatchTSTConfig`): model config
+ Returns:
+ x_mask (`torch.Tensor` of shape `(batch_size, num_channels, num_patches, patch_length)`)
+ Masked patched input
+ mask (`torch.Tensor` of shape `(batch_size, num_channels, num_patches)`)
+ Bool tensor indicating True on masked points
+ """
+
+ def __init__(self, config: PatchTSTConfig):
+ super().__init__()
+ self.random_mask_ratio = config.random_mask_ratio
+ self.channel_consistent_masking = config.channel_consistent_masking
+ self.mask_type = config.mask_type
+ self.num_forecast_mask_patches = config.num_forecast_mask_patches
+ self.unmasked_channel_indices = config.unmasked_channel_indices
+ self.mask_value = config.mask_value
+ if self.unmasked_channel_indices is not None:
+ self.unmasked_channel_indices = sorted(self.unmasked_channel_indices)
+
+ def forward(self, patch_input: torch.Tensor):
+ """
+ Parameters:
+ patch_input (`torch.Tensor` of shape `(batch_size, num_channels, num_patches, patch_length)`, *required*):
+ Patch input
+
+ Return:
+ masked_input (`torch.Tensor` of shape `(batch_size, num_channels, num_patches, patch_length)`)
+ Masked patched input
+ mask (`torch.Tensor` of shape `(batch_size, num_channels, num_patches)`)
+ Bool tensor indicating True on masked points
+
+ """
+ if self.mask_type == "random":
+ masked_input, mask = random_masking(
+ inputs=patch_input,
+ mask_ratio=self.random_mask_ratio,
+ unmasked_channel_indices=self.unmasked_channel_indices,
+ channel_consistent_masking=self.channel_consistent_masking,
+ mask_value=self.mask_value,
+ )
+ elif self.mask_type == "forecast":
+ masked_input, mask = forecast_masking(
+ inputs=patch_input,
+ num_forecast_mask_patches=self.num_forecast_mask_patches,
+ unmasked_channel_indices=self.unmasked_channel_indices,
+ mask_value=self.mask_value,
+ )
+ else:
+ raise ValueError(f"Invalid mask type {self.mask_type}.")
+
+ # mask: [bs x num_input_channels x num_patch]
+ mask = mask.bool()
+ return masked_input, mask
+
+
+class PatchTSTEncoderLayer(nn.Module):
+ """
+ PatchTST encoder layer
+ """
+
+ def __init__(self, config: PatchTSTConfig):
+ super().__init__()
+
+ self.channel_attention = config.channel_attention
+
+ self.self_attn = PatchTSTAttention(
+ embed_dim=config.d_model,
+ num_heads=config.num_attention_heads,
+ dropout=config.attention_dropout,
+ config=config,
+ )
+
+ # Add & Norm of the sublayer 1
+ self.dropout_path1 = nn.Dropout(config.path_dropout) if config.path_dropout > 0 else nn.Identity()
+ if config.norm_type == "batchnorm":
+ self.norm_sublayer1 = PatchTSTBatchNorm(config)
+ elif config.norm_type == "layernorm":
+ self.norm_sublayer1 = nn.LayerNorm(config.d_model, eps=config.norm_eps)
+ else:
+ raise ValueError(f"{config.norm_type} is not a supported norm layer type.")
+
+ # Add & Norm of the sublayer 2
+ if self.channel_attention:
+ self.dropout_path2 = nn.Dropout(config.path_dropout) if config.path_dropout > 0 else nn.Identity()
+ if config.norm_type == "batchnorm":
+ self.norm_sublayer2 = PatchTSTBatchNorm(config)
+ elif config.norm_type == "layernorm":
+ self.norm_sublayer2 = nn.LayerNorm(config.d_model, eps=config.norm_eps)
+ else:
+ raise ValueError(f"{config.norm_type} is not a supported norm layer type.")
+
+ # Position-wise Feed-Forward
+ self.ff = nn.Sequential(
+ nn.Linear(config.d_model, config.ffn_dim, bias=config.bias),
+ ACT2CLS[config.activation_function](),
+ nn.Dropout(config.ff_dropout) if config.ff_dropout > 0 else nn.Identity(),
+ nn.Linear(config.ffn_dim, config.d_model, bias=config.bias),
+ )
+
+ # Add & Norm of sublayer 3
+ self.dropout_path3 = nn.Dropout(config.path_dropout) if config.path_dropout > 0 else nn.Identity()
+ if config.norm_type == "batchnorm":
+ self.norm_sublayer3 = PatchTSTBatchNorm(config)
+ elif config.norm_type == "layernorm":
+ self.norm_sublayer3 = nn.LayerNorm(config.d_model, eps=config.norm_eps)
+ else:
+ raise ValueError(f"{config.norm_type} is not a supported norm layer type.")
+
+ self.pre_norm = config.pre_norm
+
+ def forward(self, hidden_state: torch.Tensor, output_attentions: bool | None = None):
+ """
+ Parameters:
+ hidden_state (`torch.Tensor` of shape `(batch_size, num_channels, sequence_length, d_model)`, *required*):
+ Past values of the time series
+ output_attentions (`bool`, *optional*):
+ Whether or not to return the output attention of all layers
+ Return:
+ `torch.Tensor` of shape `(batch_size, num_channels, sequence_length, d_model)`
+
+ """
+ batch_size, num_input_channels, sequence_length, d_model = hidden_state.shape
+
+ # First sublayer: attention across time
+ # hidden_states: [(bs*num_channels) x sequence_length x d_model]
+ hidden_state = hidden_state.view(batch_size * num_input_channels, sequence_length, d_model)
+
+ if self.pre_norm:
+ ## Norm and Multi-Head attention and Add residual connection
+ attn_output, attn_weights, _ = self.self_attn(
+ hidden_states=self.norm_sublayer1(hidden_state), output_attentions=output_attentions
+ )
+ # Add: residual connection with residual dropout
+ hidden_state = hidden_state + self.dropout_path1(attn_output)
+ else:
+ ## Multi-Head attention and Add residual connection and Norm - Standard Transformer from BERT
+ attn_output, attn_weights, _ = self.self_attn(
+ hidden_states=hidden_state, output_attentions=output_attentions
+ )
+ # hidden_states: [(bs*num_channels) x sequence_length x d_model]
+ hidden_state = self.norm_sublayer1(hidden_state + self.dropout_path1(attn_output))
+
+ # hidden_state: [bs x num_channels x sequence_length x d_model]
+ hidden_state = hidden_state.reshape(batch_size, num_input_channels, sequence_length, d_model)
+
+ # second sublayer: attention across variable at any given time
+ if self.channel_attention:
+ # hidden_state: [bs x sequence_length x num_channels x d_model]
+ hidden_state = hidden_state.transpose(2, 1).contiguous()
+ # hidden_state: [(bs*sequence_length) x num_channels x d_model]
+ hidden_state = hidden_state.view(batch_size * sequence_length, num_input_channels, d_model)
+ if self.pre_norm:
+ ## Norm and Multi-Head attention and Add residual connection
+ attn_output, channel_attn_weights, _ = self.self_attn(
+ hidden_states=self.norm_sublayer2(hidden_state), output_attentions=output_attentions
+ )
+ # Add: residual connection with residual dropout
+ hidden_state = hidden_state + self.dropout_path2(attn_output)
+ else:
+ ## Multi-Head attention and Add residual connection and Norm
+ attn_output, channel_attn_weights, _ = self.self_attn(
+ hidden_states=hidden_state, output_attentions=output_attentions
+ )
+ # hidden_states: [(bs*sequence_length) x num_channels x d_model]
+ hidden_state = self.norm_sublayer2(hidden_state + self.dropout_path2(attn_output))
+
+ # Reshape hidden state
+ # hidden_state: [bs x sequence_length x num_channels x d_model]
+ hidden_state = hidden_state.reshape(batch_size, sequence_length, num_input_channels, d_model)
+ # hidden_state: [bs x num_channels x sequence_length x d_model]
+ hidden_state = hidden_state.transpose(1, 2).contiguous()
+
+ # Third sublayer: mixing across hidden
+ # hidden_state: [(batch_size*num_channels) x sequence_length x d_model]
+ hidden_state = hidden_state.view(batch_size * num_input_channels, sequence_length, d_model)
+ if self.pre_norm:
+ ## Norm and Position-wise Feed-Forward and Add residual connection
+ # Add: residual connection with residual dropout
+ hidden_state = hidden_state + self.dropout_path3(self.ff(self.norm_sublayer3(hidden_state)))
+ else:
+ ## Position-wise Feed-Forward and Add residual connection and Norm
+ # Add: residual connection with residual dropout
+ hidden_state = self.norm_sublayer3(hidden_state + self.dropout_path3(self.ff(hidden_state)))
+
+ # [bs x num_channels x sequence_length x d_model]
+ hidden_state = hidden_state.reshape(batch_size, num_input_channels, sequence_length, d_model)
+
+ outputs = (hidden_state,)
+ if output_attentions:
+ outputs += (attn_weights, channel_attn_weights) if self.channel_attention else (attn_weights,)
+
+ return outputs
+
+
+@auto_docstring
+class PatchTSTPreTrainedModel(PreTrainedModel):
+ config: PatchTSTConfig
+ base_model_prefix = "model"
+ main_input_name = "past_values"
+ input_modalities = ("time",)
+ supports_gradient_checkpointing = False
+ _supports_flash_attn = True
+ _supports_sdpa = True
+ _supports_flex_attn = True
+
+ @torch.no_grad()
+ def _init_weights(self, module: nn.Module):
+ """
+ Initialize weights
+ """
+ if isinstance(module, PatchTSTPositionalEncoding):
+ # get the number of patches
+ num_patches = (
+ max(self.config.context_length, self.config.patch_length) - self.config.patch_length
+ ) // self.config.patch_stride + 1
+ # initialize cls_token
+ if self.config.use_cls_token:
+ init.normal_(module.cls_token, std=0.02)
+ num_patches += 1
+ # initialize positional encoding
+ position_enc = module._init_pe(self.config, num_patches)
+ if is_deepspeed_zero3_enabled():
+ import deepspeed
+
+ with deepspeed.zero.GatheredParameters(module.position_enc, modifier_rank=None):
+ if module.position_enc.numel() > 0:
+ init.copy_(module.position_enc, position_enc)
+ else:
+ init.copy_(module.position_enc, position_enc)
+ elif isinstance(module, (nn.LayerNorm, nn.BatchNorm1d)):
+ init.zeros_(module.bias)
+ init.ones_(module.weight)
+ if getattr(module, "running_mean", None) is not None:
+ init.zeros_(module.running_mean)
+ init.ones_(module.running_var)
+ init.zeros_(module.num_batches_tracked)
+ elif isinstance(module, nn.Linear):
+ init.normal_(module.weight, mean=0.0, std=self.config.init_std)
+ if module.bias is not None:
+ init.zeros_(module.bias)
+
+ def _set_gradient_checkpointing(self, module, value=False):
+ if isinstance(module, (PatchTSTEncoder)):
+ module.gradient_checkpointing = value
+
+
+class PatchTSTEmbedding(nn.Module):
+ def __init__(self, config: PatchTSTConfig):
+ super().__init__()
+ self.num_input_channels = config.num_input_channels
+ self.share_embedding = config.share_embedding
+ # Input encoding: projection of feature vectors onto a d-dim vector space
+ if self.share_embedding:
+ self.input_embedding = nn.Linear(config.patch_length, config.d_model)
+ else:
+ self.input_embedding = nn.ModuleList()
+ for _ in range(config.num_input_channels):
+ self.input_embedding.append(nn.Linear(config.patch_length, config.d_model))
+
+ def forward(self, patch_input: torch.Tensor):
+ """
+ Parameters:
+ patch_input (`torch.Tensor` of shape `(batch_size, num_channels, num_patches, patch_length)`, *required*):
+ Patch input for embedding
+ return:
+ `torch.Tensor` of shape `(batch_size, num_channels, num_patches, d_model)`
+ """
+ # Input encoding
+ num_input_channels = patch_input.shape[1]
+ if num_input_channels != self.num_input_channels:
+ raise ValueError(
+ f"The defined number of input channels ({self.num_input_channels}) in the config "
+ f"has to be the same as the number of channels in the batch input ({num_input_channels})"
+ )
+ if self.share_embedding:
+ embeddings = self.input_embedding(patch_input) # x: [bs x num_channels x num_patches x d_model]
+ else:
+ embeddings = [self.input_embedding[i](patch_input[:, i, :, :]) for i in range(num_input_channels)]
+ embeddings = torch.stack(embeddings, dim=1)
+ return embeddings
+
+
+class PatchTSTPositionalEncoding(nn.Module):
+ """
+ Class for positional encoding
+ """
+
+ def __init__(self, config: PatchTSTConfig, num_patches: int):
+ super().__init__()
+ self.use_cls_token = config.use_cls_token
+ self.num_input_channels = config.num_input_channels
+ if config.use_cls_token:
+ # cls_token: [1 x num_input_channels x 1 x d_model]
+ self.cls_token = nn.Parameter(torch.zeros(1, 1, 1, config.d_model))
+ num_patches += 1
+ # positional encoding: [num_patches x d_model]
+ self.position_enc = self._init_pe(config, num_patches)
+ # Positional dropout
+ self.positional_dropout = (
+ nn.Dropout(config.positional_dropout) if config.positional_dropout > 0 else nn.Identity()
+ )
+
+ @staticmethod
+ def _init_pe(config: PatchTSTConfig, num_patches: int) -> nn.Parameter:
+ # Positional encoding
+ if config.positional_encoding_type == "random":
+ position_enc = nn.Parameter(torch.randn(num_patches, config.d_model), requires_grad=True)
+ elif config.positional_encoding_type == "sincos":
+ position_enc = torch.zeros(num_patches, config.d_model)
+ position = torch.arange(0, num_patches).unsqueeze(1)
+ div_term = torch.exp(torch.arange(0, config.d_model, 2) * -(math.log(10000.0) / config.d_model))
+ position_enc[:, 0::2] = torch.sin(position * div_term)
+ position_enc[:, 1::2] = torch.cos(position * div_term)
+ position_enc = position_enc - position_enc.mean()
+ position_enc = position_enc / (position_enc.std() * 10)
+ position_enc = nn.Parameter(position_enc, requires_grad=False)
+ else:
+ raise ValueError(
+ f"{config.positional_encoding_type} is not a valid positional encoder. Available types are 'random' and 'sincos'."
+ )
+ return position_enc
+
+ def forward(self, patch_input: torch.Tensor):
+ if self.use_cls_token:
+ # patch_input: [bs x num_channels x num_patches x d_model]
+ patch_input = self.positional_dropout(patch_input + self.position_enc[1:, :])
+ # append cls token where cls_token: [1 x num_channels x 1 x d_model]
+ cls_token = self.cls_token + self.position_enc[:1, :]
+ # get the same copy of cls_token for all the samples in batch: [bs x num_channels x 1 x d_model]
+ cls_tokens = cls_token.expand(patch_input.shape[0], self.num_input_channels, -1, -1)
+ # hidden_state: [bs x num_channels x (num_patches+1) x d_model]
+ hidden_state = torch.cat((cls_tokens, patch_input), dim=2)
+ else:
+ # hidden_state: [bs x num_channels x num_patches x d_model]
+ hidden_state = self.positional_dropout(patch_input + self.position_enc)
+ return hidden_state
+
+
+class PatchTSTEncoder(PatchTSTPreTrainedModel):
+ """
+ PatchTST Encoder
+ """
+
+ def __init__(self, config: PatchTSTConfig, num_patches: int):
+ super().__init__(config)
+ self.gradient_checkpointing = False
+
+ # Input embedding: projection of feature vectors onto a d-dim vector space
+ self.embedder = PatchTSTEmbedding(config)
+ # Positional encoding
+ self.positional_encoder = PatchTSTPositionalEncoding(config, num_patches)
+ # Encoder
+ self.layers = nn.ModuleList([PatchTSTEncoderLayer(config) for i in range(config.num_hidden_layers)])
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def forward(
+ self,
+ patch_input: torch.Tensor,
+ output_hidden_states: bool | None = None,
+ output_attentions: bool | None = None,
+ **kwargs,
+ ) -> BaseModelOutput:
+ """
+ Parameters:
+ patch_input (`torch.Tensor` of shape `(batch_size, num_channels, num_patches, patch_length)`, *required*):
+ Past values of the time series
+ output_hidden_states (bool, optional): Indicates if hidden states should be outputted.
+ output_attentions (bool, optional): Indicates if attentions should be outputted.
+
+ return:
+ `BaseModelOutput`
+ """
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+
+ # Input embedding
+ patch_input = self.embedder(patch_input)
+ # Positional encoding
+ hidden_state = self.positional_encoder(patch_input)
+
+ encoder_states = () if output_hidden_states else None
+ all_attentions = () if output_attentions else None
+ for encoder_layer in self.layers:
+ if output_hidden_states:
+ encoder_states = encoder_states + (hidden_state,)
+
+ layer_outputs = encoder_layer(hidden_state=hidden_state, output_attentions=output_attentions)
+ # get hidden state. hidden_state shape is [bs x num_channels x num_patches x d_model]
+ # or [bs x num_channels x (num_patches+1) x d_model] if use cls_token
+ hidden_state = layer_outputs[0]
+ # append attention matrix at each layer
+ if output_attentions:
+ all_attentions = all_attentions + (layer_outputs[1],)
+ # return past_values, hidden_states
+ return BaseModelOutput(last_hidden_state=hidden_state, hidden_states=encoder_states, attentions=all_attentions)
+
+
+@auto_docstring(
+ custom_intro="""
+ Base class for model's outputs, with potential hidden states.
+ """
+)
+@dataclass
+class PatchTSTModelOutput(ModelOutput):
+ r"""
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, num_channels, num_patches, patch_length)`):
+ Sequence of hidden-states at the output of the last layer of the model.
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
+ one for the output of each layer) of shape `(batch_size, num_channels, height, width)`. Hidden-states of
+ the model at the output of each layer plus the optional initial embedding outputs.
+ mask (`torch.FloatTensor` of shape `(batch_size, num_channels, num_patches)`, *optional*):
+ Bool masked tensor indicating which patches are masked
+ loc (`torch.FloatTensor` of shape `(batch_size, 1, num_channels)`, *optional*):
+ Mean of the input data (batch_size, sequence_length, num_channels) over the sequence_length
+ scale (`torch.FloatTensor` of shape `(batch_size, 1, num_channels)`, *optional*):
+ Std of the input data (batch_size, sequence_length, num_channels) over the sequence_length
+ patch_input (`torch.FloatTensor` of shape `(batch_size, num_channels, num_patches, patch_length)`):
+ Patched input to the Transformer
+ """
+
+ last_hidden_state: torch.FloatTensor | None = None
+ hidden_states: tuple[torch.FloatTensor] | None = None
+ attentions: tuple[torch.FloatTensor] | None = None
+ mask: torch.FloatTensor | None = None
+ loc: torch.FloatTensor | None = None
+ scale: torch.FloatTensor | None = None
+ patch_input: torch.FloatTensor | None = None
+
+
+@auto_docstring(
+ custom_intro="""
+ Output type of [`PatchTSTForPretraining`].
+ """
+)
+@dataclass
+class PatchTSTForPretrainingOutput(ModelOutput):
+ r"""
+ loss (*optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
+ MSE loss.
+ prediction_output (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
+ Prediction outputs of the time series modeling heads.
+ """
+
+ loss: torch.FloatTensor | None = None
+ prediction_output: torch.FloatTensor | None = None
+ hidden_states: tuple[torch.FloatTensor] | None = None
+ attentions: tuple[torch.FloatTensor] | None = None
+
+
+@auto_docstring(
+ custom_intro="""
+ Output type of [`PatchTSTForRegression`].
+ """
+)
+@dataclass
+class PatchTSTForRegressionOutput(ModelOutput):
+ r"""
+ loss (*optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
+ MSE loss.
+ regression_outputs (`torch.FloatTensor` of shape `(batch_size, num_targets)`):
+ Regression outputs of the time series modeling heads.
+ """
+
+ loss: torch.FloatTensor | None = None
+ regression_outputs: torch.FloatTensor | None = None
+ hidden_states: tuple[torch.FloatTensor] | None = None
+ attentions: tuple[torch.FloatTensor] | None = None
+
+
+@auto_docstring(
+ custom_intro="""
+ Output type of [`PatchTSTForPrediction`].
+ """
+)
+@dataclass
+class PatchTSTForPredictionOutput(ModelOutput):
+ r"""
+ loss (*optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
+ MSE loss.
+ prediction_outputs (`torch.FloatTensor` of shape `(batch_size, prediction_length, -1)`):
+ Prediction outputs of the time series modeling heads.
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
+ sequence_length)`.
+
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
+ heads.
+ loc: (`torch.FloatTensor` of shape `(batch_size, 1, num_channels)`, *optional*)
+ Mean of the input data (batch_size, sequence_length, num_channels) over the sequence_length
+ scale: (`torch.FloatTensor` of shape `(batch_size, 1, num_channels)`, *optional*)
+ Std of the input data (batch_size, sequence_length, num_channels) over the sequence_length
+ """
+
+ loss: torch.FloatTensor | None = None
+ prediction_outputs: torch.FloatTensor | None = None
+ hidden_states: tuple[torch.FloatTensor] | None = None
+ attentions: tuple[torch.FloatTensor] | None = None
+ loc: torch.FloatTensor | None = None
+ scale: torch.FloatTensor | None = None
+
+
+@auto_docstring(
+ custom_intro="""
+ Output type of [`PatchTSTForClassification`].
+ """
+)
+@dataclass
+class PatchTSTForClassificationOutput(ModelOutput):
+ r"""
+ loss (*optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
+ Total loss as the sum of the masked language modeling loss and the next sequence prediction
+ (classification) loss.
+ prediction_logits (`torch.FloatTensor` of shape `(batch_size, num_targets)`):
+ Prediction scores of the PatchTST modeling head (scores before SoftMax).
+ """
+
+ loss: torch.FloatTensor | None = None
+ prediction_logits: torch.FloatTensor | None = None
+ hidden_states: tuple[torch.FloatTensor] | None = None
+ attentions: tuple[torch.FloatTensor] | None = None
+
+
+@auto_docstring(
+ custom_intro="""
+ Base class for time series model's predictions outputs that contains the sampled values from the chosen
+ distribution.
+ """
+)
+@dataclass
+class SamplePatchTSTOutput(ModelOutput):
+ r"""
+ sequences (`torch.FloatTensor` of shape `(batch_size, num_samples, prediction_length, num_targets)`):
+ Sampled values from the chosen distribution.
+ """
+
+ sequences: torch.FloatTensor | None = None
+
+
+# Copied from transformers.models.time_series_transformer.modeling_time_series_transformer.nll
+def nll(input: torch.distributions.Distribution, target: torch.Tensor) -> torch.Tensor:
+ """
+ Computes the negative log likelihood loss from input distribution with respect to target.
+ """
+ return -input.log_prob(target)
+
+
+# Copied from transformers.models.time_series_transformer.modeling_time_series_transformer.weighted_average
+def weighted_average(input_tensor: torch.Tensor, weights: torch.Tensor | None = None, dim=None) -> torch.Tensor:
+ """
+ Computes the weighted average of a given tensor across a given `dim`, masking values associated with weight zero,
+ meaning instead of `nan * 0 = nan` you will get `0 * 0 = 0`.
+
+ Args:
+ input_tensor (`torch.FloatTensor`):
+ Input tensor, of which the average must be computed.
+ weights (`torch.FloatTensor`, *optional*):
+ Weights tensor, of the same shape as `input_tensor`.
+ dim (`int`, *optional*):
+ The dim along which to average `input_tensor`.
+
+ Returns:
+ `torch.FloatTensor`: The tensor with values averaged along the specified `dim`.
+ """
+ if weights is not None:
+ weighted_tensor = torch.where(weights != 0, input_tensor * weights, torch.zeros_like(input_tensor))
+ sum_weights = torch.clamp(weights.sum(dim=dim) if dim else weights.sum(), min=1.0)
+ return (weighted_tensor.sum(dim=dim) if dim else weighted_tensor.sum()) / sum_weights
+ else:
+ return input_tensor.mean(dim=dim)
+
+
+# Copied from transformers.models.time_series_transformer.modeling_time_series_transformer.TimeSeriesStdScaler with TimeSeriesTransformer->PatchTST,TimeSeries->PatchTST
+class PatchTSTStdScaler(nn.Module):
+ """
+ Standardize features by calculating the mean and scaling along the first dimension, and then normalizes it by
+ subtracting from the mean and dividing by the standard deviation.
+ """
+
+ def __init__(self, config: PatchTSTConfig):
+ super().__init__()
+ self.dim = config.scaling_dim if hasattr(config, "scaling_dim") else 1
+ self.keepdim = config.keepdim if hasattr(config, "keepdim") else True
+ self.minimum_scale = config.minimum_scale if hasattr(config, "minimum_scale") else 1e-5
+
+ def forward(
+ self, data: torch.Tensor, observed_indicator: torch.Tensor
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ """
+ Parameters:
+ data (`torch.Tensor` of shape `(batch_size, sequence_length, num_input_channels)`):
+ input for Batch norm calculation
+ observed_indicator (`torch.BoolTensor` of shape `(batch_size, sequence_length, num_input_channels)`):
+ Calculating the scale on the observed indicator.
+ Returns:
+ tuple of `torch.Tensor` of shapes
+ (`(batch_size, sequence_length, num_input_channels)`,`(batch_size, 1, num_input_channels)`,
+ `(batch_size, 1, num_input_channels)`)
+ """
+ denominator = observed_indicator.sum(self.dim, keepdim=self.keepdim)
+ denominator = denominator.clamp_min(1.0)
+ loc = (data * observed_indicator).sum(self.dim, keepdim=self.keepdim) / denominator
+
+ variance = (((data - loc) * observed_indicator) ** 2).sum(self.dim, keepdim=self.keepdim) / denominator
+ scale = torch.sqrt(variance + self.minimum_scale)
+ return (data - loc) / scale, loc, scale
+
+
+# Copied from transformers.models.time_series_transformer.modeling_time_series_transformer.TimeSeriesMeanScaler with TimeSeriesTransformer->PatchTST,TimeSeries->PatchTST
+class PatchTSTMeanScaler(nn.Module):
+ """
+ Computes a scaling factor as the weighted average absolute value along the first dimension, and scales the data
+ accordingly.
+ """
+
+ def __init__(self, config: PatchTSTConfig):
+ super().__init__()
+ self.dim = config.scaling_dim if hasattr(config, "scaling_dim") else 1
+ self.keepdim = config.keepdim if hasattr(config, "keepdim") else True
+ self.minimum_scale = config.minimum_scale if hasattr(config, "minimum_scale") else 1e-10
+ self.default_scale = config.default_scale if hasattr(config, "default_scale") else None
+
+ def forward(
+ self, data: torch.Tensor, observed_indicator: torch.Tensor
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ """
+ Parameters:
+ data (`torch.Tensor` of shape `(batch_size, sequence_length, num_input_channels)`):
+ input for Batch norm calculation
+ observed_indicator (`torch.BoolTensor` of shape `(batch_size, sequence_length, num_input_channels)`):
+ Calculating the scale on the observed indicator.
+ Returns:
+ tuple of `torch.Tensor` of shapes
+ (`(batch_size, sequence_length, num_input_channels)`,`(batch_size, 1, num_input_channels)`,
+ `(batch_size, 1, num_input_channels)`)
+ """
+ ts_sum = (data * observed_indicator).abs().sum(self.dim, keepdim=True)
+ num_observed = observed_indicator.sum(self.dim, keepdim=True)
+
+ scale = ts_sum / torch.clamp(num_observed, min=1)
+
+ # If `default_scale` is provided, we use it, otherwise we use the scale
+ # of the batch.
+ if self.default_scale is None:
+ batch_sum = ts_sum.sum(dim=0)
+ batch_observations = torch.clamp(num_observed.sum(0), min=1)
+ default_scale = torch.squeeze(batch_sum / batch_observations)
+ else:
+ default_scale = self.default_scale * torch.ones_like(scale)
+
+ # apply default scale where there are no observations
+ scale = torch.where(num_observed > 0, scale, default_scale)
+
+ # ensure the scale is at least `self.minimum_scale`
+ scale = torch.clamp(scale, min=self.minimum_scale)
+ scaled_data = data / scale
+
+ if not self.keepdim:
+ scale = scale.squeeze(dim=self.dim)
+
+ return scaled_data, torch.zeros_like(scale), scale
+
+
+# Copied from transformers.models.time_series_transformer.modeling_time_series_transformer.TimeSeriesNOPScaler with TimeSeriesTransformer->PatchTST,TimeSeries->PatchTST
+class PatchTSTNOPScaler(nn.Module):
+ """
+ Assigns a scaling factor equal to 1 along the first dimension, and therefore applies no scaling to the input data.
+ """
+
+ def __init__(self, config: PatchTSTConfig):
+ super().__init__()
+ self.dim = config.scaling_dim if hasattr(config, "scaling_dim") else 1
+ self.keepdim = config.keepdim if hasattr(config, "keepdim") else True
+
+ def forward(
+ self, data: torch.Tensor, observed_indicator: torch.Tensor | None = None
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ """
+ Parameters:
+ data (`torch.Tensor` of shape `(batch_size, sequence_length, num_input_channels)`):
+ input for Batch norm calculation
+ Returns:
+ tuple of `torch.Tensor` of shapes
+ (`(batch_size, sequence_length, num_input_channels)`,`(batch_size, 1, num_input_channels)`,
+ `(batch_size, 1, num_input_channels)`)
+ """
+ scale = torch.ones_like(data, requires_grad=False).mean(dim=self.dim, keepdim=self.keepdim)
+ loc = torch.zeros_like(data, requires_grad=False).mean(dim=self.dim, keepdim=self.keepdim)
+ return data, loc, scale
+
+
+class PatchTSTScaler(nn.Module):
+ def __init__(self, config: PatchTSTConfig):
+ super().__init__()
+ if config.scaling == "mean" or config.scaling is True:
+ self.scaler = PatchTSTMeanScaler(config)
+ elif config.scaling == "std":
+ self.scaler = PatchTSTStdScaler(config)
+ else:
+ self.scaler = PatchTSTNOPScaler(config)
+
+ def forward(
+ self, data: torch.Tensor, observed_indicator: torch.Tensor
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ """
+ Parameters:
+ data (`torch.Tensor` of shape `(batch_size, sequence_length, num_input_channels)`):
+ Input for scaler calculation
+ observed_indicator (`torch.BoolTensor` of shape `(batch_size, sequence_length, num_input_channels)`):
+ Calculating the scale on the observed indicator.
+ Returns:
+ tuple of `torch.Tensor` of shapes
+ (`(batch_size, sequence_length, num_input_channels)`,`(batch_size, 1, num_input_channels)`,
+ `(batch_size, 1, um_input_channels)`)
+ """
+ data, loc, scale = self.scaler(data, observed_indicator)
+ return data, loc, scale
+
+
+@auto_docstring
+class PatchTSTModel(PatchTSTPreTrainedModel):
+ def __init__(self, config: PatchTSTConfig):
+ super().__init__(config)
+
+ self.scaler = PatchTSTScaler(config)
+ self.patchifier = PatchTSTPatchify(config)
+ self.do_mask_input = config.do_mask_input
+ # get num_patches information from PatchTSTPatchify
+ num_patches = self.patchifier.num_patches
+
+ if self.do_mask_input:
+ self.masking = PatchTSTMasking(config)
+ else:
+ self.masking = nn.Identity()
+ self.encoder = PatchTSTEncoder(config, num_patches=num_patches)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def forward(
+ self,
+ past_values: torch.Tensor,
+ past_observed_mask: torch.Tensor | None = None,
+ future_values: torch.Tensor | None = None,
+ output_hidden_states: bool | None = None,
+ output_attentions: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple | PatchTSTModelOutput:
+ r"""
+ Parameters:
+ past_values (`torch.Tensor` of shape `(bs, sequence_length, num_input_channels)`, *required*):
+ Input sequence to the model
+ past_observed_mask (`torch.BoolTensor` of shape `(batch_size, sequence_length, num_input_channels)`, *optional*):
+ Boolean mask to indicate which `past_values` were observed and which were missing. Mask values selected
+ in `[0, 1]`:
+
+ - 1 for values that are **observed**,
+ - 0 for values that are **missing** (i.e. NaNs that were replaced by zeros).
+ future_values (`torch.BoolTensor` of shape `(batch_size, prediction_length, num_input_channels)`, *optional*):
+ Future target values associated with the `past_values`
+ output_hidden_states (`bool`, *optional*):
+ Whether or not to return the hidden states of all layers
+ output_attentions (`bool`, *optional*):
+ Whether or not to return the output attention of all layers
+ return_dict (`bool`, *optional*):
+ Whether or not to return a `ModelOutput` instead of a plain tuple.
+
+ Returns:
+ `PatchTSTModelOutput` or tuple of `torch.Tensor` (if `return_dict`=False or `config.return_dict`=False)
+
+ Examples:
+
+ ```python
+ >>> from huggingface_hub import hf_hub_download
+ >>> import torch
+ >>> from transformers import PatchTSTModel
+
+ >>> file = hf_hub_download(
+ ... repo_id="hf-internal-testing/etth1-hourly-batch", filename="train-batch.pt", repo_type="dataset"
+ ... )
+ >>> batch = torch.load(file)
+
+ >>> model = PatchTSTModel.from_pretrained("namctin/patchtst_etth1_pretrain")
+
+ >>> # during training, one provides both past and future values
+ >>> outputs = model(
+ ... past_values=batch["past_values"],
+ ... future_values=batch["future_values"],
+ ... )
+
+ >>> last_hidden_state = outputs.last_hidden_state
+ ```"""
+
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+
+ if past_observed_mask is None:
+ past_observed_mask = torch.ones_like(past_values)
+
+ # x: tensor [bs x sequence_length x num_input_channels]
+ scaled_past_values, loc, scale = self.scaler(past_values, past_observed_mask)
+
+ # patched_values: [bs x num_input_channels x num_patches x patch_length] for pretrain
+ patched_values = self.patchifier(scaled_past_values)
+ if self.do_mask_input:
+ masked_values, mask = self.masking(patched_values)
+ else:
+ masked_values, mask = self.masking(patched_values), None
+
+ encoder_output = self.encoder(
+ patch_input=masked_values, output_hidden_states=output_hidden_states, output_attentions=output_attentions
+ )
+
+ if not return_dict:
+ outputs = (encoder_output.last_hidden_state, encoder_output.hidden_states, encoder_output.attentions)
+ outputs = outputs + (mask, loc, scale, patched_values)
+ return tuple(v for v in outputs if v is not None)
+
+ return PatchTSTModelOutput(
+ last_hidden_state=encoder_output.last_hidden_state,
+ hidden_states=encoder_output.hidden_states,
+ attentions=encoder_output.attentions,
+ mask=mask,
+ loc=loc,
+ scale=scale,
+ patch_input=patched_values,
+ )
+
+
+class PatchTSTMaskPretrainHead(nn.Module):
+ """
+ Pretraining head for mask modelling
+ """
+
+ def __init__(self, config: PatchTSTConfig):
+ super().__init__()
+ self.dropout = nn.Dropout(config.head_dropout) if config.head_dropout > 0 else nn.Identity()
+ self.linear = nn.Linear(config.d_model, config.patch_length)
+ self.use_cls_token = config.use_cls_token
+
+ def forward(self, embedding: torch.Tensor) -> torch.Tensor:
+ """
+ Parameters:
+ embedding (`torch.Tensor` of shape `(bs, num_channels, num_patches, d_model)` or
+ `(bs, num_channels, num_patches+1, d_model)` if `cls_token` is set to True, *required*):
+ Embedding from the model
+ Returns:
+ `torch.Tensor` of shape `(bs, num_channels, num_patches, d_model)` or
+ `(bs, num_channels, num_patches+1, d_model)` if `cls_token` is set to True
+
+ """
+ embedding = self.linear(self.dropout(embedding)) # [bs x num_channels x num_patches x patch_length]
+ if self.use_cls_token:
+ embedding = embedding[:, :, 1:, :] # remove the first cls token
+ return embedding
+
+
+@auto_docstring(
+ custom_intro="""
+ The PatchTST for pretrain model.
+ """
+)
+class PatchTSTForPretraining(PatchTSTPreTrainedModel):
+ def __init__(self, config: PatchTSTConfig):
+ super().__init__(config)
+
+ config.do_mask_input = True
+ self.model = PatchTSTModel(config=config)
+ self.head = PatchTSTMaskPretrainHead(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def forward(
+ self,
+ past_values: torch.Tensor,
+ past_observed_mask: torch.Tensor | None = None,
+ output_hidden_states: bool | None = None,
+ output_attentions: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple | PatchTSTForPretrainingOutput:
+ r"""
+ Parameters:
+ past_values (`torch.Tensor` of shape `(bs, sequence_length, num_input_channels)`, *required*):
+ Input sequence to the model
+ past_observed_mask (`torch.BoolTensor` of shape `(batch_size, sequence_length, num_input_channels)`, *optional*):
+ Boolean mask to indicate which `past_values` were observed and which were missing. Mask values selected
+ in `[0, 1]`:
+
+ - 1 for values that are **observed**,
+ - 0 for values that are **missing** (i.e. NaNs that were replaced by zeros).
+ output_hidden_states (`bool`, *optional*):
+ Whether or not to return the hidden states of all layers
+ output_attentions (`bool`, *optional*):
+ Whether or not to return the output attention of all layers
+ return_dict (`bool`, *optional*): Whether or not to return a `ModelOutput` instead of a plain tuple.
+
+ Returns:
+ `PatchTSTForPretrainingOutput` or tuple of `torch.Tensor` (if `return_dict`=False or
+ `config.return_dict`=False)
+
+ Examples:
+
+ ```python
+ >>> from huggingface_hub import hf_hub_download
+ >>> import torch
+ >>> from transformers import PatchTSTConfig, PatchTSTForPretraining
+
+ >>> file = hf_hub_download(
+ ... repo_id="hf-internal-testing/etth1-hourly-batch", filename="train-batch.pt", repo_type="dataset"
+ ... )
+ >>> batch = torch.load(file)
+
+ >>> # Config for random mask pretraining
+ >>> config = PatchTSTConfig(
+ ... num_input_channels=7,
+ ... context_length=512,
+ ... patch_length=12,
+ ... stride=12,
+ ... mask_type='random',
+ ... random_mask_ratio=0.4,
+ ... use_cls_token=True,
+ ... )
+ >>> # Config for forecast mask pretraining
+ >>> config = PatchTSTConfig(
+ ... num_input_channels=7,
+ ... context_length=512,
+ ... patch_length=12,
+ ... stride=12,
+ ... mask_type='forecast',
+ ... num_forecast_mask_patches=5,
+ ... use_cls_token=True,
+ ... )
+ >>> model = PatchTSTForPretraining(config)
+
+ >>> # during training, one provides both past and future values
+ >>> outputs = model(past_values=batch["past_values"])
+
+ >>> loss = outputs.loss
+ >>> loss.backward()
+ ```"""
+
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ # past_values: [bs x num_channels x num_patches x d_model] or
+ # [bs x num_channels x (num_patches+1) x d_model] if use cls_token
+ model_output = self.model(
+ past_values=past_values,
+ past_observed_mask=past_observed_mask,
+ output_hidden_states=output_hidden_states,
+ output_attentions=output_attentions,
+ return_dict=True,
+ )
+
+ # last_hidden_state: [bs x num_channels x num_patches x patch_length] or
+ # [bs x num_channels x (num_patches+1) x patch_length] if use cls_token
+ x_hat = self.head(model_output.last_hidden_state)
+
+ # calculate masked_loss
+ loss = nn.MSELoss(reduction="none")
+ loss_val = loss(x_hat, model_output.patch_input)
+ masked_loss = (loss_val.mean(dim=-1) * model_output.mask).sum() / (model_output.mask.sum() + 1e-10)
+
+ encoder_states = model_output.hidden_states
+ if not return_dict:
+ outputs = (x_hat,) + model_output[1:-4]
+ outputs = (masked_loss,) + outputs if masked_loss is not None else outputs
+ return outputs
+ return PatchTSTForPretrainingOutput(
+ loss=masked_loss, prediction_output=x_hat, hidden_states=encoder_states, attentions=model_output.attentions
+ )
+
+
+class PatchTSTClassificationHead(nn.Module):
+ def __init__(self, config: PatchTSTConfig):
+ super().__init__()
+ self.use_cls_token = config.use_cls_token
+ self.pooling_type = config.pooling_type
+ self.flatten = nn.Flatten(start_dim=1)
+ self.dropout = nn.Dropout(config.head_dropout) if config.head_dropout > 0 else nn.Identity()
+ self.linear = nn.Linear(config.num_input_channels * config.d_model, config.num_targets)
+
+ def forward(self, embedding: torch.Tensor):
+ """
+ Parameters:
+ embedding (`torch.Tensor` of shape `(bs, num_channels, num_patches, d_model)` or
+ `(bs, num_channels, num_patches+1, d_model)` if `cls_token` is set to True, *required*):
+ Embedding from the model
+ Returns:
+ `torch.Tensor` of shape `(bs, num_targets)`
+
+ """
+ if self.use_cls_token:
+ # use the first output token, pooled_embedding: bs x num_channels x d_model
+ pooled_embedding = embedding[:, :, 0, :]
+ elif self.pooling_type == "mean":
+ # pooled_embedding: [bs x num_channels x d_model]
+ pooled_embedding = embedding.mean(dim=2)
+ elif self.pooling_type == "max":
+ # pooled_embedding: [bs x num_channels x d_model]
+ pooled_embedding = embedding.max(dim=2).values
+ else:
+ raise ValueError(f"pooling operator {self.pooling_type} is not implemented yet")
+ # pooled_embedding: bs x num_channels * d_model
+ pooled_embedding = self.flatten(pooled_embedding)
+ # output: bs x n_classes
+ output = self.linear(self.dropout(pooled_embedding))
+ return output
+
+
+@auto_docstring(
+ custom_intro="""
+ The PatchTST for classification model.
+ """
+)
+class PatchTSTForClassification(PatchTSTPreTrainedModel):
+ def __init__(self, config: PatchTSTConfig):
+ super().__init__(config)
+
+ # Turn off masking
+ if config.do_mask_input:
+ logger.warning("Setting `do_mask_input` parameter to False.")
+ config.do_mask_input = False
+
+ self.model = PatchTSTModel(config)
+ self.head = PatchTSTClassificationHead(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ past_values: torch.Tensor,
+ target_values: torch.Tensor | None = None,
+ past_observed_mask: bool | None = None,
+ output_hidden_states: bool | None = None,
+ output_attentions: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple | PatchTSTForClassificationOutput:
+ r"""
+ past_values (`torch.Tensor` of shape `(bs, sequence_length, num_input_channels)`, *required*):
+ Input sequence to the model
+ target_values (`torch.Tensor`, *optional*):
+ Labels associates with the `past_values`
+ past_observed_mask (`torch.BoolTensor` of shape `(batch_size, sequence_length, num_input_channels)`, *optional*):
+ Boolean mask to indicate which `past_values` were observed and which were missing. Mask values selected
+ in `[0, 1]`:
+
+ - 1 for values that are **observed**,
+ - 0 for values that are **missing** (i.e. NaNs that were replaced by zeros).
+
+ Examples:
+
+ ```python
+ >>> from transformers import PatchTSTConfig, PatchTSTForClassification
+
+ >>> # classification task with two input channel2 and 3 classes
+ >>> config = PatchTSTConfig(
+ ... num_input_channels=2,
+ ... num_targets=3,
+ ... context_length=512,
+ ... patch_length=12,
+ ... stride=12,
+ ... use_cls_token=True,
+ ... )
+ >>> model = PatchTSTForClassification(config=config)
+
+ >>> # during inference, one only provides past values
+ >>> past_values = torch.randn(20, 512, 2)
+ >>> outputs = model(past_values=past_values)
+ >>> labels = outputs.prediction_logits
+ ```"""
+
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ model_output = self.model(
+ past_values=past_values,
+ past_observed_mask=past_observed_mask,
+ output_hidden_states=output_hidden_states,
+ output_attentions=output_attentions,
+ return_dict=True,
+ )
+ y_hat = self.head(model_output.last_hidden_state)
+
+ loss_val = None
+ if target_values is not None:
+ loss = nn.CrossEntropyLoss()
+ loss_val = loss(y_hat, target_values)
+
+ if not return_dict:
+ outputs = (y_hat,) + model_output[1:-3]
+ outputs = (loss_val,) + outputs if loss_val is not None else outputs
+ return outputs
+ return PatchTSTForClassificationOutput(
+ loss=loss_val,
+ prediction_logits=y_hat,
+ hidden_states=model_output.hidden_states,
+ attentions=model_output.attentions,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ The PatchTST for regression Model.
+ """
+)
+class PatchTSTPredictionHead(nn.Module):
+ def __init__(self, config: PatchTSTConfig, num_patches: int, distribution_output=None):
+ r"""
+ num_patches (`int`):
+ The number of patches in the input sequence.
+ distribution_output (`DistributionOutput`, *optional*):
+ The distribution output layer for probabilistic forecasting. If None, a linear output layer is used.
+ """
+ super().__init__()
+
+ self.share_projection = config.share_projection
+ self.num_input_channels = config.num_input_channels
+ self.use_cls_token = config.use_cls_token
+ self.pooling_type = config.pooling_type
+ if self.pooling_type or self.use_cls_token:
+ head_dim = config.d_model
+ else:
+ head_dim = config.d_model * num_patches
+
+ if not self.share_projection:
+ # if each channel has its own head
+ self.projections = nn.ModuleList()
+ self.dropouts = nn.ModuleList()
+ self.flattens = nn.ModuleList()
+ for i in range(self.num_input_channels):
+ self.flattens.append(nn.Flatten(start_dim=2))
+ if distribution_output is None:
+ # use linear head
+ self.projections.append(nn.Linear(head_dim, config.prediction_length))
+ else:
+ # use distribution head
+ self.projections.append(distribution_output.get_parameter_projection(head_dim))
+ self.dropouts.append(nn.Dropout(config.head_dropout) if config.head_dropout > 0 else nn.Identity())
+ else:
+ # all the channels share the same head
+ self.flatten = nn.Flatten(start_dim=2)
+ if distribution_output is None:
+ # use linear head
+ self.projection = nn.Linear(head_dim, config.prediction_length)
+ else:
+ # use distribution head
+ self.projection = distribution_output.get_parameter_projection(head_dim)
+ self.dropout = nn.Dropout(config.head_dropout) if config.head_dropout > 0 else nn.Identity()
+
+ def forward(self, embedding: torch.Tensor):
+ """
+ Parameters:
+ embedding (`torch.Tensor` of shape `(bs, num_channels, num_patches, d_model)` or
+ `(bs, num_channels, num_patches+1, d_model)` if `cls_token` is set to True, *required*):
+ Embedding from the model
+ Returns:
+ `torch.Tensor` of shape `(bs, forecast_len, num_channels)`
+
+ """
+ if self.use_cls_token:
+ # pooled_embedding: [bs x num_channels x d_model]
+ pooled_embedding = embedding[:, :, 0, :]
+ else:
+ if self.pooling_type == "mean":
+ # pooled_embedding: [bs x num_channels x d_model]
+ pooled_embedding = embedding.mean(dim=2)
+ elif self.pooling_type == "max":
+ # pooled_embedding: [bs x num_channels x d_model]
+ pooled_embedding = embedding.max(dim=2).values
+ else:
+ # pooled_embedding: [bs x num_channels x num_patches x d_model]
+ pooled_embedding = embedding
+
+ if not self.share_projection:
+ output = []
+ for i in range(self.num_input_channels):
+ # pooled_embedding: [bs x (d_model * num_patches)] or [bs x d_model)]
+ pooled_embedding = self.flattens[i](pooled_embedding[:, i, :])
+ pooled_embedding = self.dropouts[i](pooled_embedding)
+ # pooled_embedding: [bs x forecast_len]
+ # or tuple ([bs x forecast_len], [bs x forecast_len]) if using distribution head
+ pooled_embedding = self.projections[i](pooled_embedding)
+ output.append(pooled_embedding)
+ # output: [bs x num_channels x forecast_len]
+ output = torch.stack(output, dim=1)
+ else:
+ # pooled_embedding: [bs x num_channels x (d_model * num_patches)] or [bs x num_channels x d_model)]
+ pooled_embedding = self.flatten(pooled_embedding)
+ pooled_embedding = self.dropout(pooled_embedding)
+ # output: [bs x num_channels x forecast_len] or
+ # tuple ([bs x num_channels x forecast_len], [bs x num_channels x forecast_len]) if using distribution head
+ output = self.projection(pooled_embedding)
+
+ if isinstance(output, tuple):
+ # output: ([bs x forecast_len x num_channels], [bs x forecast_len x num_channels])
+ output = tuple(z.transpose(2, 1) for z in output)
+ else:
+ output = output.transpose(2, 1) # [bs x forecast_len x num_channels]
+ return output
+
+
+@auto_docstring(
+ custom_intro="""
+ The PatchTST for prediction model.
+ """
+)
+class PatchTSTForPrediction(PatchTSTPreTrainedModel):
+ def __init__(self, config: PatchTSTConfig):
+ super().__init__(config)
+
+ # Turn off masking
+ if config.do_mask_input:
+ logger.warning("Setting `do_mask_input` parameter to False.")
+ config.do_mask_input = False
+
+ self.model = PatchTSTModel(config)
+
+ if config.loss == "mse":
+ self.distribution_output = None
+ else:
+ if config.distribution_output == "student_t":
+ self.distribution_output = StudentTOutput(dim=config.prediction_length)
+ elif config.distribution_output == "normal":
+ self.distribution_output = NormalOutput(dim=config.prediction_length)
+ elif config.distribution_output == "negative_binomial":
+ self.distribution_output = NegativeBinomialOutput(dim=config.prediction_length)
+ else:
+ raise ValueError(f"Unknown distribution output {config.distribution_output}")
+
+ self.head = PatchTSTPredictionHead(
+ config, self.model.patchifier.num_patches, distribution_output=self.distribution_output
+ )
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def forward(
+ self,
+ past_values: torch.Tensor,
+ past_observed_mask: torch.Tensor | None = None,
+ future_values: torch.Tensor | None = None,
+ output_hidden_states: bool | None = None,
+ output_attentions: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple | PatchTSTForPredictionOutput:
+ r"""
+ Parameters:
+ past_values (`torch.Tensor` of shape `(bs, sequence_length, num_input_channels)`, *required*):
+ Input sequence to the model
+ past_observed_mask (`torch.BoolTensor` of shape `(batch_size, sequence_length, num_input_channels)`, *optional*):
+ Boolean mask to indicate which `past_values` were observed and which were missing. Mask values selected
+ in `[0, 1]`:
+
+ - 1 for values that are **observed**,
+ - 0 for values that are **missing** (i.e. NaNs that were replaced by zeros).
+ future_values (`torch.Tensor` of shape `(bs, forecast_len, num_input_channels)`, *optional*):
+ Future target values associated with the `past_values`
+ output_hidden_states (`bool`, *optional*):
+ Whether or not to return the hidden states of all layers
+ output_attentions (`bool`, *optional*):
+ Whether or not to return the output attention of all layers
+ return_dict (`bool`, *optional*):
+ Whether or not to return a `ModelOutput` instead of a plain tuple.
+
+ Returns:
+ `PatchTSTForPredictionOutput` or tuple of `torch.Tensor` (if `return_dict`=False or
+ `config.return_dict`=False)
+
+ Examples:
+
+ ```python
+ >>> from huggingface_hub import hf_hub_download
+ >>> import torch
+ >>> from transformers import PatchTSTConfig, PatchTSTForPrediction
+
+ >>> file = hf_hub_download(
+ ... repo_id="hf-internal-testing/etth1-hourly-batch", filename="train-batch.pt", repo_type="dataset"
+ ... )
+ >>> batch = torch.load(file)
+
+ >>> # Prediction task with 7 input channels and prediction length is 96
+ >>> model = PatchTSTForPrediction.from_pretrained("namctin/patchtst_etth1_forecast")
+
+ >>> # during training, one provides both past and future values
+ >>> outputs = model(
+ ... past_values=batch["past_values"],
+ ... future_values=batch["future_values"],
+ ... )
+
+ >>> loss = outputs.loss
+ >>> loss.backward()
+
+ >>> # during inference, one only provides past values, the model outputs future values
+ >>> outputs = model(past_values=batch["past_values"])
+ >>> prediction_outputs = outputs.prediction_outputs
+ ```"""
+
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ # get model output
+ model_output = self.model(
+ past_values=past_values,
+ past_observed_mask=past_observed_mask,
+ output_hidden_states=output_hidden_states,
+ output_attentions=output_attentions,
+ return_dict=True,
+ )
+ # get output head
+ y_hat = self.head(model_output.last_hidden_state)
+
+ loss_val = None
+
+ if self.distribution_output:
+ y_hat_out = y_hat
+ else:
+ y_hat_out = y_hat * model_output.scale + model_output.loc
+
+ if future_values is not None:
+ if self.distribution_output:
+ distribution = self.distribution_output.distribution(
+ y_hat, loc=model_output.loc, scale=model_output.scale
+ )
+ loss_val = nll(distribution, future_values)
+ # take average of the loss
+ loss_val = weighted_average(loss_val)
+ else:
+ loss = nn.MSELoss(reduction="mean")
+ loss_val = loss(y_hat_out, future_values)
+
+ loc = model_output.loc
+ scale = model_output.scale
+
+ if not return_dict:
+ outputs = (y_hat_out,) + model_output[1:-1]
+ outputs = (loss_val,) + outputs if loss_val is not None else outputs
+ return outputs
+ return PatchTSTForPredictionOutput(
+ loss=loss_val,
+ prediction_outputs=y_hat_out,
+ hidden_states=model_output.hidden_states,
+ attentions=model_output.attentions,
+ loc=loc,
+ scale=scale,
+ )
+
+ @torch.no_grad()
+ def generate(
+ self,
+ past_values: torch.Tensor,
+ past_observed_mask: torch.Tensor | None = None,
+ ) -> SamplePatchTSTOutput:
+ """
+ Generate sequences of sample predictions from a model with a probability distribution head.
+
+ Parameters:
+ past_values (`torch.FloatTensor` of shape `(batch_size, sequence_length, num_input_channels)`):
+ Past values of the time series that serves as context in order to predict the future.
+ past_observed_mask (`torch.BoolTensor` of shape `(batch_size, sequence_length, num_input_channels)`, *optional*):
+ Boolean mask to indicate which `past_values` were observed and which were missing. Mask values selected
+ in `[0, 1]`:
+
+ - 1 for values that are **observed**,
+ - 0 for values that are **missing** (i.e. NaNs that were replaced by zeros).
+
+ Return:
+ [`SamplePatchTSTOutput`] where the outputs `sequences` tensor will have shape `(batch_size, number of
+ samples, prediction_length, 1)` or `(batch_size, number of samples, prediction_length, num_input_channels)`
+ for multivariate predictions.
+ """
+ # get number of samples
+ num_parallel_samples = self.config.num_parallel_samples
+
+ # get model output
+ outputs = self(
+ past_values=past_values,
+ future_values=None,
+ past_observed_mask=past_observed_mask,
+ output_hidden_states=False,
+ )
+ if self.distribution_output:
+ # get distribution
+ distribution = self.distribution_output.distribution(
+ outputs.prediction_outputs, loc=outputs.loc, scale=outputs.scale
+ )
+ # get samples: list of [bs x forecast_len x num_channels]
+ samples = [distribution.sample() for _ in range(num_parallel_samples)]
+ # samples: [bs x num_samples x forecast_len x num_channels]
+ samples = torch.stack(samples, dim=1)
+ else:
+ samples = outputs.prediction_outputs.unsqueeze(1)
+
+ return SamplePatchTSTOutput(sequences=samples)
+
+
+class PatchTSTRegressionHead(nn.Module):
+ """
+ Regression head
+ """
+
+ def __init__(self, config: PatchTSTConfig, distribution_output=None):
+ super().__init__()
+ self.y_range = config.output_range
+ self.use_cls_token = config.use_cls_token
+ self.pooling_type = config.pooling_type
+ self.distribution_output = distribution_output
+
+ head_dim = config.num_input_channels * config.d_model
+
+ self.flatten = nn.Flatten(start_dim=1)
+ self.dropout = nn.Dropout(config.head_dropout) if config.head_dropout > 0 else nn.Identity()
+
+ if distribution_output is None:
+ self.projection = nn.Linear(head_dim, config.num_targets)
+ else:
+ self.projection = distribution_output.get_parameter_projection(head_dim)
+
+ def forward(self, embedding: torch.Tensor):
+ """
+ Parameters:
+ embedding (`torch.Tensor` of shape `(bs, num_channels, num_patches, d_model)` or
+ `(bs, num_channels, num_patches+1, d_model)` if `cls_token` is set to True, *required*):
+ Embedding from the model
+ Returns:
+ `torch.Tensor` of shape `(bs, output_dim)`
+
+ """
+ if self.use_cls_token:
+ # use the first output token, pooled_embedding: [bs x num_channels x d_model]
+ pooled_embedding = embedding[:, :, 0, :]
+ elif self.pooling_type == "mean":
+ # pooled_embedding: [bs x num_channels x d_model]
+ pooled_embedding = embedding.mean(dim=2)
+ elif self.pooling_type == "max":
+ # pooled_embedding: [bs x num_channels x d_model]
+ pooled_embedding = embedding.max(dim=2).values
+ else:
+ raise ValueError(f"pooling operator {self.pooling_type} is not implemented yet")
+ # flatten the input
+ # pooled_embedding: bs x (num_channels * d_model)
+ pooled_embedding = self.dropout(self.flatten(pooled_embedding))
+ # projection
+ # output: bs x output_dim or a tuple of this shape for distribution head
+ output = self.projection(pooled_embedding)
+ # apply sigmoid to bound the output if required
+ if (self.distribution_output is None) & (self.y_range is not None): # linear head
+ output = torch.sigmoid(output) * (self.y_range[1] - self.y_range[0]) + self.y_range[0]
+ return output
+
+
+@auto_docstring(
+ custom_intro="""
+ The PatchTST for regression model.
+ """
+)
+class PatchTSTForRegression(PatchTSTPreTrainedModel):
+ def __init__(self, config: PatchTSTConfig):
+ super().__init__(config)
+
+ # Turn off masking
+ if config.do_mask_input:
+ logger.warning("Setting `do_mask_input` parameter to False.")
+ config.do_mask_input = False
+
+ self.model = PatchTSTModel(config)
+ if config.loss == "mse":
+ self.distribution_output = None
+ else:
+ if config.distribution_output == "student_t":
+ self.distribution_output = StudentTOutput(dim=config.num_targets)
+ elif config.distribution_output == "normal":
+ self.distribution_output = NormalOutput(dim=config.num_targets)
+ elif config.distribution_output == "negative_binomial":
+ self.distribution_output = NegativeBinomialOutput(dim=config.num_targets)
+ else:
+ raise ValueError(f"Unknown distribution output {config.distribution_output}")
+
+ self.head = PatchTSTRegressionHead(config, self.distribution_output)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ past_values: torch.Tensor,
+ target_values: torch.Tensor | None = None,
+ past_observed_mask: torch.Tensor | None = None,
+ output_hidden_states: bool | None = None,
+ output_attentions: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple | PatchTSTForRegressionOutput:
+ r"""
+ past_values (`torch.Tensor` of shape `(bs, sequence_length, num_input_channels)`, *required*):
+ Input sequence to the model
+ target_values (`torch.Tensor` of shape `(bs, num_input_channels)`):
+ Target values associates with the `past_values`
+ past_observed_mask (`torch.BoolTensor` of shape `(batch_size, sequence_length, num_input_channels)`, *optional*):
+ Boolean mask to indicate which `past_values` were observed and which were missing. Mask values selected
+ in `[0, 1]`:
+
+ - 1 for values that are **observed**,
+ - 0 for values that are **missing** (i.e. NaNs that were replaced by zeros).
+ Whether or not to return a `ModelOutput` instead of a plain tuple.
+
+ Examples:
+
+ ```python
+ >>> from transformers import PatchTSTConfig, PatchTSTForRegression
+
+ >>> # Regression task with 6 input channels and regress 2 targets
+ >>> model = PatchTSTForRegression.from_pretrained("namctin/patchtst_etth1_regression")
+
+ >>> # during inference, one only provides past values, the model outputs future values
+ >>> past_values = torch.randn(20, 512, 6)
+ >>> outputs = model(past_values=past_values)
+ >>> regression_outputs = outputs.regression_outputs
+ ```"""
+
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ model_output = self.model(
+ past_values=past_values,
+ past_observed_mask=past_observed_mask,
+ output_hidden_states=output_hidden_states,
+ output_attentions=output_attentions,
+ return_dict=True,
+ )
+ # get output head. y_hat is of shape [bs x num_targets] or tuple of this shape
+ y_hat = self.head(model_output.last_hidden_state)
+
+ loss = None
+ if target_values is not None:
+ if self.distribution_output:
+ distribution = self.distribution_output.distribution(y_hat)
+ # y_hat should be a 2-tuple, each with dimension [bs, num_targets]
+ y_hat = tuple(item.view(-1, self.config.num_targets) for item in y_hat)
+ loss = nll(distribution, target_values)
+ # take average of the loss
+ loss = weighted_average(loss)
+ else:
+ loss = nn.MSELoss(reduction="mean")
+ loss = loss(y_hat, target_values)
+
+ if not return_dict:
+ # hidden_states, attentions, mask
+ outputs = (y_hat,) + model_output[1:-3]
+ outputs = (loss,) + outputs if loss is not None else outputs
+ return outputs
+ return PatchTSTForRegressionOutput(
+ loss=loss,
+ regression_outputs=y_hat,
+ hidden_states=model_output.hidden_states,
+ attentions=model_output.attentions,
+ )
+
+ @torch.no_grad()
+ def generate(
+ self,
+ past_values: torch.Tensor,
+ past_observed_mask: torch.Tensor | None = None,
+ ) -> SamplePatchTSTOutput:
+ """
+ Generate sequences of sample predictions from a model with a probability distribution head.
+
+ Parameters:
+ past_values (`torch.FloatTensor` of shape `(batch_size, sequence_length, num_input_channels)`):
+ Past values of the time series that serves as context in order to predict the future.
+ past_observed_mask (`torch.BoolTensor` of shape `(batch_size, sequence_length, num_input_channels)`, *optional*):
+ Boolean mask to indicate which `past_values` were observed and which were missing. Mask values selected
+ in `[0, 1]`:
+
+ - 1 for values that are **observed**,
+ - 0 for values that are **missing** (i.e. NaNs that were replaced by zeros).
+
+ Return:
+ [`SamplePatchTSTOutput`] where the outputs `sequences` tensor will have shape `(batch_size, number of
+ samples, num_targets)`.
+ """
+ # get number of samples
+ num_parallel_samples = self.config.num_parallel_samples
+
+ # get model output
+ outputs = self(
+ past_values=past_values,
+ target_values=None,
+ past_observed_mask=past_observed_mask,
+ output_hidden_states=False,
+ )
+
+ # get distribution
+ distribution = self.distribution_output.distribution(outputs.regression_outputs)
+ # get samples: list of [bs x num_targets]
+ samples = [distribution.sample() for _ in range(num_parallel_samples)]
+ # samples: [bs x num_samples x num_targets]
+ samples = torch.stack(samples, dim=1).view(-1, num_parallel_samples, self.config.num_targets)
+ return SamplePatchTSTOutput(sequences=samples)
+
+
+__all__ = [
+ "PatchTSTModel",
+ "PatchTSTPreTrainedModel",
+ "PatchTSTForPrediction",
+ "PatchTSTForPretraining",
+ "PatchTSTForRegression",
+ "PatchTSTForClassification",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pe_audio_video/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pe_audio_video/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..22175813f31f9bcbabd516309fc493b034f198f6
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pe_audio_video/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pe_audio_video/__pycache__/configuration_pe_audio_video.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pe_audio_video/__pycache__/configuration_pe_audio_video.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c5d9fc2859a31da50a0292fdf1aac05b44034472
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pe_audio_video/__pycache__/configuration_pe_audio_video.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pe_audio_video/__pycache__/modeling_pe_audio_video.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pe_audio_video/__pycache__/modeling_pe_audio_video.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..163d3a8320ee82c0d99c9fb49f5d78dc6f400f73
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pe_audio_video/__pycache__/modeling_pe_audio_video.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pe_audio_video/__pycache__/modular_pe_audio_video.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pe_audio_video/__pycache__/modular_pe_audio_video.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e062e5a85790a40860e6667f423af73079bc95c8
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pe_audio_video/__pycache__/modular_pe_audio_video.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pe_audio_video/__pycache__/processing_pe_audio_video.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pe_audio_video/__pycache__/processing_pe_audio_video.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9ecf5ace7af8a8e012c844c2ba971fa571ec1c7e
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pe_audio_video/__pycache__/processing_pe_audio_video.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/persimmon/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/persimmon/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bf6de696dac8a595d5e15f8d3b1acd4735ca6ee0
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/persimmon/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/persimmon/__pycache__/configuration_persimmon.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/persimmon/__pycache__/configuration_persimmon.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b6bb8afb7abebfafc636d2c8f7c670b3718890a2
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/persimmon/__pycache__/configuration_persimmon.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/persimmon/__pycache__/modeling_persimmon.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/persimmon/__pycache__/modeling_persimmon.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0fa486be9f7ae6604c67b0223618e9ee1809dc75
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/persimmon/__pycache__/modeling_persimmon.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/phi4_multimodal/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/phi4_multimodal/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..85fbe13e7ac6ccf175eba071b73234bb315be7db
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/phi4_multimodal/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/phi4_multimodal/__pycache__/configuration_phi4_multimodal.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/phi4_multimodal/__pycache__/configuration_phi4_multimodal.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c099ce8d26546be49d2225d1bbc3cea4c586e818
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/phi4_multimodal/__pycache__/configuration_phi4_multimodal.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/phi4_multimodal/__pycache__/feature_extraction_phi4_multimodal.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/phi4_multimodal/__pycache__/feature_extraction_phi4_multimodal.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..eb731d901e41ddf1c39b67607b676fed07e8c5fa
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/phi4_multimodal/__pycache__/feature_extraction_phi4_multimodal.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/phi4_multimodal/__pycache__/image_processing_phi4_multimodal.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/phi4_multimodal/__pycache__/image_processing_phi4_multimodal.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..71d6c2123a0bc3e9fed2d4dc1f3a4cdb6f2df217
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/phi4_multimodal/__pycache__/image_processing_phi4_multimodal.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/phi4_multimodal/__pycache__/modular_phi4_multimodal.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/phi4_multimodal/__pycache__/modular_phi4_multimodal.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8ff28f01266dd57dcc69b0d0067443705c2f548f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/phi4_multimodal/__pycache__/modular_phi4_multimodal.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/phi4_multimodal/__pycache__/processing_phi4_multimodal.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/phi4_multimodal/__pycache__/processing_phi4_multimodal.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..79bead5fe0cccb081ab19198e6654a024149b931
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/phi4_multimodal/__pycache__/processing_phi4_multimodal.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pixtral/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pixtral/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b0d0bf1822f15b0660ac1dfd96060d468593bad6
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pixtral/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pixtral/__pycache__/configuration_pixtral.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pixtral/__pycache__/configuration_pixtral.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e99ceaff93d0f9588a41a2dc8ddfd6bb4a4400f5
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pixtral/__pycache__/configuration_pixtral.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pixtral/__pycache__/image_processing_pil_pixtral.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pixtral/__pycache__/image_processing_pil_pixtral.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..703817688889e11583db8a16699ac84024f6ccb1
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pixtral/__pycache__/image_processing_pil_pixtral.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pixtral/__pycache__/image_processing_pixtral.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pixtral/__pycache__/image_processing_pixtral.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c98bdcf964f3793d6e83e6c59db06497126d26dd
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pixtral/__pycache__/image_processing_pixtral.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pixtral/__pycache__/modeling_pixtral.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pixtral/__pycache__/modeling_pixtral.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..59cd32620a558c9f245e1baecdc4614975432a9c
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pixtral/__pycache__/modeling_pixtral.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pixtral/__pycache__/processing_pixtral.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pixtral/__pycache__/processing_pixtral.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5c7a8d88c9474adc1b5df6780bdc096a395c6d1e
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pixtral/__pycache__/processing_pixtral.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pp_formulanet/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pp_formulanet/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..066f8084a4a318df1164ad7186b6287a5b88f4fc
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pp_formulanet/__init__.py
@@ -0,0 +1,29 @@
+# Copyright 2026 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_pp_formulanet import *
+ from .image_processing_pp_formulanet import *
+ from .modeling_pp_formulanet import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pp_formulanet/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pp_formulanet/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4ac44b8ff969a061b612162994367fdb2aefa519
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pp_formulanet/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pp_formulanet/__pycache__/configuration_pp_formulanet.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pp_formulanet/__pycache__/configuration_pp_formulanet.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7e0465e103ebb780a9203be48c654e134a979bad
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pp_formulanet/__pycache__/configuration_pp_formulanet.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pp_formulanet/__pycache__/image_processing_pp_formulanet.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pp_formulanet/__pycache__/image_processing_pp_formulanet.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9132219408464748da91160e749643afb0d54233
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pp_formulanet/__pycache__/image_processing_pp_formulanet.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pp_formulanet/__pycache__/modeling_pp_formulanet.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pp_formulanet/__pycache__/modeling_pp_formulanet.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ea8605b1b92382a6cecdd3c78494791b47e6c00a
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pp_formulanet/__pycache__/modeling_pp_formulanet.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pp_formulanet/__pycache__/modular_pp_formulanet.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pp_formulanet/__pycache__/modular_pp_formulanet.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2c5d74ad03c0754f4ff2845590fe810b2b682c83
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pp_formulanet/__pycache__/modular_pp_formulanet.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pp_formulanet/__pycache__/processing_pp_formulanet.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pp_formulanet/__pycache__/processing_pp_formulanet.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dce2b1b4eeb454030dd03125a131b53692372b8f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pp_formulanet/__pycache__/processing_pp_formulanet.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pp_formulanet/configuration_pp_formulanet.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pp_formulanet/configuration_pp_formulanet.py
new file mode 100644
index 0000000000000000000000000000000000000000..e5749c68e71ef6f4d5569625a37706bff5cde887
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pp_formulanet/configuration_pp_formulanet.py
@@ -0,0 +1,155 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/pp_formulanet/modular_pp_formulanet.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_pp_formulanet.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2026 The PaddlePaddle Team and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring, logging
+
+
+logger = logging.get_logger(__name__)
+
+
+@auto_docstring(checkpoint="PaddlePaddle/PPFormulaNet_plus-L_safetensors")
+@strict
+class PPFormulaNetVisionConfig(PreTrainedConfig):
+ r"""
+ output_channels (`int`, *optional*, defaults to 256):
+ Dimensionality of the output channels in the Patch Encoder.
+ window_size (`int`, *optional*, defaults to 14):
+ Window size for relative position.
+ global_attn_indexes (`list[int]`, *optional*, defaults to `[2, 5, 8, 11]`):
+ The indexes of the global attention layers.
+ mlp_dim (`int`, *optional*, defaults to 3072):
+ The dimensionality of the MLP layer in the Transformer encoder.
+ post_conv_in_channels (`int`, *optional*, defaults to 256):
+ Number of input channels for the post-encoder convolution layer.
+ post_conv_out_channels (`int`, *optional*, defaults to 1024):
+ Number of output channels for the post-encoder convolution layer.
+ post_conv_mid_channels (`int`, *optional*, defaults to 512):
+ Number of intermediate channels for the post-encoder convolution layer.
+ decoder_hidden_size (`int`, *optional*, defaults to 512):
+ The hidden size of the decoder that the encoder features are projected to.
+ """
+
+ base_config_key = "vision_config"
+ hidden_size: int = 768
+ output_channels: int = 256
+ num_hidden_layers: int = 12
+ num_attention_heads: int = 12
+ num_channels: int = 3
+ image_size: int = 512
+ patch_size: int | list[int] | tuple[int, int] = 16
+ hidden_act: str = "gelu"
+ layer_norm_eps: float = 1e-06
+ attention_dropout: float | int = 0.0
+ initializer_range: float = 1e-10
+ qkv_bias: bool = True
+ use_abs_pos: bool = True
+ use_rel_pos: bool = True
+ window_size: int = 14
+ global_attn_indexes: list[int] | tuple[int, ...] = (2, 5, 8, 11)
+ mlp_dim: int = 3072
+
+ post_conv_in_channels: int = 256
+ post_conv_out_channels: int = 1024
+ post_conv_mid_channels: int = 512
+ decoder_hidden_size: int = 512
+
+
+@auto_docstring(checkpoint="PaddlePaddle/PPFormulaNet_plus-L_safetensors")
+@strict
+class PPFormulaNetTextConfig(PreTrainedConfig):
+ r"""
+ Example:
+
+ ```python
+ >>> from transformers import PPFormulaNetTextConfig, PPFormulaNetTextModel
+
+ >>> # Initializing a PP_FORMULANET facebook/pp_formulanet-large-cc25 style configuration
+ >>> configuration = PPFormulaNetTextConfig()
+
+ >>> # Initializing a model (with random weights) from the facebook/pp_formulanet-large-cc25 style configuration
+ >>> model = PPFormulaNetTextModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "pp_formulanet"
+ keys_to_ignore_at_inference = ["past_key_values"]
+ attribute_map = {
+ "num_attention_heads": "encoder_attention_heads",
+ "hidden_size": "d_model",
+ "num_hidden_layers": "encoder_layers",
+ }
+ vocab_size: int = 50000
+ max_position_embeddings: int = 2560
+ encoder_layers: int = 12
+ encoder_attention_heads: int = 16
+ decoder_layers: int = 8
+ decoder_ffn_dim: int = 2048
+ decoder_attention_heads: int = 16
+ decoder_layerdrop: float | int = 0.0
+ use_cache: bool = True
+ is_encoder_decoder: bool = True
+ activation_function: str = "gelu"
+ d_model: int = 512
+ dropout: float | int = 0.1
+ attention_dropout: float | int = 0.0
+ activation_dropout: float | int = 0.0
+ init_std: float = 0.02
+ scale_embedding: bool = True
+ pad_token_id: int | None = 1
+ bos_token_id: int | None = 0
+ eos_token_id: int | list[int] | None = 2
+ decoder_start_token_id: int | None = 2
+ forced_eos_token_id: int | list[int] | None = 2
+ tie_word_embeddings: bool = False
+ base_config_key = "text_config"
+
+
+@auto_docstring(checkpoint="PaddlePaddle/PPFormulaNet_plus-L_safetensors")
+@strict
+class PPFormulaNetConfig(PreTrainedConfig):
+ model_type = "pp_formulanet"
+ sub_configs = {"text_config": PPFormulaNetTextConfig, "vision_config": PPFormulaNetVisionConfig}
+
+ text_config: dict | PPFormulaNetTextConfig | None = None
+ vision_config: dict | PPFormulaNetVisionConfig | None = None
+ is_encoder_decoder: bool = True
+
+ def __post_init__(self, **kwargs):
+ if isinstance(self.text_config, dict):
+ self.text_config = PPFormulaNetTextConfig(**self.text_config)
+ elif self.text_config is None:
+ logger.info("text_config is None. Initializing the PPFormulaNetTextConfig with default values.")
+ self.text_config = PPFormulaNetTextConfig()
+
+ if isinstance(self.vision_config, dict):
+ self.vision_config = PPFormulaNetVisionConfig(**self.vision_config)
+ elif self.vision_config is None:
+ logger.info("vision_config is None. Initializing the PPFormulaNetVisionConfig with default values.")
+ self.vision_config = PPFormulaNetVisionConfig()
+
+ super().__post_init__(**kwargs)
+
+
+__all__ = ["PPFormulaNetConfig", "PPFormulaNetTextConfig", "PPFormulaNetVisionConfig"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pp_formulanet/image_processing_pp_formulanet.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pp_formulanet/image_processing_pp_formulanet.py
new file mode 100644
index 0000000000000000000000000000000000000000..b3a5a5f5c6f72b7631c7ec170eaf69e6350a9578
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pp_formulanet/image_processing_pp_formulanet.py
@@ -0,0 +1,298 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/pp_formulanet/modular_pp_formulanet.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_pp_formulanet.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2026 The PaddlePaddle Team and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+import torch
+from torchvision.transforms.v2 import functional as tvF
+
+from ...image_processing_backends import TorchvisionBackend
+from ...image_processing_utils import BatchFeature
+from ...image_transforms import get_resize_output_image_size, group_images_by_shape, reorder_images
+from ...image_utils import ChannelDimension, ImageInput, PILImageResampling, SizeDict
+from ...processing_utils import ImagesKwargs, Unpack
+from ...utils import TensorType, auto_docstring
+from ...utils.import_utils import requires
+
+
+class PPFormulaNetImageProcessorKwargs(ImagesKwargs, total=False):
+ r"""
+ do_crop_margin (`bool`, *optional*, defaults to `self.do_crop_margin`):
+ Whether to crop the image margins.
+ do_thumbnail (`bool`, *optional*, defaults to `self.do_thumbnail`):
+ Whether to resize the image using thumbnail method.
+ do_align_long_axis (`bool`, *optional*, defaults to `self.do_align_long_axis`):
+ Whether to align the long axis of the image with the long axis of `size` by rotating by 90 degrees.
+ """
+
+ do_crop_margin: bool
+ do_thumbnail: bool
+ do_align_long_axis: bool
+
+
+@auto_docstring
+@requires(backends=("torch",))
+class PPFormulaNetImageProcessor(TorchvisionBackend):
+ valid_kwargs = PPFormulaNetImageProcessorKwargs
+ resample = PILImageResampling.BILINEAR
+ image_mean = [0.7931, 0.7931, 0.7931]
+ image_std = [0.1738, 0.1738, 0.1738]
+ size = {"height": 768, "width": 768}
+ do_resize = True
+ do_normalize = True
+ do_thumbnail = True
+ do_align_long_axis = False
+ do_pad = True
+ do_rescale = True
+ do_crop_margin = True
+
+ def __init__(self, **kwargs: Unpack[PPFormulaNetImageProcessorKwargs]):
+ super().__init__(**kwargs)
+
+ @auto_docstring
+ def preprocess(self, images: ImageInput, **kwargs: Unpack[PPFormulaNetImageProcessorKwargs]) -> BatchFeature:
+ return super().preprocess(images, **kwargs)
+
+ def python_find_non_zero(
+ self,
+ image: "torch.Tensor",
+ ):
+ """This is a reimplementation of a findNonZero function equivalent to cv2."""
+
+ non_zero_indices = torch.nonzero(image, as_tuple=False)
+ idxvec = non_zero_indices[:, [2, 1]]
+ idxvec = idxvec.reshape(-1, 1, 2)
+ return idxvec
+
+ def python_bounding_rect(self, coordinates):
+ """This is a reimplementation of a BoundingRect function equivalent to cv2."""
+
+ min_values = torch.amin(coordinates, axis=(0, 1)).to(torch.int)
+ max_values = torch.amax(coordinates, axis=(0, 1)).to(torch.int)
+
+ x_min, y_min = min_values[0], min_values[1]
+ width = max_values[0] - x_min + 1
+ height = max_values[1] - y_min + 1
+ return x_min, y_min, width, height
+
+ def crop_margin(
+ self,
+ image: "torch.Tensor",
+ gray_threshold: int = 200,
+ ) -> "torch.Tensor":
+ """
+ Crops the margin of the image. Gray pixels are considered margin (i.e., pixels with a value below the
+ threshold).
+
+ Args:
+ image (`torch.Tensor`):
+ The image to be cropped.
+ gray_threshold (`int`, *optional*, defaults to `200`)
+ Value below which pixels are considered to be gray.
+ """
+ data = tvF.rgb_to_grayscale(image, num_output_channels=1)
+
+ max_val = torch.max(data)
+ min_val = torch.min(data)
+
+ if max_val == min_val:
+ return image
+ data = (data - min_val) / (max_val - min_val) * 255
+ gray = data < gray_threshold
+ coords = self.python_find_non_zero(gray)
+ x_min, y_min, width, height = self.python_bounding_rect(coords)
+ image = image[:, y_min : y_min + height, x_min : x_min + width]
+
+ return image
+
+ def align_long_axis(
+ self,
+ image: "torch.Tensor",
+ size: SizeDict,
+ ) -> "torch.Tensor":
+ """
+ Align the long axis of the image to the longest axis of the specified size.
+
+ Args:
+ image (`torch.Tensor`):
+ The image to be aligned.
+ size (`SizeDict`):
+ The size to align the long axis to.
+ Returns:
+ `torch.Tensor`: The aligned image.
+ """
+ input_height, input_width = image.shape[-2:]
+ output_height, output_width = size.height, size.width
+
+ if (output_width < output_height and input_width > input_height) or (
+ output_width > output_height and input_width < input_height
+ ):
+ image = torch.rot90(image, 3, dims=[1, 2])
+
+ return image
+
+ def thumbnail(
+ self,
+ image: "torch.Tensor",
+ size: SizeDict,
+ ) -> "torch.Tensor":
+ """
+ Resize the image to make a thumbnail. The image is resized so that no dimension is larger than any
+ corresponding dimension of the specified size.
+
+ Args:
+ image (`torch.tensor`):
+ The image to be resized.
+ size (`SizeDict`):
+ The size to resize the image to.
+ """
+
+ input_height, input_width = image.shape[-2:]
+ output_height, output_width = size.height, size.width
+
+ # We always resize to the smallest of either the input or output size.
+ height = min(input_height, output_height)
+ width = min(input_width, output_width)
+
+ if height == input_height and width == input_width:
+ return image
+
+ if input_height > input_width:
+ width = int(input_width * height / input_height)
+ elif input_width > input_height:
+ height = int(input_height * width / input_width)
+
+ new_size = (height, width)
+
+ return tvF.resize(image, new_size, interpolation=tvF.InterpolationMode.BICUBIC)
+
+ def pad_images(
+ self,
+ image: "torch.Tensor",
+ size: SizeDict,
+ ) -> "torch.Tensor":
+ """
+ Pads a batch of images to the specified size at the top, bottom, left and right.
+
+ Args:
+ image (`torch.tensor`):
+ The image to be padded.
+ size (`SizeDict`):
+ The size to pad the image to.
+ """
+ input_height, input_width = image.shape[-2:]
+ output_height, output_width = size.height, size.width
+
+ delta_width = output_width - input_width
+ delta_height = output_height - input_height
+
+ pad_top = delta_height // 2
+ pad_left = delta_width // 2
+
+ pad_bottom = delta_height - pad_top
+ pad_right = delta_width - pad_left
+
+ padding = (pad_left, pad_top, pad_right, pad_bottom)
+ return tvF.pad(image, padding)
+
+ def resize(
+ self,
+ image: "torch.Tensor",
+ size: SizeDict,
+ resample: "PILImageResampling | tvF.InterpolationMode | int | None" = None,
+ antialias: bool = True,
+ **kwargs,
+ ) -> "torch.Tensor":
+ """
+ Resize an image to `(size.height, size.width)`.
+
+ Args:
+ image (`torch.Tensor`):
+ Image to resize.
+ size (`SizeDict`):
+ Size of the output image.
+ resample (`PILImageResampling | tvF.InterpolationMode | int`, *optional*):
+ Resampling filter to use when resizing the image.
+ Returns:
+ `torch.Tensor`: The resized image.
+ """
+ shortest_edge = min(size.height, size.width)
+
+ new_size = get_resize_output_image_size(
+ image, size=shortest_edge, default_to_square=False, input_data_format=ChannelDimension.FIRST
+ )
+ return super().resize(
+ image, SizeDict(height=new_size[0], width=new_size[1]), resample=resample, antialias=antialias, **kwargs
+ )
+
+ def _preprocess(
+ self,
+ images: list["torch.Tensor"],
+ do_resize: bool,
+ size: SizeDict,
+ resample: "PILImageResampling | tvF.InterpolationMode | int | None",
+ do_rescale: bool,
+ rescale_factor: float,
+ do_normalize: bool,
+ image_mean: float | list[float] | None,
+ image_std: float | list[float] | None,
+ do_pad: bool | None,
+ disable_grouping: bool | None,
+ return_tensors: str | TensorType | None,
+ do_align_long_axis: bool = False,
+ do_thumbnail: bool = True,
+ do_crop_margin: bool = True,
+ **kwargs,
+ ) -> BatchFeature:
+ # Crop images
+ if do_crop_margin:
+ images = [self.crop_margin(image) for image in images]
+
+ # Group images by size for batched resizing
+ grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping)
+ resized_images_grouped = {}
+ for shape, stacked_images in grouped_images.items():
+ if do_align_long_axis:
+ stacked_images = self.align_long_axis(image=stacked_images, size=size)
+ if do_resize:
+ stacked_images = self.resize(image=stacked_images, size=size, resample=resample)
+ if do_thumbnail:
+ stacked_images = self.thumbnail(image=stacked_images, size=size)
+ if do_pad:
+ stacked_images = self.pad_images(image=stacked_images, size=size)
+ resized_images_grouped[shape] = stacked_images
+ resized_images = reorder_images(resized_images_grouped, grouped_images_index)
+
+ # Group images by size for further processing
+ # Needed in case do_resize is False, or resize returns images with different sizes
+ grouped_images, grouped_images_index = group_images_by_shape(resized_images, disable_grouping=disable_grouping)
+ processed_images_grouped = {}
+ for shape, stacked_images in grouped_images.items():
+ # Fused rescale and normalize
+ stacked_images = self.rescale_and_normalize(
+ stacked_images, do_rescale, rescale_factor, do_normalize, image_mean, image_std
+ )
+ processed_images_grouped[shape] = stacked_images
+
+ processed_images = reorder_images(processed_images_grouped, grouped_images_index)
+
+ return BatchFeature(data={"pixel_values": processed_images}, tensor_type=return_tensors)
+
+
+__all__ = ["PPFormulaNetImageProcessor"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pp_formulanet/modeling_pp_formulanet.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pp_formulanet/modeling_pp_formulanet.py
new file mode 100644
index 0000000000000000000000000000000000000000..14c4b371de889dd30357e58ef8c15d439864debc
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pp_formulanet/modeling_pp_formulanet.py
@@ -0,0 +1,1165 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/pp_formulanet/modular_pp_formulanet.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_pp_formulanet.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2026 The PaddlePaddle Team and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import collections
+import math
+from collections.abc import Callable
+from dataclasses import dataclass
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...cache_utils import Cache, DynamicCache, EncoderDecoderCache
+from ...generation import GenerationMixin
+from ...masking_utils import create_bidirectional_mask, create_causal_mask
+from ...modeling_flash_attention_utils import FlashAttentionKwargs
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import (
+ BaseModelOutputWithPastAndCrossAttentions,
+ BaseModelOutputWithPooling,
+ Seq2SeqLMOutput,
+ Seq2SeqModelOutput,
+)
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import (
+ TransformersKwargs,
+ auto_docstring,
+ can_return_tuple,
+ is_torchdynamo_compiling,
+ logging,
+)
+from ...utils.generic import merge_with_config_defaults
+from ...utils.output_capturing import OutputRecorder, capture_outputs
+from .configuration_pp_formulanet import PPFormulaNetConfig, PPFormulaNetVisionConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+class PPFormulaNetPreTrainedModel(PreTrainedModel):
+ config: PPFormulaNetConfig
+ base_model_prefix = "model"
+ main_input_name = "pixel_values"
+ input_modalities = ("image",)
+ supports_gradient_checkpointing = True
+ _keep_in_fp32_modules_strict = []
+ # Note this goes for the decoder only, the encoder will inherently always use eager attention
+ _supports_sdpa = True
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ """Initialize the weights"""
+ super()._init_weights(module)
+
+ # Initialize positional embeddings to zero (PPFormulaNetVisionModel holds pos_embed)
+ if isinstance(module, PPFormulaNetVisionModel):
+ if module.pos_embed is not None:
+ init.constant_(module.pos_embed, 0.0)
+
+ # Initialize relative positional embeddings to zero (PPFormulaNetVisionAttention holds rel_pos_h/w)
+ if isinstance(module, PPFormulaNetVisionAttention):
+ if module.use_rel_pos:
+ init.constant_(module.rel_pos_h, 0.0)
+ init.constant_(module.rel_pos_w, 0.0)
+
+
+# overrider for PPFormulaNetModel's encoder output
+@dataclass
+class PPFormulaNetVisionEncoderOutput(BaseModelOutputWithPooling):
+ pass
+
+
+class PPFormulaNetVisionAttention(nn.Module):
+ """Multi-head Attention block with relative position embeddings."""
+
+ def __init__(self, config, window_size):
+ super().__init__()
+ input_size = (
+ (config.image_size // config.patch_size, config.image_size // config.patch_size)
+ if window_size == 0
+ else (window_size, window_size)
+ )
+
+ self.num_attention_heads = config.num_attention_heads
+ head_dim = config.hidden_size // config.num_attention_heads
+ self.scale = head_dim**-0.5
+ self.dropout = config.attention_dropout
+
+ self.qkv = nn.Linear(config.hidden_size, config.hidden_size * 3, bias=config.qkv_bias)
+ self.proj = nn.Linear(config.hidden_size, config.hidden_size)
+
+ self.use_rel_pos = config.use_rel_pos
+ if self.use_rel_pos:
+ if input_size is None:
+ raise ValueError("Input size must be provided if using relative positional encoding.")
+
+ # initialize relative positional embeddings
+ self.rel_pos_h = nn.Parameter(torch.zeros(2 * input_size[0] - 1, head_dim))
+ self.rel_pos_w = nn.Parameter(torch.zeros(2 * input_size[1] - 1, head_dim))
+
+ def get_rel_pos(self, q_size: int, k_size: int, rel_pos: torch.Tensor) -> torch.Tensor:
+ """
+ Get relative positional embeddings according to the relative positions of
+ query and key sizes.
+
+ Args:
+ q_size (int):
+ size of the query.
+ k_size (int):
+ size of key k.
+ rel_pos (`torch.Tensor`):
+ relative position embeddings (L, channel).
+
+ Returns:
+ Extracted positional embeddings according to relative positions.
+ """
+ max_rel_dist = int(2 * max(q_size, k_size) - 1)
+ # Interpolate rel pos.
+ rel_pos_resized = F.interpolate(
+ rel_pos.reshape(1, rel_pos.shape[0], -1).transpose(1, 2),
+ size=max_rel_dist,
+ mode="linear",
+ )
+ rel_pos_resized = rel_pos_resized.reshape(-1, max_rel_dist).permute(1, 0)
+
+ # Scale the coords with short length if shapes for q and k are different.
+ q_coords = torch.arange(q_size)[:, None] * max(k_size / q_size, 1.0)
+ k_coords = torch.arange(k_size)[None, :] * max(q_size / k_size, 1.0)
+ relative_coords = (q_coords - k_coords) + (k_size - 1) * max(q_size / k_size, 1.0)
+
+ return rel_pos_resized[relative_coords.long()]
+
+ def get_decomposed_rel_pos(
+ self,
+ query: torch.Tensor,
+ rel_pos_h: torch.Tensor,
+ rel_pos_w: torch.Tensor,
+ q_size: tuple[int, int],
+ k_size: tuple[int, int],
+ ) -> torch.Tensor:
+ """
+ Calculate decomposed Relative Positional Embeddings from :paper:`mvitv2`.
+ https://github.com/facebookresearch/mvit/blob/19786631e330df9f3622e5402b4a419a263a2c80/mvit/models/attention.py
+
+ Args:
+ query (`torch.Tensor`):
+ query q in the attention layer with shape (batch_size, query_height * query_width, channel).
+ rel_pos_h (`torch.Tensor`):
+ relative position embeddings (Lh, channel) for height axis.
+ rel_pos_w (`torch.Tensor`):
+ relative position embeddings (Lw, channel) for width axis.
+ q_size (tuple):
+ spatial sequence size of query q with (query_height, query_width).
+ k_size (tuple):
+ spatial sequence size of key k with (key_height, key_width).
+
+ Returns:
+ decomposed_rel_pos (`torch.Tensor`):
+ decomposed relative position embeddings.
+ """
+ query_height, query_width = q_size
+ key_height, key_width = k_size
+ relative_position_height = self.get_rel_pos(query_height, key_height, rel_pos_h)
+ relative_position_width = self.get_rel_pos(query_width, key_width, rel_pos_w)
+
+ batch_size, _, dim = query.shape
+ reshaped_query = query.reshape(batch_size, query_height, query_width, dim)
+ rel_h = torch.einsum("bhwc,hkc->bhwk", reshaped_query, relative_position_height)
+ rel_w = torch.einsum("bhwc,wkc->bhwk", reshaped_query, relative_position_width)
+
+ decomposed_rel_pos = rel_h[:, :, :, :, None] + rel_w[:, :, :, None, :]
+
+ return decomposed_rel_pos
+
+ def forward(self, hidden_states: torch.Tensor, output_attentions=None) -> tuple[torch.Tensor, torch.Tensor]:
+ batch_size, height, width, _ = hidden_states.shape
+ # qkv with shape (3, batch_size, nHead, height * width, channel)
+ qkv = (
+ self.qkv(hidden_states)
+ .reshape(batch_size, height * width, 3, self.num_attention_heads, -1)
+ .permute(2, 0, 3, 1, 4)
+ )
+ # q, k, v with shape (batch_size * nHead, height * width, channel)
+ query, key, value = qkv.reshape(3, batch_size * self.num_attention_heads, height * width, -1).unbind(0)
+
+ attn_weights = (query * self.scale) @ key.transpose(-2, -1)
+
+ if self.use_rel_pos:
+ decomposed_rel_pos = self.get_decomposed_rel_pos(
+ query, self.rel_pos_h, self.rel_pos_w, (height, width), (height, width)
+ )
+ decomposed_rel_pos = decomposed_rel_pos.reshape_as(attn_weights)
+ attn_weights = attn_weights + decomposed_rel_pos
+
+ attn_weights = torch.nn.functional.softmax(attn_weights, dtype=torch.float32, dim=-1).to(query.dtype)
+
+ attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
+
+ attn_output = (attn_probs @ value).reshape(batch_size, self.num_attention_heads, height, width, -1)
+ attn_output = attn_output.permute(0, 2, 3, 1, 4).reshape(batch_size, height, width, -1)
+
+ attn_output = self.proj(attn_output)
+ return attn_output, attn_weights
+
+
+class PPFormulaNetMultiModalProjector(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.conv1 = nn.Conv2d(
+ config.post_conv_in_channels, config.post_conv_mid_channels, kernel_size=3, stride=2, padding=1, bias=False
+ )
+ self.conv2 = nn.Conv2d(
+ config.post_conv_mid_channels,
+ config.post_conv_out_channels,
+ kernel_size=3,
+ stride=2,
+ padding=1,
+ bias=False,
+ )
+ self.linear_1 = nn.Linear(config.post_conv_out_channels, config.post_conv_out_channels)
+ self.linear_2 = nn.Linear(config.post_conv_out_channels, config.decoder_hidden_size)
+
+ def forward(self, hidden_states: torch.Tensor, **kwargs: Unpack[TransformersKwargs]):
+ hidden_states = self.conv1(hidden_states)
+ hidden_states = self.conv2(hidden_states)
+ hidden_states = hidden_states.flatten(2).transpose(1, 2)
+ hidden_states = self.linear_1(hidden_states)
+ hidden_states = self.linear_2(hidden_states)
+ return hidden_states
+
+
+class PPFormulaNetMLPBlock(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.lin1 = nn.Linear(config.hidden_size, config.mlp_dim)
+ self.lin2 = nn.Linear(config.mlp_dim, config.hidden_size)
+ self.act = ACT2FN[config.hidden_act]
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.lin1(hidden_states)
+ hidden_states = self.act(hidden_states)
+ hidden_states = self.lin2(hidden_states)
+ return hidden_states
+
+
+class PPFormulaNetVisionLayer(GradientCheckpointingLayer):
+ def __init__(self, config, window_size):
+ super().__init__()
+ self.layer_norm1 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.attn = PPFormulaNetVisionAttention(config, window_size)
+ self.layer_norm2 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.mlp = PPFormulaNetMLPBlock(config)
+ self.window_size = window_size
+
+ def window_partition(self, hidden_states: torch.Tensor, window_size: int) -> tuple[torch.Tensor, tuple[int, int]]:
+ """
+ Args:
+ Partition into non-overlapping windows with padding if needed.
+ hidden_states (tensor): input tokens with [batch_size, height, width, channel]. window_size (int): window
+ size.
+
+ Returns:
+ windows: windows after partition with [batch_size * num_windows, window_size, window_size, channel].
+ (pad_height, pad_width): padded height and width before partition
+ """
+ batch_size, height, width, channel = hidden_states.shape
+
+ pad_h = (window_size - height % window_size) % window_size
+ pad_w = (window_size - width % window_size) % window_size
+ hidden_states = F.pad(hidden_states, (0, 0, 0, pad_w, 0, pad_h))
+ pad_height, pad_width = height + pad_h, width + pad_w
+
+ hidden_states = hidden_states.reshape(
+ batch_size, pad_height // window_size, window_size, pad_width // window_size, window_size, channel
+ )
+ windows = hidden_states.permute(0, 1, 3, 2, 4, 5).contiguous().reshape(-1, window_size, window_size, channel)
+ return windows, (pad_height, pad_width)
+
+ def window_unpartition(
+ self, windows: torch.Tensor, window_size: int, padding_shape: tuple[int, int], original_shape: tuple[int, int]
+ ) -> torch.Tensor:
+ """
+ Args:
+ Window unpartition into original sequences and removing padding.
+ hidden_states (tensor):
+ input tokens with [batch_size * num_windows, window_size, window_size, channel].
+ window_size (int):
+ window size.
+ padding_shape (Tuple):
+ padded height and width (pad_height, pad_width).
+ original_shape (Tuple): original height and width (height, width) before padding.
+
+ Returns:
+ hidden_states: unpartitioned sequences with [batch_size, height, width, channel].
+ """
+ pad_height, pad_width = padding_shape
+ height, width = original_shape
+ batch_size = windows.shape[0] // (pad_height * pad_width // window_size // window_size)
+ hidden_states = windows.reshape(
+ batch_size, pad_height // window_size, pad_width // window_size, window_size, window_size, -1
+ )
+ hidden_states = (
+ hidden_states.permute(0, 1, 3, 2, 4, 5).contiguous().reshape(batch_size, pad_height, pad_width, -1)
+ )
+
+ hidden_states = hidden_states[:, :height, :width, :].contiguous()
+ return hidden_states
+
+ def forward(self, hidden_states: torch.Tensor) -> tuple[torch.FloatTensor]:
+ residual = hidden_states
+ hidden_states = self.layer_norm1(hidden_states)
+ # Window partition
+ if self.window_size > 0:
+ height, width = hidden_states.shape[1], hidden_states.shape[2]
+ hidden_states, padding_shape = self.window_partition(hidden_states, self.window_size)
+
+ hidden_states, attn_weights = self.attn(
+ hidden_states=hidden_states,
+ )
+ # Reverse window partition
+ if self.window_size > 0:
+ hidden_states = self.window_unpartition(hidden_states, self.window_size, padding_shape, (height, width))
+
+ hidden_states = residual + hidden_states
+ layernorm_output = self.layer_norm2(hidden_states)
+ hidden_states = hidden_states + self.mlp(layernorm_output)
+ return hidden_states
+
+
+class PPFormulaNetPatchEmbeddings(nn.Module):
+ """
+ This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
+ `hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
+ Transformer.
+ """
+
+ def __init__(self, config):
+ super().__init__()
+ image_size, patch_size = config.image_size, config.patch_size
+ num_channels, hidden_size = config.num_channels, config.hidden_size
+ image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
+ patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
+ num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
+ self.image_size = image_size
+ self.patch_size = patch_size
+ self.num_channels = num_channels
+ self.num_patches = num_patches
+
+ self.projection = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=patch_size)
+
+ def forward(self, pixel_values):
+ batch_size, num_channels, height, width = pixel_values.shape
+ if num_channels != self.num_channels:
+ raise ValueError(
+ "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
+ )
+ if height != self.image_size[0] or width != self.image_size[1]:
+ raise ValueError(
+ f"Input image size ({height}*{width}) doesn't match model ({self.image_size[0]}*{self.image_size[1]})."
+ )
+ embeddings = self.projection(pixel_values).permute(0, 2, 3, 1)
+ return embeddings
+
+
+class PPFormulaNetLayerNorm(nn.LayerNorm):
+ r"""LayerNorm that supports two data formats: channels_last (default) or channels_first.
+ The ordering of the dimensions in the inputs. channels_last corresponds to inputs with shape (batch_size, height,
+ width, channels) while channels_first corresponds to inputs with shape (batch_size, channels, height, width).
+ """
+
+ def __init__(self, normalized_shape, *, eps=1e-6, data_format="channels_last", **kwargs):
+ super().__init__(normalized_shape, eps=eps, **kwargs)
+ if data_format not in ["channels_last", "channels_first"]:
+ raise NotImplementedError(f"Unsupported data format: {data_format}")
+ self.data_format = data_format
+
+ def forward(self, features: torch.Tensor) -> torch.Tensor:
+ """
+ Args:
+ features: Tensor of shape (batch_size, channels, height, width) OR (batch_size, height, width, channels)
+ """
+ if self.data_format == "channels_first":
+ features = features.permute(0, 2, 3, 1)
+ features = super().forward(features)
+ features = features.permute(0, 3, 1, 2)
+ else:
+ features = super().forward(features)
+ return features
+
+
+class PPFormulaNetVisionNeck(nn.Module):
+ def __init__(self, config: PPFormulaNetVisionConfig):
+ super().__init__()
+ self.config = config
+
+ self.conv1 = nn.Conv2d(config.hidden_size, config.output_channels, kernel_size=1, bias=False)
+ self.layer_norm1 = PPFormulaNetLayerNorm(config.output_channels, data_format="channels_first")
+ self.conv2 = nn.Conv2d(config.output_channels, config.output_channels, kernel_size=3, padding=1, bias=False)
+ self.layer_norm2 = PPFormulaNetLayerNorm(config.output_channels, data_format="channels_first")
+
+ def forward(self, hidden_states):
+ hidden_states = hidden_states.permute(0, 3, 1, 2)
+ hidden_states = self.conv1(hidden_states)
+ hidden_states = self.layer_norm1(hidden_states)
+
+ hidden_states = self.conv2(hidden_states)
+ hidden_states = self.layer_norm2(hidden_states)
+ return hidden_states
+
+
+class PPFormulaNetVisionModel(PPFormulaNetPreTrainedModel):
+ _can_record_outputs = {"hidden_states": PPFormulaNetVisionLayer, "attentions": PPFormulaNetVisionAttention}
+ input_modalities = ("image",)
+
+ def __init__(self, config: PPFormulaNetVisionConfig):
+ super().__init__(config)
+ self.config = config
+ self.image_size = config.image_size
+ self.patch_embed = PPFormulaNetPatchEmbeddings(config)
+
+ self.pos_embed = None
+ if config.use_abs_pos:
+ # Initialize absolute positional embedding with pretrain image size.
+ self.pos_embed = nn.Parameter(
+ torch.zeros(
+ 1,
+ config.image_size // config.patch_size,
+ config.image_size // config.patch_size,
+ config.hidden_size,
+ )
+ )
+
+ self.layers = nn.ModuleList()
+ for i in range(config.num_hidden_layers):
+ layer = PPFormulaNetVisionLayer(
+ config,
+ window_size=config.window_size if i not in config.global_attn_indexes else 0,
+ )
+ self.layers.append(layer)
+
+ self.neck = PPFormulaNetVisionNeck(config)
+
+ self.gradient_checkpointing = False
+ self.multi_modal_projector = PPFormulaNetMultiModalProjector(config)
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.patch_embed
+
+ @merge_with_config_defaults
+ @capture_outputs(tie_last_hidden_states=False)
+ def forward(
+ self, pixel_values: torch.FloatTensor | None = None, **kwargs: Unpack[TransformersKwargs]
+ ) -> tuple | BaseModelOutputWithPooling:
+ if pixel_values is None:
+ raise ValueError("You have to specify pixel_values")
+
+ hidden_states = self.patch_embed(pixel_values)
+ if self.pos_embed is not None:
+ hidden_states = hidden_states + self.pos_embed
+ for layer_module in self.layers:
+ hidden_states = layer_module(hidden_states)
+ hidden_states = self.neck(hidden_states)
+ pooler_output = self.multi_modal_projector(hidden_states)
+
+ return BaseModelOutputWithPooling(
+ last_hidden_state=hidden_states,
+ pooler_output=pooler_output,
+ )
+
+
+class PPFormulaNetLearnedPositionalEmbedding(nn.Embedding):
+ """
+ This module learns positional embeddings up to a fixed maximum size.
+ """
+
+ def __init__(self, num_embeddings: int, embedding_dim: int):
+ # PPFormulaNet is set up so that if padding_idx is specified then offset the embedding ids by 2
+ # and adjust num_embeddings appropriately. Other models don't have this hack
+ self.offset = 2
+ super().__init__(num_embeddings + self.offset, embedding_dim)
+
+ def forward(
+ self, input_ids: torch.Tensor, past_key_values_length: int = 0, position_ids: torch.Tensor | None = None
+ ):
+ """`input_ids' shape is expected to be [bsz x seqlen]."""
+
+ if position_ids is None:
+ bsz, seq_len = input_ids.shape[:2]
+ position_ids = torch.arange(
+ past_key_values_length, past_key_values_length + seq_len, dtype=torch.long, device=self.weight.device
+ ).expand(bsz, -1)
+ else:
+ position_ids = position_ids.unsqueeze(0)
+
+ return super().forward(position_ids + self.offset)
+
+
+class PPFormulaNetScaledWordEmbedding(nn.Embedding):
+ """
+ This module overrides nn.Embeddings' forward by multiplying with embeddings scale.
+ """
+
+ def __init__(self, num_embeddings: int, embedding_dim: int, padding_idx: int, embed_scale: float | None = 1.0):
+ super().__init__(num_embeddings, embedding_dim, padding_idx)
+ self.embed_scale = embed_scale
+
+ def forward(self, input_ids: torch.Tensor):
+ return super().forward(input_ids) * self.embed_scale
+
+
+def eager_attention_forward(
+ module: nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: torch.Tensor | None,
+ scaling: float | None = None,
+ dropout: float = 0.0,
+ **kwargs: Unpack[TransformersKwargs],
+):
+ if scaling is None:
+ scaling = query.size(-1) ** -0.5
+
+ # Take the dot product between "query" and "key" to get the raw attention scores.
+ attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
+
+ if attention_mask is not None:
+ attn_weights = attn_weights + attention_mask
+
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
+
+ attn_output = torch.matmul(attn_weights, value)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+
+ return attn_output, attn_weights
+
+
+class PPFormulaNetAttention(nn.Module):
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
+
+ def __init__(
+ self,
+ embed_dim: int,
+ num_heads: int,
+ dropout: float = 0.0,
+ is_decoder: bool = False,
+ bias: bool = True,
+ is_causal: bool = False,
+ config: PPFormulaNetConfig | None = None,
+ layer_idx: int | None = None,
+ ):
+ super().__init__()
+ self.embed_dim = embed_dim
+ self.num_heads = num_heads
+ self.dropout = dropout
+ self.head_dim = embed_dim // num_heads
+ self.config = config
+
+ if (self.head_dim * num_heads) != self.embed_dim:
+ raise ValueError(
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
+ f" and `num_heads`: {num_heads})."
+ )
+ self.scaling = self.head_dim**-0.5
+ self.is_decoder = is_decoder
+ self.is_causal = is_causal
+ self.layer_idx = layer_idx
+ if layer_idx is None and self.is_decoder:
+ logger.warning_once(
+ f"Instantiating a decoder {self.__class__.__name__} without passing `layer_idx` is not recommended and "
+ "will lead to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
+ "when creating this class."
+ )
+
+ self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
+ self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ key_value_states: torch.Tensor | None = None,
+ past_key_values: Cache | None = None,
+ attention_mask: torch.Tensor | None = None,
+ # TODO: we need a refactor so that the different attention modules can get their specific kwargs
+ # ATM, we have mixed things encoder, decoder, and encoder-decoder attn
+ **kwargs: Unpack[FlashAttentionKwargs],
+ ) -> tuple[torch.Tensor, torch.Tensor | None]:
+ """Input shape: Batch x Time x Channel"""
+
+ # if key_value_states are provided this layer is used as a cross-attention layer
+ # for the decoder
+ is_cross_attention = key_value_states is not None
+
+ # determine input shapes
+ input_shape = hidden_states.shape[:-1]
+
+ hidden_shape = (*input_shape, -1, self.head_dim)
+
+ # get query proj
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+
+ is_updated = False
+ if past_key_values is not None:
+ if isinstance(past_key_values, EncoderDecoderCache):
+ is_updated = past_key_values.is_updated.get(self.layer_idx)
+ if is_cross_attention:
+ # after the first generated id, we can subsequently re-use all key/value_states from cache
+ curr_past_key_values = past_key_values.cross_attention_cache
+ else:
+ curr_past_key_values = past_key_values.self_attention_cache
+ else:
+ curr_past_key_values = past_key_values
+
+ current_states = key_value_states if is_cross_attention else hidden_states
+ if is_cross_attention and past_key_values is not None and is_updated:
+ # reuse k,v, cross_attentions
+ key_states = curr_past_key_values.layers[self.layer_idx].keys
+ value_states = curr_past_key_values.layers[self.layer_idx].values
+ else:
+ key_states = self.k_proj(current_states)
+ value_states = self.v_proj(current_states)
+ kv_shape = (*current_states.shape[:-1], -1, self.head_dim)
+ key_states = key_states.view(kv_shape).transpose(1, 2)
+ value_states = value_states.view(kv_shape).transpose(1, 2)
+
+ if past_key_values is not None:
+ key_states, value_states = curr_past_key_values.update(key_states, value_states, self.layer_idx)
+ # set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls
+ if is_cross_attention and isinstance(past_key_values, EncoderDecoderCache):
+ past_key_values.is_updated[self.layer_idx] = True
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_states,
+ key_states,
+ value_states,
+ attention_mask,
+ dropout=0.0 if not self.training else self.dropout,
+ scaling=self.scaling,
+ **kwargs,
+ )
+
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ attn_output = self.out_proj(attn_output)
+
+ return attn_output, attn_weights
+
+
+class PPFormulaNetDecoderLayer(GradientCheckpointingLayer):
+ def __init__(self, config: PPFormulaNetConfig, layer_idx: int | None = None):
+ super().__init__()
+ self.embed_dim = config.d_model
+
+ self.self_attn = PPFormulaNetAttention(
+ embed_dim=self.embed_dim,
+ num_heads=config.decoder_attention_heads,
+ dropout=config.attention_dropout,
+ is_decoder=True,
+ is_causal=True,
+ config=config,
+ layer_idx=layer_idx,
+ )
+ self.dropout = config.dropout
+ self.activation_fn = ACT2FN[config.activation_function]
+ self.activation_dropout = config.activation_dropout
+
+ self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
+ self.encoder_attn = PPFormulaNetAttention(
+ self.embed_dim,
+ config.decoder_attention_heads,
+ dropout=config.attention_dropout,
+ is_decoder=True,
+ config=config,
+ layer_idx=layer_idx,
+ )
+ self.encoder_attn_layer_norm = nn.LayerNorm(self.embed_dim)
+ self.fc1 = nn.Linear(self.embed_dim, config.decoder_ffn_dim)
+ self.fc2 = nn.Linear(config.decoder_ffn_dim, self.embed_dim)
+ self.final_layer_norm = nn.LayerNorm(self.embed_dim)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor | None = None,
+ encoder_hidden_states: torch.Tensor | None = None,
+ encoder_attention_mask: torch.Tensor | None = None,
+ past_key_values: Cache | None = None,
+ use_cache: bool | None = True,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.Tensor:
+ """
+ Args:
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
+ attention_mask (`torch.FloatTensor`): attention mask of size
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
+ encoder_hidden_states (`torch.FloatTensor`):
+ cross attention input to the layer of shape `(batch, seq_len, embed_dim)`
+ encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
+ past_key_values (`Cache`): cached past key and value projection states
+ """
+ residual = hidden_states
+ hidden_states = self.self_attn_layer_norm(hidden_states)
+
+ # Self Attention
+ hidden_states, _ = self.self_attn(
+ hidden_states=hidden_states,
+ past_key_values=past_key_values,
+ attention_mask=attention_mask,
+ **kwargs,
+ )
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
+ hidden_states = residual + hidden_states
+
+ # Cross-Attention Block
+ if encoder_hidden_states is not None:
+ residual = hidden_states
+ hidden_states = self.encoder_attn_layer_norm(hidden_states)
+
+ hidden_states, _ = self.encoder_attn(
+ hidden_states=hidden_states,
+ key_value_states=encoder_hidden_states,
+ attention_mask=encoder_attention_mask,
+ past_key_values=past_key_values,
+ **kwargs,
+ )
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
+ hidden_states = residual + hidden_states
+
+ # Fully Connected
+ residual = hidden_states
+ hidden_states = self.final_layer_norm(hidden_states)
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
+ hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
+ hidden_states = self.fc2(hidden_states)
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
+ hidden_states = residual + hidden_states
+
+ return hidden_states
+
+
+@auto_docstring
+class PPFormulaNetTextModel(PPFormulaNetPreTrainedModel):
+ """
+ Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`PPFormulaNetTextModelLayer`]
+
+ Args:
+ config: PPFormulaNetConfig
+ embed_tokens (nn.Embedding): output embedding
+ """
+
+ _can_record_outputs = {
+ "hidden_states": PPFormulaNetDecoderLayer,
+ "attentions": OutputRecorder(PPFormulaNetAttention, index=1, layer_name="self_attn"),
+ "cross_attentions": OutputRecorder(PPFormulaNetAttention, index=1, layer_name="encoder_attn"),
+ }
+
+ def __init__(self, config: PPFormulaNetConfig):
+ super().__init__(config)
+ self.dropout = config.dropout
+ self.layerdrop = config.decoder_layerdrop
+ self.padding_idx = config.pad_token_id
+ self.max_target_positions = config.max_position_embeddings
+ embed_scale = math.sqrt(config.d_model) if config.scale_embedding else 1.0
+
+ self.embed_tokens = PPFormulaNetScaledWordEmbedding(
+ config.vocab_size, config.d_model, self.padding_idx, embed_scale=embed_scale
+ )
+
+ self.embed_positions = PPFormulaNetLearnedPositionalEmbedding(
+ config.max_position_embeddings,
+ config.d_model,
+ )
+ self.layers = nn.ModuleList(
+ [PPFormulaNetDecoderLayer(config, layer_idx=i) for i in range(config.decoder_layers)]
+ )
+ self.config = config
+
+ self.layernorm_embedding = nn.LayerNorm(config.d_model)
+ self.layer_norm = nn.LayerNorm(config.d_model)
+
+ self.gradient_checkpointing = False
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @merge_with_config_defaults
+ @capture_outputs
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ encoder_attention_mask: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ use_cache: bool | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutputWithPastAndCrossAttentions:
+ r"""
+ Args:
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
+ provide it.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input-ids)
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
+
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+
+ [What are attention masks?](../glossary#attention-mask)
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
+ of the decoder.
+ encoder_attention_mask (`torch.LongTensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):
+ Mask to avoid performing cross-attention on padding tokens indices of encoder input_ids. Mask values
+ selected in `[0, 1]`:
+
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+
+ [What are attention masks?](../glossary#attention-mask)
+ past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
+ It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
+
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
+ cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
+
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
+ that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
+ all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
+ than the model's internal embedding lookup matrix.
+ """
+ if (input_ids is None) ^ (inputs_embeds is not None):
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
+
+ if inputs_embeds is None:
+ inputs_embeds = self.embed_tokens(input_ids)
+
+ # initialize `past_key_values`
+ if use_cache and past_key_values is None:
+ past_key_values = (
+ EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache(config=self.config))
+ if encoder_hidden_states is not None or self.config.is_encoder_decoder
+ else DynamicCache(config=self.config)
+ )
+
+ batch_size, seq_length = inputs_embeds.size()[:-1]
+ past_key_values_length = past_key_values.get_seq_length() if past_key_values is not None else 0
+ position_ids = torch.arange(seq_length, device=inputs_embeds.device) + past_key_values_length
+
+ if attention_mask is None and not is_torchdynamo_compiling():
+ # required mask seq length can be calculated via length of past cache
+ mask_seq_length = past_key_values_length + seq_length
+ attention_mask = torch.ones(batch_size, mask_seq_length, device=inputs_embeds.device)
+
+ self_attn_cache = (
+ past_key_values.self_attention_cache
+ if isinstance(past_key_values, EncoderDecoderCache)
+ else past_key_values
+ )
+
+ causal_mask = create_causal_mask(
+ config=self.config,
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ past_key_values=self_attn_cache,
+ )
+ encoder_attention_mask = create_bidirectional_mask(
+ config=self.config,
+ inputs_embeds=inputs_embeds,
+ attention_mask=encoder_attention_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ )
+
+ # embed positions
+ position_ids = self.embed_positions(input_ids, past_key_values_length, position_ids=position_ids)
+
+ hidden_states = inputs_embeds + position_ids.to(inputs_embeds.device)
+ hidden_states = self.layernorm_embedding(hidden_states)
+
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
+
+ for idx, decoder_layer in enumerate(self.layers):
+ # add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
+ if self.training:
+ dropout_probability = torch.rand([])
+ if dropout_probability < self.layerdrop:
+ continue
+
+ hidden_states = decoder_layer(
+ hidden_states,
+ causal_mask,
+ encoder_hidden_states, # as a positional argument for gradient checkpointing
+ encoder_attention_mask=encoder_attention_mask,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ **kwargs,
+ )
+
+ hidden_states = self.layer_norm(hidden_states)
+
+ return BaseModelOutputWithPastAndCrossAttentions(
+ last_hidden_state=hidden_states,
+ past_key_values=past_key_values,
+ )
+
+
+def shift_tokens_right(input_ids: torch.Tensor, pad_token_id: int):
+ """
+ Shift input ids one token to the right, and wrap the last non pad token (the token) Note that PPFormulaNet does not
+ have a single `decoder_start_token_id` in contrast to other Bart-like models.
+ """
+ prev_output_tokens = input_ids.clone()
+
+ if pad_token_id is None:
+ raise ValueError("self.model.config.pad_token_id has to be defined.")
+ # replace possible -100 values in labels by `pad_token_id`
+ prev_output_tokens.masked_fill_(prev_output_tokens == -100, pad_token_id)
+
+ index_of_eos = (prev_output_tokens.ne(pad_token_id).sum(dim=1) - 1).unsqueeze(-1)
+ decoder_start_tokens = prev_output_tokens.gather(1, index_of_eos).squeeze()
+ prev_output_tokens[:, 1:] = prev_output_tokens[:, :-1].clone()
+ prev_output_tokens[:, 0] = decoder_start_tokens
+
+ return prev_output_tokens
+
+
+class PPFormulaNetModel(PPFormulaNetPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.decoder = PPFormulaNetTextModel(config.text_config)
+ self.encoder = PPFormulaNetVisionModel(config=config.vision_config)
+
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: torch.FloatTensor | None = None,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor
+ | None = None, # Kept in the signature for compatibility to avoid duplicate-keyword errors.
+ decoder_input_ids: torch.LongTensor | None = None,
+ decoder_attention_mask: torch.LongTensor | None = None,
+ decoder_inputs_embeds: torch.FloatTensor | None = None,
+ encoder_outputs: list[torch.FloatTensor] | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor
+ | None = None, # Kept in the signature for compatibility to avoid duplicate-keyword errors.
+ use_cache: bool | None = None,
+ **kwargs,
+ ) -> tuple | Seq2SeqModelOutput:
+ if decoder_input_ids is None and decoder_inputs_embeds is None:
+ decoder_input_ids = shift_tokens_right(input_ids, self.config.text_config.pad_token_id)
+
+ if (encoder_outputs is None) ^ (pixel_values is not None):
+ raise ValueError("You must specify exactly one of encoder_outputs or pixel_values")
+
+ if encoder_outputs is None:
+ encoder_outputs: BaseModelOutputWithPooling = self.encoder(
+ pixel_values=pixel_values,
+ **kwargs,
+ )
+ elif not isinstance(encoder_outputs, BaseModelOutputWithPooling):
+ encoder_outputs = BaseModelOutputWithPooling(
+ last_hidden_state=encoder_outputs[0],
+ pooler_output=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
+ hidden_states=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
+ attentions=encoder_outputs[3] if len(encoder_outputs) > 3 else None,
+ )
+
+ decoder_outputs = self.decoder(
+ input_ids=decoder_input_ids,
+ attention_mask=decoder_attention_mask,
+ encoder_hidden_states=encoder_outputs.pooler_output,
+ past_key_values=past_key_values,
+ inputs_embeds=decoder_inputs_embeds,
+ use_cache=use_cache,
+ **kwargs,
+ )
+
+ return Seq2SeqModelOutput(
+ last_hidden_state=decoder_outputs.last_hidden_state,
+ past_key_values=decoder_outputs.past_key_values,
+ decoder_hidden_states=decoder_outputs.hidden_states,
+ decoder_attentions=decoder_outputs.attentions,
+ cross_attentions=decoder_outputs.cross_attentions,
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
+ encoder_hidden_states=encoder_outputs.hidden_states,
+ encoder_attentions=encoder_outputs.attentions,
+ )
+
+
+@auto_docstring
+class PPFormulaNetForConditionalGeneration(PPFormulaNetPreTrainedModel, GenerationMixin):
+ _tied_weights_keys = {}
+
+ def __init__(self, config: PPFormulaNetConfig):
+ super().__init__(config)
+ self.model = PPFormulaNetModel(config)
+ self.lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.vocab_size, bias=False)
+ self.post_init()
+
+ def get_output_embeddings(self) -> nn.Module:
+ return self.lm_head
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: torch.FloatTensor | None = None,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ decoder_input_ids: torch.LongTensor | None = None,
+ decoder_attention_mask: torch.LongTensor | None = None,
+ encoder_outputs: list[torch.FloatTensor] | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ decoder_inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ use_cache: bool | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | Seq2SeqLMOutput:
+ r"""
+ Example:
+
+ ```python
+ >>> from io import BytesIO
+
+ >>> import httpx
+ >>> from PIL import Image
+ >>> from transformers import AutoProcessor, PPFormulaNetForConditionalGeneration
+
+ >>> model_path = "PaddlePaddle/PP-FormulaNet_plus-L_safetensors" # or "PaddlePaddle/PP-FormulaNet-L_safetensors"
+ >>> model = PPFormulaNetForConditionalGeneration.from_pretrained(model_path, device_map="auto")
+ >>> processor = AutoProcessor.from_pretrained(model_path)
+
+ >>> image_url = "https://paddle-model-ecology.bj.bcebos.com/paddlex/imgs/demo_image/general_formula_rec_001.png"
+ >>> image = Image.open(BytesIO(httpx.get(image_url).content)).convert("RGB")
+ >>> inputs = processor(images=image, return_tensors="pt").to(model.device)
+ >>> outputs = model(**inputs)
+ >>> result = processor.post_process(outputs)
+ >>> print(result)
+ ['\\zeta_{0}(\\nu)=-\\frac{\\nu\\varrho^{-2\\nu}}{\\pi}\\int_{\\mu}^{\\infty}d\\omega\\int_{C_{+}}d z\\frac{2z^{2}}{(z^{2}+\\omega^{2})^{\\nu+1}}\\breve{\\Psi}(\\omega;z)e^{i\\epsilon z}\\quad,']
+ ```"""
+ outputs = self.model(
+ input_ids=input_ids,
+ pixel_values=pixel_values,
+ attention_mask=attention_mask,
+ decoder_input_ids=decoder_input_ids,
+ encoder_outputs=encoder_outputs,
+ decoder_attention_mask=decoder_attention_mask,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ decoder_inputs_embeds=decoder_inputs_embeds,
+ use_cache=use_cache,
+ **kwargs,
+ )
+
+ hidden_states = outputs[0]
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(
+ logits=logits, labels=labels, vocab_size=self.config.text_config.vocab_size, **kwargs
+ )
+
+ return Seq2SeqLMOutput(
+ loss=loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ decoder_hidden_states=outputs.decoder_hidden_states,
+ decoder_attentions=outputs.decoder_attentions,
+ cross_attentions=outputs.cross_attentions,
+ encoder_last_hidden_state=outputs.encoder_last_hidden_state,
+ encoder_hidden_states=outputs.encoder_hidden_states,
+ encoder_attentions=outputs.encoder_attentions,
+ )
+
+ def prepare_inputs_for_generation(
+ self,
+ input_ids,
+ past_key_values=None,
+ inputs_embeds=None,
+ pixel_values=None,
+ attention_mask=None,
+ logits_to_keep=None,
+ is_first_iteration=False,
+ **kwargs,
+ ):
+ # Overwritten -- in specific circumstances we don't want to forward image inputs to the model
+
+ model_inputs = super().prepare_inputs_for_generation(
+ input_ids,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ logits_to_keep=logits_to_keep,
+ is_first_iteration=is_first_iteration,
+ **kwargs,
+ )
+
+ if is_first_iteration or not kwargs.get("use_cache", True):
+ # Pixel values are used only in the first iteration if available
+ # In subsequent iterations, they are already merged with text and cached
+ # NOTE: first iteration doesn't have to be prefill, it can be the first
+ # iteration with a question and cached system prompt (continue generate from cache)
+ model_inputs["pixel_values"] = pixel_values
+
+ return model_inputs
+
+ # override this function to compatible with `_prepare_encoder_decoder_kwargs_for_generation`
+ def get_encoder(self):
+ return self.model.get_encoder()
+
+
+__all__ = [
+ "PPFormulaNetModel",
+ "PPFormulaNetTextModel",
+ "PPFormulaNetVisionModel",
+ "PPFormulaNetForConditionalGeneration",
+ "PPFormulaNetPreTrainedModel",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pp_formulanet/modular_pp_formulanet.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pp_formulanet/modular_pp_formulanet.py
new file mode 100644
index 0000000000000000000000000000000000000000..743c15a7dad6ead020ee9d34b0aa52acd89bdeee
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pp_formulanet/modular_pp_formulanet.py
@@ -0,0 +1,532 @@
+# Copyright 2026 The PaddlePaddle Team and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import re
+from dataclasses import dataclass
+
+import torch
+import torch.nn as nn
+from huggingface_hub.dataclasses import strict
+
+from ... import initialization as init
+from ...cache_utils import Cache
+from ...configuration_utils import PreTrainedConfig
+from ...image_processing_utils import BatchFeature
+from ...image_utils import (
+ ImageInput,
+)
+from ...modeling_outputs import (
+ BaseModelOutputWithPooling,
+ Seq2SeqLMOutput,
+ Seq2SeqModelOutput,
+)
+from ...modeling_utils import PreTrainedModel
+from ...processing_utils import (
+ ProcessingKwargs,
+ Unpack,
+)
+from ...utils import (
+ TransformersKwargs,
+ auto_docstring,
+ can_return_tuple,
+ logging,
+)
+from ...utils.generic import merge_with_config_defaults
+from ...utils.import_utils import requires
+from ...utils.output_capturing import capture_outputs
+from ..florence2.modeling_florence2 import Florence2ForConditionalGeneration
+from ..mbart.configuration_mbart import MBartConfig
+from ..mbart.modeling_mbart import MBartDecoder, shift_tokens_right
+from ..nougat.image_processing_nougat import NougatImageProcessor
+from ..nougat.processing_nougat import NougatProcessor
+from ..slanext.configuration_slanext import SLANeXtVisionConfig
+from ..slanext.modeling_slanext import (
+ SLANeXtPreTrainedModel,
+ SLANeXtVisionAttention,
+ SLANeXtVisionEncoder,
+)
+
+
+logger = logging.get_logger(__name__)
+
+
+@auto_docstring(checkpoint="PaddlePaddle/PPFormulaNet_plus-L_safetensors")
+@strict
+class PPFormulaNetVisionConfig(SLANeXtVisionConfig):
+ r"""
+ output_channels (`int`, *optional*, defaults to 256):
+ Dimensionality of the output channels in the Patch Encoder.
+ window_size (`int`, *optional*, defaults to 14):
+ Window size for relative position.
+ global_attn_indexes (`list[int]`, *optional*, defaults to `[2, 5, 8, 11]`):
+ The indexes of the global attention layers.
+ mlp_dim (`int`, *optional*, defaults to 3072):
+ The dimensionality of the MLP layer in the Transformer encoder.
+ post_conv_in_channels (`int`, *optional*, defaults to 256):
+ Number of input channels for the post-encoder convolution layer.
+ post_conv_out_channels (`int`, *optional*, defaults to 1024):
+ Number of output channels for the post-encoder convolution layer.
+ post_conv_mid_channels (`int`, *optional*, defaults to 512):
+ Number of intermediate channels for the post-encoder convolution layer.
+ decoder_hidden_size (`int`, *optional*, defaults to 512):
+ The hidden size of the decoder that the encoder features are projected to.
+ """
+
+ post_conv_in_channels: int = 256
+ post_conv_out_channels: int = 1024
+ post_conv_mid_channels: int = 512
+ decoder_hidden_size: int = 512
+
+
+@auto_docstring(checkpoint="PaddlePaddle/PPFormulaNet_plus-L_safetensors")
+@strict
+class PPFormulaNetTextConfig(MBartConfig):
+ base_config_key = "text_config"
+ vocab_size: int = 50000
+ max_position_embeddings: int = 2560
+ decoder_layers: int = 8
+ decoder_ffn_dim: int = 2048
+ d_model: int = 512
+ scale_embedding: bool = True
+ decoder_start_token_id: int | None = 2
+ tie_word_embeddings: bool = False
+ is_encoder_decoder: bool = True
+ classifier_dropout = AttributeError()
+ encoder_ffn_dim = AttributeError()
+ encoder_layerdrop = AttributeError()
+ is_decoder = AttributeError()
+
+
+@auto_docstring(checkpoint="PaddlePaddle/PPFormulaNet_plus-L_safetensors")
+@strict
+class PPFormulaNetConfig(PreTrainedConfig):
+ model_type = "pp_formulanet"
+ sub_configs = {"text_config": PPFormulaNetTextConfig, "vision_config": PPFormulaNetVisionConfig}
+
+ text_config: dict | PPFormulaNetTextConfig | None = None
+ vision_config: dict | PPFormulaNetVisionConfig | None = None
+ is_encoder_decoder: bool = True
+
+ def __post_init__(self, **kwargs):
+ if isinstance(self.text_config, dict):
+ self.text_config = PPFormulaNetTextConfig(**self.text_config)
+ elif self.text_config is None:
+ logger.info("text_config is None. Initializing the PPFormulaNetTextConfig with default values.")
+ self.text_config = PPFormulaNetTextConfig()
+
+ if isinstance(self.vision_config, dict):
+ self.vision_config = PPFormulaNetVisionConfig(**self.vision_config)
+ elif self.vision_config is None:
+ logger.info("vision_config is None. Initializing the PPFormulaNetVisionConfig with default values.")
+ self.vision_config = PPFormulaNetVisionConfig()
+
+ super().__post_init__(**kwargs)
+
+
+@auto_docstring
+@requires(backends=("torch",))
+class PPFormulaNetImageProcessor(NougatImageProcessor):
+ image_mean = [0.7931, 0.7931, 0.7931]
+ image_std = [0.1738, 0.1738, 0.1738]
+ size = {"height": 768, "width": 768}
+
+
+@auto_docstring
+class PPFormulaNetProcessor(NougatProcessor):
+ r"""
+ [`PPFormulaNetProcessor`] offers all the functionalities of [`PPFormulaNetImageProcessor`] and [`NougatTokenizer`]. See the
+ [`~PPFormulaNetProcessor.__call__`] and [`~PPFormulaNetProcessor.decode`] for more information.
+ """
+
+ def __init__(self, image_processor, tokenizer):
+ super().__init__(image_processor, tokenizer)
+
+ # normalize() regex
+ self._text_reg = re.compile(r"(\\(operatorname|mathrm|text|mathbf)\s?\*? {.*?})")
+ self._macro_pattern = re.compile(r"(\\[a-zA-Z]+)\s(?=\w)|\\[a-zA-Z]+\s(?=})")
+ self._protected_macros = {"\\operatorname", "\\mathrm", "\\text", "\\mathbf"}
+
+ letter = r"[a-zA-Z]"
+ noletter = r"[\W_^\d]"
+ self._rule_noletter_noletter = re.compile(r"(?!\\ )(%s)\s+?(%s)" % (noletter, noletter))
+ self._rule_noletter_letter = re.compile(r"(?!\\ )(%s)\s+?(%s)" % (noletter, letter))
+ self._rule_letter_noletter = re.compile(r"(%s)\s+?(%s)" % (letter, noletter))
+
+ # remove_chinese_text_wrapping() regex
+ self._chinese_text_wrapping_pattern = re.compile(r"\\text\s*{([^{}]*[\u4e00-\u9fff]+[^{}]*)}")
+
+ def __call__(
+ self,
+ images: ImageInput,
+ **kwargs: Unpack[ProcessingKwargs],
+ ) -> BatchFeature:
+ r"""
+ images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`):
+ The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
+ tensor. Both channels-first and channels-last formats are supported.
+
+ Returns:
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
+
+ - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
+ """
+ output_kwargs = self._merge_kwargs(
+ ProcessingKwargs,
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
+ **kwargs,
+ )
+
+ image_inputs = self.image_processor(images=images, **output_kwargs["images_kwargs"])
+ return BatchFeature({**image_inputs})
+
+ def normalize(self, text: str) -> str:
+ """Normalizes a string by removing unnecessary spaces."""
+ names = []
+ for x in self._text_reg.findall(text):
+ matches = self._macro_pattern.findall(x[0])
+ for m in matches:
+ if m not in self._protected_macros and m.strip() != "":
+ text = text.replace(m, m + "XXXXXXX")
+ text = text.replace(" ", "")
+ names.append(text)
+
+ if names:
+ text = self._text_reg.sub(lambda match: str(names.pop(0)), text)
+
+ new_text = text
+ while True:
+ text = new_text
+ new_text = self._rule_noletter_noletter.sub(r"\1\2", text)
+ new_text = self._rule_noletter_letter.sub(r"\1\2", new_text)
+ new_text = self._rule_letter_noletter.sub(r"\1\2", new_text)
+ if new_text == text:
+ break
+
+ return new_text.replace("XXXXXXX", " ")
+
+ def remove_chinese_text_wrapping(self, formula: str) -> str:
+ def replacer(match):
+ return match.group(1)
+
+ replaced_formula = self._chinese_text_wrapping_pattern.sub(replacer, formula)
+ return replaced_formula.replace('"', "")
+
+ def post_process_generation(self, text: str) -> str:
+ """Post-processes a string by fixing text and normalizing it.
+
+ Args:
+ text (str): String to post-process.
+
+ Returns:
+ str: Post-processed string.
+ """
+ text = self.remove_chinese_text_wrapping(text)
+ try:
+ from ftfy import fix_text
+
+ text = fix_text(text)
+ except ImportError:
+ logger.warning_once(
+ "ftfy is not installed, skipping fix_text. "
+ "Output may contain unnormalized unicode, extra spaces, or escaped artifacts"
+ )
+ text = self.normalize(text)
+ return text
+
+ def post_process(self, generated_outputs, skip_special_tokens=True, **kwargs):
+ """
+ Post-process the output of the model to decode the text.
+
+ Args:
+ generated_outputs (`torch.Tensor` or `np.ndarray`):
+ The output of the model `generate` function. The output is expected to be a tensor of shape `(batch_size, sequence_length)`
+ or `(sequence_length,)`.
+ skip_special_tokens (`bool`, *optional*, defaults to `True`):
+ Whether or not to remove special tokens in the output. Argument passed to the tokenizer's `batch_decode` method.
+ **kwargs:
+ Additional arguments to be passed to the tokenizer's `batch_decode method`.
+
+ Returns:
+ `list[str]`: The decoded text.
+ """
+ generated_texts = self.batch_decode(generated_outputs, skip_special_tokens=skip_special_tokens, **kwargs)
+ return [self.post_process_generation(text) for text in generated_texts]
+
+
+class PPFormulaNetPreTrainedModel(SLANeXtPreTrainedModel):
+ _keep_in_fp32_modules_strict = []
+ base_model_prefix = "model"
+ # Note this goes for the decoder only, the encoder will inherently always use eager attention
+ _supports_sdpa = True
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ """Initialize the weights"""
+ PreTrainedModel._init_weights(module)
+
+ # Initialize positional embeddings to zero (PPFormulaNetVisionModel holds pos_embed)
+ if isinstance(module, PPFormulaNetVisionModel):
+ if module.pos_embed is not None:
+ init.constant_(module.pos_embed, 0.0)
+
+ # Initialize relative positional embeddings to zero (PPFormulaNetVisionAttention holds rel_pos_h/w)
+ if isinstance(module, PPFormulaNetVisionAttention):
+ if module.use_rel_pos:
+ init.constant_(module.rel_pos_h, 0.0)
+ init.constant_(module.rel_pos_w, 0.0)
+
+
+# overrider for PPFormulaNetModel's encoder output
+@dataclass
+class PPFormulaNetVisionEncoderOutput(BaseModelOutputWithPooling):
+ pass
+
+
+class PPFormulaNetVisionAttention(SLANeXtVisionAttention):
+ pass
+
+
+class PPFormulaNetMultiModalProjector(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.conv1 = nn.Conv2d(
+ config.post_conv_in_channels, config.post_conv_mid_channels, kernel_size=3, stride=2, padding=1, bias=False
+ )
+ self.conv2 = nn.Conv2d(
+ config.post_conv_mid_channels,
+ config.post_conv_out_channels,
+ kernel_size=3,
+ stride=2,
+ padding=1,
+ bias=False,
+ )
+ self.linear_1 = nn.Linear(config.post_conv_out_channels, config.post_conv_out_channels)
+ self.linear_2 = nn.Linear(config.post_conv_out_channels, config.decoder_hidden_size)
+
+ def forward(self, hidden_states: torch.Tensor, **kwargs: Unpack[TransformersKwargs]):
+ hidden_states = self.conv1(hidden_states)
+ hidden_states = self.conv2(hidden_states)
+ hidden_states = hidden_states.flatten(2).transpose(1, 2)
+ hidden_states = self.linear_1(hidden_states)
+ hidden_states = self.linear_2(hidden_states)
+ return hidden_states
+
+
+class PPFormulaNetVisionModel(SLANeXtVisionEncoder):
+ def __init__(self, config: PPFormulaNetVisionConfig):
+ super().__init__()
+ self.multi_modal_projector = PPFormulaNetMultiModalProjector(config)
+
+ @merge_with_config_defaults
+ @capture_outputs(tie_last_hidden_states=False)
+ def forward(
+ self, pixel_values: torch.FloatTensor | None = None, **kwargs: Unpack[TransformersKwargs]
+ ) -> tuple | BaseModelOutputWithPooling:
+ if pixel_values is None:
+ raise ValueError("You have to specify pixel_values")
+
+ hidden_states = self.patch_embed(pixel_values)
+ if self.pos_embed is not None:
+ hidden_states = hidden_states + self.pos_embed
+ for layer_module in self.layers:
+ hidden_states = layer_module(hidden_states)
+ hidden_states = self.neck(hidden_states)
+ pooler_output = self.multi_modal_projector(hidden_states)
+
+ return BaseModelOutputWithPooling(
+ last_hidden_state=hidden_states,
+ pooler_output=pooler_output,
+ )
+
+
+@auto_docstring
+class PPFormulaNetTextModel(MBartDecoder):
+ pass
+
+
+class PPFormulaNetModel(PPFormulaNetPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.decoder = PPFormulaNetTextModel(config.text_config)
+ self.encoder = PPFormulaNetVisionModel(config=config.vision_config)
+
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: torch.FloatTensor | None = None,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor
+ | None = None, # Kept in the signature for compatibility to avoid duplicate-keyword errors.
+ decoder_input_ids: torch.LongTensor | None = None,
+ decoder_attention_mask: torch.LongTensor | None = None,
+ decoder_inputs_embeds: torch.FloatTensor | None = None,
+ encoder_outputs: list[torch.FloatTensor] | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor
+ | None = None, # Kept in the signature for compatibility to avoid duplicate-keyword errors.
+ use_cache: bool | None = None,
+ **kwargs,
+ ) -> tuple | Seq2SeqModelOutput:
+ if decoder_input_ids is None and decoder_inputs_embeds is None:
+ decoder_input_ids = shift_tokens_right(input_ids, self.config.text_config.pad_token_id)
+
+ if (encoder_outputs is None) ^ (pixel_values is not None):
+ raise ValueError("You must specify exactly one of encoder_outputs or pixel_values")
+
+ if encoder_outputs is None:
+ encoder_outputs: BaseModelOutputWithPooling = self.encoder(
+ pixel_values=pixel_values,
+ **kwargs,
+ )
+ elif not isinstance(encoder_outputs, BaseModelOutputWithPooling):
+ encoder_outputs = BaseModelOutputWithPooling(
+ last_hidden_state=encoder_outputs[0],
+ pooler_output=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
+ hidden_states=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
+ attentions=encoder_outputs[3] if len(encoder_outputs) > 3 else None,
+ )
+
+ decoder_outputs = self.decoder(
+ input_ids=decoder_input_ids,
+ attention_mask=decoder_attention_mask,
+ encoder_hidden_states=encoder_outputs.pooler_output,
+ past_key_values=past_key_values,
+ inputs_embeds=decoder_inputs_embeds,
+ use_cache=use_cache,
+ **kwargs,
+ )
+
+ return Seq2SeqModelOutput(
+ last_hidden_state=decoder_outputs.last_hidden_state,
+ past_key_values=decoder_outputs.past_key_values,
+ decoder_hidden_states=decoder_outputs.hidden_states,
+ decoder_attentions=decoder_outputs.attentions,
+ cross_attentions=decoder_outputs.cross_attentions,
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
+ encoder_hidden_states=encoder_outputs.hidden_states,
+ encoder_attentions=encoder_outputs.attentions,
+ )
+
+
+@auto_docstring
+class PPFormulaNetForConditionalGeneration(Florence2ForConditionalGeneration):
+ _tied_weights_keys = {}
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: torch.FloatTensor | None = None,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ decoder_input_ids: torch.LongTensor | None = None,
+ decoder_attention_mask: torch.LongTensor | None = None,
+ encoder_outputs: list[torch.FloatTensor] | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ decoder_inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ use_cache: bool | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | Seq2SeqLMOutput:
+ r"""
+ Example:
+
+ ```python
+ >>> from io import BytesIO
+
+ >>> import httpx
+ >>> from PIL import Image
+ >>> from transformers import AutoProcessor, PPFormulaNetForConditionalGeneration
+
+ >>> model_path = "PaddlePaddle/PP-FormulaNet_plus-L_safetensors" # or "PaddlePaddle/PP-FormulaNet-L_safetensors"
+ >>> model = PPFormulaNetForConditionalGeneration.from_pretrained(model_path, device_map="auto")
+ >>> processor = AutoProcessor.from_pretrained(model_path)
+
+ >>> image_url = "https://paddle-model-ecology.bj.bcebos.com/paddlex/imgs/demo_image/general_formula_rec_001.png"
+ >>> image = Image.open(BytesIO(httpx.get(image_url).content)).convert("RGB")
+ >>> inputs = processor(images=image, return_tensors="pt").to(model.device)
+ >>> outputs = model(**inputs)
+ >>> result = processor.post_process(outputs)
+ >>> print(result)
+ ['\\zeta_{0}(\\nu)=-\\frac{\\nu\\varrho^{-2\\nu}}{\\pi}\\int_{\\mu}^{\\infty}d\\omega\\int_{C_{+}}d z\\frac{2z^{2}}{(z^{2}+\\omega^{2})^{\\nu+1}}\\breve{\\Psi}(\\omega;z)e^{i\\epsilon z}\\quad,']
+ ```"""
+ outputs = self.model(
+ input_ids=input_ids,
+ pixel_values=pixel_values,
+ attention_mask=attention_mask,
+ decoder_input_ids=decoder_input_ids,
+ encoder_outputs=encoder_outputs,
+ decoder_attention_mask=decoder_attention_mask,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ decoder_inputs_embeds=decoder_inputs_embeds,
+ use_cache=use_cache,
+ **kwargs,
+ )
+
+ hidden_states = outputs[0]
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(
+ logits=logits, labels=labels, vocab_size=self.config.text_config.vocab_size, **kwargs
+ )
+
+ return Seq2SeqLMOutput(
+ loss=loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ decoder_hidden_states=outputs.decoder_hidden_states,
+ decoder_attentions=outputs.decoder_attentions,
+ cross_attentions=outputs.cross_attentions,
+ encoder_last_hidden_state=outputs.encoder_last_hidden_state,
+ encoder_hidden_states=outputs.encoder_hidden_states,
+ encoder_attentions=outputs.encoder_attentions,
+ )
+
+ # override this function to compatible with `_prepare_encoder_decoder_kwargs_for_generation`
+ def get_encoder(self):
+ return self.model.get_encoder()
+
+ def get_placeholder_mask(self):
+ raise AttributeError("The PPFormulaNet does not need placeholder mask.")
+
+ def get_image_features(self):
+ raise AttributeError("The PPFormulaNet does not need `get_image_features`.")
+
+ def _prepare_encoder_decoder_kwargs_for_generation(self):
+ raise AttributeError("The PPFormulaNet use default implementation.")
+
+
+__all__ = [
+ "PPFormulaNetProcessor",
+ "PPFormulaNetImageProcessor",
+ "PPFormulaNetConfig",
+ "PPFormulaNetTextConfig",
+ "PPFormulaNetModel",
+ "PPFormulaNetTextModel",
+ "PPFormulaNetVisionModel",
+ "PPFormulaNetVisionConfig",
+ "PPFormulaNetForConditionalGeneration",
+ "PPFormulaNetPreTrainedModel",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pp_formulanet/processing_pp_formulanet.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pp_formulanet/processing_pp_formulanet.py
new file mode 100644
index 0000000000000000000000000000000000000000..2c323289fb0587c48f2c970f91d53429d4c48c4a
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pp_formulanet/processing_pp_formulanet.py
@@ -0,0 +1,155 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/pp_formulanet/modular_pp_formulanet.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_pp_formulanet.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2026 The PaddlePaddle Team and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import re
+
+from ...image_processing_utils import BatchFeature
+from ...image_utils import ImageInput
+from ...processing_utils import ProcessingKwargs, ProcessorMixin, Unpack
+from ...utils import auto_docstring, logging
+
+
+logger = logging.get_logger(__name__)
+
+
+@auto_docstring
+class PPFormulaNetProcessor(ProcessorMixin):
+ r"""
+ [`PPFormulaNetProcessor`] offers all the functionalities of [`PPFormulaNetImageProcessor`] and [`NougatTokenizer`]. See the
+ [`~PPFormulaNetProcessor.__call__`] and [`~PPFormulaNetProcessor.decode`] for more information.
+ """
+
+ def __init__(self, image_processor, tokenizer):
+ super().__init__(image_processor, tokenizer)
+
+ # normalize() regex
+ self._text_reg = re.compile(r"(\\(operatorname|mathrm|text|mathbf)\s?\*? {.*?})")
+ self._macro_pattern = re.compile(r"(\\[a-zA-Z]+)\s(?=\w)|\\[a-zA-Z]+\s(?=})")
+ self._protected_macros = {"\\operatorname", "\\mathrm", "\\text", "\\mathbf"}
+
+ letter = r"[a-zA-Z]"
+ noletter = r"[\W_^\d]"
+ self._rule_noletter_noletter = re.compile(r"(?!\\ )(%s)\s+?(%s)" % (noletter, noletter))
+ self._rule_noletter_letter = re.compile(r"(?!\\ )(%s)\s+?(%s)" % (noletter, letter))
+ self._rule_letter_noletter = re.compile(r"(%s)\s+?(%s)" % (letter, noletter))
+
+ # remove_chinese_text_wrapping() regex
+ self._chinese_text_wrapping_pattern = re.compile(r"\\text\s*{([^{}]*[\u4e00-\u9fff]+[^{}]*)}")
+
+ @auto_docstring
+ def __call__(
+ self,
+ images: ImageInput,
+ **kwargs: Unpack[ProcessingKwargs],
+ ) -> BatchFeature:
+ r"""
+ images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`):
+ The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
+ tensor. Both channels-first and channels-last formats are supported.
+
+ Returns:
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
+
+ - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
+ """
+ output_kwargs = self._merge_kwargs(
+ ProcessingKwargs,
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
+ **kwargs,
+ )
+
+ image_inputs = self.image_processor(images=images, **output_kwargs["images_kwargs"])
+ return BatchFeature({**image_inputs})
+
+ def post_process_generation(self, text: str) -> str:
+ """Post-processes a string by fixing text and normalizing it.
+
+ Args:
+ text (str): String to post-process.
+
+ Returns:
+ str: Post-processed string.
+ """
+ text = self.remove_chinese_text_wrapping(text)
+ try:
+ from ftfy import fix_text
+
+ text = fix_text(text)
+ except ImportError:
+ logger.warning_once(
+ "ftfy is not installed, skipping fix_text. "
+ "Output may contain unnormalized unicode, extra spaces, or escaped artifacts"
+ )
+ text = self.normalize(text)
+ return text
+
+ def normalize(self, text: str) -> str:
+ """Normalizes a string by removing unnecessary spaces."""
+ names = []
+ for x in self._text_reg.findall(text):
+ matches = self._macro_pattern.findall(x[0])
+ for m in matches:
+ if m not in self._protected_macros and m.strip() != "":
+ text = text.replace(m, m + "XXXXXXX")
+ text = text.replace(" ", "")
+ names.append(text)
+
+ if names:
+ text = self._text_reg.sub(lambda match: str(names.pop(0)), text)
+
+ new_text = text
+ while True:
+ text = new_text
+ new_text = self._rule_noletter_noletter.sub(r"\1\2", text)
+ new_text = self._rule_noletter_letter.sub(r"\1\2", new_text)
+ new_text = self._rule_letter_noletter.sub(r"\1\2", new_text)
+ if new_text == text:
+ break
+
+ return new_text.replace("XXXXXXX", " ")
+
+ def remove_chinese_text_wrapping(self, formula: str) -> str:
+ def replacer(match):
+ return match.group(1)
+
+ replaced_formula = self._chinese_text_wrapping_pattern.sub(replacer, formula)
+ return replaced_formula.replace('"', "")
+
+ def post_process(self, generated_outputs, skip_special_tokens=True, **kwargs):
+ """
+ Post-process the output of the model to decode the text.
+
+ Args:
+ generated_outputs (`torch.Tensor` or `np.ndarray`):
+ The output of the model `generate` function. The output is expected to be a tensor of shape `(batch_size, sequence_length)`
+ or `(sequence_length,)`.
+ skip_special_tokens (`bool`, *optional*, defaults to `True`):
+ Whether or not to remove special tokens in the output. Argument passed to the tokenizer's `batch_decode` method.
+ **kwargs:
+ Additional arguments to be passed to the tokenizer's `batch_decode method`.
+
+ Returns:
+ `list[str]`: The decoded text.
+ """
+ generated_texts = self.batch_decode(generated_outputs, skip_special_tokens=skip_special_tokens, **kwargs)
+ return [self.post_process_generation(text) for text in generated_texts]
+
+
+__all__ = ["PPFormulaNetProcessor"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pp_lcnet_v3/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pp_lcnet_v3/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..bfde11d84f54b721013ddd890c3ec6621e7a0e07
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pp_lcnet_v3/__init__.py
@@ -0,0 +1,27 @@
+# Copyright 2026 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_pp_lcnet_v3 import *
+ from .modeling_pp_lcnet_v3 import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pp_lcnet_v3/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pp_lcnet_v3/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..182a41a9991174a7d25fab06af2b742b75a91d10
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pp_lcnet_v3/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pp_lcnet_v3/__pycache__/configuration_pp_lcnet_v3.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pp_lcnet_v3/__pycache__/configuration_pp_lcnet_v3.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e8e9e2c65773b59a0e72a7d08f79ed66f7f93a3c
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pp_lcnet_v3/__pycache__/configuration_pp_lcnet_v3.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pp_lcnet_v3/__pycache__/modeling_pp_lcnet_v3.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pp_lcnet_v3/__pycache__/modeling_pp_lcnet_v3.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..27257eeb30d44e796c1af230e4ebbb1fd851d055
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pp_lcnet_v3/__pycache__/modeling_pp_lcnet_v3.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pp_lcnet_v3/__pycache__/modular_pp_lcnet_v3.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pp_lcnet_v3/__pycache__/modular_pp_lcnet_v3.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..18eb35e88efef940caa3f8928d540b3afe0a62ed
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pp_lcnet_v3/__pycache__/modular_pp_lcnet_v3.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pp_lcnet_v3/configuration_pp_lcnet_v3.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pp_lcnet_v3/configuration_pp_lcnet_v3.py
new file mode 100644
index 0000000000000000000000000000000000000000..f3fc81756c061582fdf2c4c09460b4e20205a548
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pp_lcnet_v3/configuration_pp_lcnet_v3.py
@@ -0,0 +1,108 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/pp_lcnet_v3/modular_pp_lcnet_v3.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_pp_lcnet_v3.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2026 The PaddlePaddle Team and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+from huggingface_hub.dataclasses import strict
+
+from ...backbone_utils import BackboneConfigMixin
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring
+
+
+@auto_docstring(checkpoint="PaddlePaddle/Not_yet_released")
+@strict
+class PPLCNetV3Config(BackboneConfigMixin, PreTrainedConfig):
+ r"""
+ scale (`float`, *optional*, defaults to 1.0):
+ The scaling factor for the model's channel dimensions, used to adjust the model size and computational cost
+ without changing the overall architecture (e.g., 0.25, 0.5, 1.0, 1.5).
+ block_configs (`list[list[tuple]]`, *optional*, defaults to `None`):
+ Configuration for each block in each stage. Each tuple contains:
+ (kernel_size, in_channels, out_channels, stride, use_squeeze_excitation).
+ If `None`, uses the default PP-LCNet configuration.
+ stem_channels (`int`, *optional*, defaults to 16):
+ The number of output channels for the stem layer.
+ stem_stride (`int`, *optional*, defaults to 2):
+ The stride for the stem convolution layer.
+ reduction (`int`, *optional*, defaults to 4):
+ The reduction factor for feature channel dimensions in the squeeze-and-excitation (SE) blocks, used to
+ reduce the number of model parameters and computational complexity while maintaining feature representability.
+ divisor (`int`, *optional*, defaults to 8):
+ The divisor used to ensure that various model parameters (e.g., channel dimensions, kernel sizes) are
+ multiples of this value, promoting efficient model implementation and resource utilization.
+ conv_symmetric_num (`int`, *optional*, defaults to `4`):
+ The number of kxk convolution branches in the learnable reparameterization layer, used to enhance feature
+ extraction capability through multi-branch architecture during training while enabling efficient inference
+ via structural reparameterization.
+ """
+
+ model_type = "pp_lcnet_v3"
+
+ scale: float | int = 1.0
+ block_configs: list | None = None
+ stem_channels: int = 16
+ stem_stride: int = 2
+ reduction: int = 4
+ divisor: int = 8
+ hidden_act: str = "hardswish"
+ _out_features: list[str] | None = None
+ _out_indices: list[int] | None = None
+
+ conv_symmetric_num: int = 4
+
+ def __post_init__(self, **kwargs):
+ # Default block configs for PP-LCNetV3
+ # Each tuple: (kernel_size, in_channels, out_channels, stride, use_squeeze_excitation)
+ self.block_configs = (
+ [
+ # Stage 1 (blocks2)
+ [[3, 16, 32, 1, False]],
+ # Stage 2 (blocks3)
+ [[3, 32, 64, 2, False], [3, 64, 64, 1, False]],
+ # Stage 3 (blocks4)
+ [[3, 64, 128, 2, False], [3, 128, 128, 1, False]],
+ # Stage 4 (blocks5)
+ [
+ [3, 128, 256, 2, False],
+ [5, 256, 256, 1, False],
+ [5, 256, 256, 1, False],
+ [5, 256, 256, 1, False],
+ [5, 256, 256, 1, False],
+ ],
+ # Stage 5 (blocks6)
+ [[5, 256, 512, 2, True], [5, 512, 512, 1, True], [5, 512, 512, 1, False], [5, 512, 512, 1, False]],
+ ]
+ if self.block_configs is None
+ else self.block_configs
+ )
+ self.depths = [len(blocks) for blocks in self.block_configs]
+ self.stage_names = ["stem"] + [f"stage{idx}" for idx in range(1, len(self.block_configs) + 1)]
+ self.set_output_features_output_indices(
+ out_indices=kwargs.pop("out_indices", None), out_features=kwargs.pop("out_features", None)
+ )
+ super().__post_init__(**kwargs)
+
+ def validate_architecture(self):
+ """Part of `@strict`-powered validation. Validates the architecture of the config."""
+ if len(self.block_configs) != 5:
+ raise ValueError(f"block_configs must have 5 stages, but got {len(self.block_configs)}")
+
+
+__all__ = ["PPLCNetV3Config"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pp_lcnet_v3/modeling_pp_lcnet_v3.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pp_lcnet_v3/modeling_pp_lcnet_v3.py
new file mode 100644
index 0000000000000000000000000000000000000000..810f6ab80f5310ece1b11c2fce157fcd24d69011
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pp_lcnet_v3/modeling_pp_lcnet_v3.py
@@ -0,0 +1,410 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/pp_lcnet_v3/modular_pp_lcnet_v3.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_pp_lcnet_v3.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2026 The PaddlePaddle Team and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+import torch
+import torch.nn as nn
+from torch import Tensor
+
+from ...activations import ACT2FN
+from ...backbone_utils import BackboneMixin, filter_output_hidden_states
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import BackboneOutput, BaseModelOutputWithNoAttention
+from ...modeling_utils import PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import TransformersKwargs, auto_docstring
+from ...utils.generic import can_return_tuple, merge_with_config_defaults
+from ...utils.output_capturing import capture_outputs
+from .configuration_pp_lcnet_v3 import PPLCNetV3Config
+
+
+class PPLCNetV3ConvLayer(nn.Module):
+ def __init__(
+ self,
+ in_channels: int,
+ out_channels: int,
+ kernel_size: int = 3,
+ stride: int = 1,
+ bias: bool = False,
+ dilation: int | tuple[int, int] = 1,
+ groups: int = 1,
+ activation: str = "hardswish",
+ ):
+ super().__init__()
+ self.convolution = nn.Conv2d(
+ in_channels=in_channels,
+ out_channels=out_channels,
+ kernel_size=kernel_size,
+ stride=stride,
+ padding=kernel_size // 2,
+ bias=bias,
+ dilation=dilation,
+ groups=groups,
+ )
+ self.normalization = nn.BatchNorm2d(out_channels)
+ self.activation = ACT2FN[activation] if activation is not None else nn.Identity()
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.convolution(hidden_states)
+ hidden_states = self.normalization(hidden_states)
+ hidden_states = self.activation(hidden_states)
+ return hidden_states
+
+
+class PPLCNetV3LearnableAffineBlock(nn.Module):
+ def __init__(self, scale_value: float = 1.0, bias_value: float = 0.0):
+ super().__init__()
+ self.scale = nn.Parameter(torch.tensor([scale_value]), requires_grad=True)
+ self.bias = nn.Parameter(torch.tensor([bias_value]), requires_grad=True)
+
+ def forward(self, hidden_state: Tensor) -> Tensor:
+ hidden_state = self.scale * hidden_state + self.bias
+ return hidden_state
+
+
+class PPLCNetV3ActLearnableAffineBlock(nn.Module):
+ """
+ Activation block with a trainable affine transformation applied after the non-linear activation.
+ """
+
+ def __init__(self, activation="hardswish"):
+ super().__init__()
+ self.act = ACT2FN[activation]
+ self.lab = PPLCNetV3LearnableAffineBlock()
+
+ def forward(self, hidden_state: torch.Tensor):
+ return self.lab(self.act(hidden_state))
+
+
+class PPLCNetV3LearnableRepLayer(nn.Module):
+ """
+ Learnable Reparameterization Layer (RepLayer) that fuses multiple convolution branches
+ (kxk and 1x1) with an optional identity branch. This layer enables structural reparameterization
+ for efficient inference while maintaining training flexibility.
+ """
+
+ def __init__(
+ self,
+ in_channels: int,
+ out_channels: int,
+ kernel_size: int,
+ activation: str,
+ stride: int,
+ num_conv_branches: int,
+ groups: int = 1,
+ ):
+ super().__init__()
+ self.groups = groups
+ self.stride = stride
+ self.kernel_size = kernel_size
+ self.in_channels = in_channels
+ self.out_channels = out_channels
+ self.num_conv_branches = num_conv_branches
+ self.padding = (kernel_size - 1) // 2
+
+ self.identity = (
+ nn.BatchNorm2d(num_features=in_channels) if out_channels == in_channels and stride == 1 else None
+ )
+
+ self.conv_symmetric = nn.ModuleList(
+ [
+ PPLCNetV3ConvLayer(
+ in_channels,
+ out_channels,
+ kernel_size,
+ stride,
+ groups=groups,
+ activation=None,
+ )
+ for _ in range(self.num_conv_branches)
+ ]
+ )
+
+ self.conv_small_symmetric = (
+ PPLCNetV3ConvLayer(in_channels, out_channels, 1, stride, groups=groups, activation=None)
+ if kernel_size > 1
+ else None
+ )
+
+ self.lab = PPLCNetV3LearnableAffineBlock()
+ self.act = PPLCNetV3ActLearnableAffineBlock(activation=activation)
+
+ def forward(self, hidden_state: torch.Tensor):
+ output = None
+
+ if self.identity is not None:
+ output = self.identity(hidden_state)
+
+ if self.conv_small_symmetric is not None:
+ residual = self.conv_small_symmetric(hidden_state)
+ output = residual if output is None else output + residual
+
+ for conv in self.conv_symmetric:
+ residual = conv(hidden_state)
+ output = residual if output is None else output + residual
+
+ hidden_state = self.lab(output)
+ if self.stride != 2:
+ hidden_state = self.act(hidden_state)
+ return hidden_state
+
+
+class PPLCNetV3SqueezeExcitationModule(nn.Module):
+ """
+ Squeeze-and-Excitation (SE) Module: Adaptive feature recalibration
+ Enhances the model's ability to focus on important channels by learning channel-wise attention weights.
+ """
+
+ def __init__(self, channel, reduction=4):
+ super().__init__()
+ self.avg_pool = nn.AdaptiveAvgPool2d(1)
+
+ self.convolutions = nn.ModuleList()
+ for in_channels, out_channels, activation in [
+ [channel, channel // reduction, nn.ReLU()],
+ [channel // reduction, channel, nn.Hardsigmoid()],
+ ]:
+ self.convolutions.append(
+ nn.Conv2d(
+ in_channels=in_channels,
+ out_channels=out_channels,
+ kernel_size=1,
+ stride=1,
+ padding=0,
+ bias=True,
+ )
+ )
+ self.convolutions.append(activation)
+
+ def forward(self, hidden_state):
+ residual = hidden_state
+ hidden_state = self.avg_pool(hidden_state)
+ for layer in self.convolutions:
+ hidden_state = layer(hidden_state)
+ hidden_state = residual * hidden_state
+
+ return hidden_state
+
+
+class PPLCNetV3DepthwiseSeparableConvLayer(GradientCheckpointingLayer):
+ """
+ Depthwise Separable Convolution Layer: Depthwise Conv -> SE Module (optional) -> Pointwise Conv
+ Core component of lightweight models (e.g., MobileNet, PP-LCNet) that significantly reduces
+ the number of parameters and computational cost.
+ """
+
+ def __init__(
+ self,
+ in_channels,
+ out_channels,
+ stride,
+ kernel_size,
+ use_squeeze_excitation,
+ config,
+ ):
+ super().__init__()
+ self.depthwise_convolution = PPLCNetV3LearnableRepLayer(
+ in_channels=in_channels,
+ out_channels=in_channels,
+ kernel_size=kernel_size,
+ stride=stride,
+ groups=in_channels,
+ num_conv_branches=config.conv_symmetric_num,
+ activation=config.hidden_act,
+ )
+ self.squeeze_excitation_module = (
+ PPLCNetV3SqueezeExcitationModule(in_channels, config.reduction)
+ if use_squeeze_excitation
+ else nn.Identity()
+ )
+ self.pointwise_convolution = PPLCNetV3LearnableRepLayer(
+ in_channels=in_channels,
+ kernel_size=1,
+ out_channels=out_channels,
+ stride=1,
+ num_conv_branches=config.conv_symmetric_num,
+ activation=config.hidden_act,
+ )
+
+ def forward(self, hidden_state):
+ hidden_state = self.depthwise_convolution(hidden_state)
+ hidden_state = self.squeeze_excitation_module(hidden_state)
+ hidden_state = self.pointwise_convolution(hidden_state)
+
+ return hidden_state
+
+
+def make_divisible(value: int, divisor: int = 8, min_value: int | None = None) -> int:
+ """
+ Ensure that all layers have a channel count that is divisible by `divisor`.
+ """
+ if min_value is None:
+ min_value = divisor
+ new_value = max(min_value, int(value + divisor / 2) // divisor * divisor)
+ # Make sure that round down does not go down by more than 10%.
+ if new_value < 0.9 * value:
+ new_value += divisor
+ return int(new_value)
+
+
+class PPLCNetV3Block(nn.Module):
+ def __init__(self, config, stage_index):
+ super().__init__()
+ self.config = config
+
+ blocks = config.block_configs[stage_index]
+
+ self.layers = nn.ModuleList()
+ for kernel_size, in_channels, out_channels, stride, use_squeeze_excitation in blocks:
+ scaled_in_channels = make_divisible(in_channels * config.scale, config.divisor)
+ scaled_out_channels = make_divisible(out_channels * config.scale, config.divisor)
+
+ depthwise_block = PPLCNetV3DepthwiseSeparableConvLayer(
+ in_channels=scaled_in_channels,
+ out_channels=scaled_out_channels,
+ kernel_size=kernel_size,
+ stride=stride,
+ use_squeeze_excitation=use_squeeze_excitation,
+ config=config,
+ )
+ self.layers.append(depthwise_block)
+
+ def forward(self, hidden_states):
+ for layer in self.layers:
+ hidden_states = layer(hidden_states)
+ return hidden_states
+
+
+@auto_docstring
+class PPLCNetV3PreTrainedModel(PreTrainedModel):
+ """
+ An abstract base class for PP-LCNet models that inherits from Hugging Face PreTrainedModel.
+ Provides common functionality for weight initialization and loading.
+ """
+
+ config: PPLCNetV3Config
+ base_model_prefix = "model"
+ main_input_name = "pixel_values"
+ input_modalities = ("image",)
+ _can_compile_fullgraph = True
+ supports_gradient_checkpointing = True
+ _no_split_modules = ["PPLCNetV3DepthwiseSeparableConvLayer"]
+ _can_record_outputs = {
+ "hidden_states": PPLCNetV3Block,
+ }
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ super()._init_weights(module)
+ if isinstance(module, (PPLCNetV3LearnableAffineBlock)):
+ nn.init.ones_(module.scale)
+ nn.init.zeros_(module.bias)
+
+
+@auto_docstring(
+ custom_intro="""
+ PPLCNetV3 backbone model for feature extraction.
+ """
+)
+class PPLCNetV3Backbone(BackboneMixin, PPLCNetV3PreTrainedModel):
+ has_attentions = False
+
+ def __init__(self, config: PPLCNetV3Config):
+ super().__init__(config)
+ num_features = [config.stem_channels]
+ for block in config.block_configs:
+ num_features.append(int(block[-1][2] * config.scale))
+ self.num_features = num_features
+ self.encoder = PPLCNetV3Encoder(config)
+
+ self.post_init()
+
+ @can_return_tuple
+ @filter_output_hidden_states
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: torch.Tensor,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> BackboneOutput:
+ r"""
+ Examples:
+
+ ```python
+ >>> from transformers import PPLCNetV3Config, PPLCNetV3Backbone
+ >>> import torch
+
+ >>> config = PPLCNetV3Config()
+ >>> model = PPLCNetV3Backbone(config)
+
+ >>> pixel_values = torch.randn(1, 3, 224, 224)
+
+ >>> with torch.no_grad():
+ ... outputs = model(pixel_values)
+
+ >>> feature_maps = outputs.feature_maps
+ >>> list(feature_maps[-1].shape)
+ ```"""
+ kwargs["output_hidden_states"] = True # required to extract layers for the stages
+ hidden_states = self.encoder(pixel_values, **kwargs).hidden_states
+
+ feature_maps = ()
+ for idx, stage in enumerate(self.stage_names):
+ if stage in self.out_features:
+ feature_maps += (hidden_states[idx],)
+
+ return BackboneOutput(
+ feature_maps=feature_maps,
+ hidden_states=hidden_states,
+ )
+
+
+class PPLCNetV3Encoder(PPLCNetV3PreTrainedModel):
+ def __init__(self, config: PPLCNetV3Config):
+ super().__init__(config)
+ self.config = config
+
+ # stem
+ self.convolution = PPLCNetV3ConvLayer(
+ in_channels=3,
+ kernel_size=3,
+ out_channels=make_divisible(config.stem_channels * config.scale, config.divisor),
+ stride=config.stem_stride,
+ activation=None,
+ )
+ # stages
+ self.blocks = nn.ModuleList([])
+ for stage_index in range(len(config.block_configs)):
+ block = PPLCNetV3Block(config, stage_index)
+ self.blocks.append(block)
+
+ self.post_init()
+
+ @merge_with_config_defaults
+ @capture_outputs
+ def forward(self, pixel_values: torch.Tensor, **kwargs) -> BaseModelOutputWithNoAttention:
+ hidden_state = self.convolution(pixel_values)
+ for block in self.blocks:
+ hidden_state = block(hidden_state)
+
+ return BaseModelOutputWithNoAttention(last_hidden_state=hidden_state)
+
+
+__all__ = ["PPLCNetV3Backbone", "PPLCNetV3PreTrainedModel"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pp_lcnet_v3/modular_pp_lcnet_v3.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pp_lcnet_v3/modular_pp_lcnet_v3.py
new file mode 100644
index 0000000000000000000000000000000000000000..a339afd90874236c1cafda852608f9a3b6753a9e
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/pp_lcnet_v3/modular_pp_lcnet_v3.py
@@ -0,0 +1,267 @@
+# Copyright 2026 The PaddlePaddle Team and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+import torch
+import torch.nn as nn
+from huggingface_hub.dataclasses import strict
+
+from ...activations import ACT2FN
+from ...configuration_utils import PreTrainedConfig
+from ...modeling_utils import PreTrainedModel
+from ...utils import (
+ auto_docstring,
+)
+from ..hgnet_v2.modeling_hgnet_v2 import HGNetV2LearnableAffineBlock
+from ..mobilenet_v2.modeling_mobilenet_v2 import make_divisible
+from ..pp_lcnet.configuration_pp_lcnet import PPLCNetConfig
+from ..pp_lcnet.modeling_pp_lcnet import (
+ PPLCNetBackbone,
+ PPLCNetConvLayer,
+ PPLCNetDepthwiseSeparableConvLayer,
+ PPLCNetEncoder,
+ PPLCNetPreTrainedModel,
+)
+
+
+@auto_docstring(checkpoint="PaddlePaddle/Not_yet_released")
+@strict
+class PPLCNetV3Config(PPLCNetConfig):
+ r"""
+ scale (`float`, *optional*, defaults to 1.0):
+ The scaling factor for the model's channel dimensions, used to adjust the model size and computational cost
+ without changing the overall architecture (e.g., 0.25, 0.5, 1.0, 1.5).
+ block_configs (`list[list[tuple]]`, *optional*, defaults to `None`):
+ Configuration for each block in each stage. Each tuple contains:
+ (kernel_size, in_channels, out_channels, stride, use_squeeze_excitation).
+ If `None`, uses the default PP-LCNet configuration.
+ stem_channels (`int`, *optional*, defaults to 16):
+ The number of output channels for the stem layer.
+ stem_stride (`int`, *optional*, defaults to 2):
+ The stride for the stem convolution layer.
+ reduction (`int`, *optional*, defaults to 4):
+ The reduction factor for feature channel dimensions in the squeeze-and-excitation (SE) blocks, used to
+ reduce the number of model parameters and computational complexity while maintaining feature representability.
+ divisor (`int`, *optional*, defaults to 8):
+ The divisor used to ensure that various model parameters (e.g., channel dimensions, kernel sizes) are
+ multiples of this value, promoting efficient model implementation and resource utilization.
+ conv_symmetric_num (`int`, *optional*, defaults to `4`):
+ The number of kxk convolution branches in the learnable reparameterization layer, used to enhance feature
+ extraction capability through multi-branch architecture during training while enabling efficient inference
+ via structural reparameterization.
+ """
+
+ model_type = "pp_lcnet_v3"
+
+ conv_symmetric_num: int = 4
+ hidden_dropout_prob = AttributeError()
+ class_expand = AttributeError()
+
+ def __post_init__(self, **kwargs):
+ # Default block configs for PP-LCNetV3
+ # Each tuple: (kernel_size, in_channels, out_channels, stride, use_squeeze_excitation)
+ self.block_configs = (
+ [
+ # Stage 1 (blocks2)
+ [[3, 16, 32, 1, False]],
+ # Stage 2 (blocks3)
+ [[3, 32, 64, 2, False], [3, 64, 64, 1, False]],
+ # Stage 3 (blocks4)
+ [[3, 64, 128, 2, False], [3, 128, 128, 1, False]],
+ # Stage 4 (blocks5)
+ [
+ [3, 128, 256, 2, False],
+ [5, 256, 256, 1, False],
+ [5, 256, 256, 1, False],
+ [5, 256, 256, 1, False],
+ [5, 256, 256, 1, False],
+ ],
+ # Stage 5 (blocks6)
+ [[5, 256, 512, 2, True], [5, 512, 512, 1, True], [5, 512, 512, 1, False], [5, 512, 512, 1, False]],
+ ]
+ if self.block_configs is None
+ else self.block_configs
+ )
+ self.depths = [len(blocks) for blocks in self.block_configs]
+ self.stage_names = ["stem"] + [f"stage{idx}" for idx in range(1, len(self.block_configs) + 1)]
+ self.set_output_features_output_indices(
+ out_indices=kwargs.pop("out_indices", None), out_features=kwargs.pop("out_features", None)
+ )
+ PreTrainedConfig.__post_init__(**kwargs)
+
+
+class PPLCNetV3ConvLayer(PPLCNetConvLayer):
+ pass
+
+
+class PPLCNetV3LearnableAffineBlock(HGNetV2LearnableAffineBlock):
+ pass
+
+
+class PPLCNetV3ActLearnableAffineBlock(nn.Module):
+ """
+ Activation block with a trainable affine transformation applied after the non-linear activation.
+ """
+
+ def __init__(self, activation="hardswish"):
+ super().__init__()
+ self.act = ACT2FN[activation]
+ self.lab = PPLCNetV3LearnableAffineBlock()
+
+ def forward(self, hidden_state: torch.Tensor):
+ return self.lab(self.act(hidden_state))
+
+
+class PPLCNetV3LearnableRepLayer(nn.Module):
+ """
+ Learnable Reparameterization Layer (RepLayer) that fuses multiple convolution branches
+ (kxk and 1x1) with an optional identity branch. This layer enables structural reparameterization
+ for efficient inference while maintaining training flexibility.
+ """
+
+ def __init__(
+ self,
+ in_channels: int,
+ out_channels: int,
+ kernel_size: int,
+ activation: str,
+ stride: int,
+ num_conv_branches: int,
+ groups: int = 1,
+ ):
+ super().__init__()
+ self.groups = groups
+ self.stride = stride
+ self.kernel_size = kernel_size
+ self.in_channels = in_channels
+ self.out_channels = out_channels
+ self.num_conv_branches = num_conv_branches
+ self.padding = (kernel_size - 1) // 2
+
+ self.identity = (
+ nn.BatchNorm2d(num_features=in_channels) if out_channels == in_channels and stride == 1 else None
+ )
+
+ self.conv_symmetric = nn.ModuleList(
+ [
+ PPLCNetV3ConvLayer(
+ in_channels,
+ out_channels,
+ kernel_size,
+ stride,
+ groups=groups,
+ activation=None,
+ )
+ for _ in range(self.num_conv_branches)
+ ]
+ )
+
+ self.conv_small_symmetric = (
+ PPLCNetV3ConvLayer(in_channels, out_channels, 1, stride, groups=groups, activation=None)
+ if kernel_size > 1
+ else None
+ )
+
+ self.lab = PPLCNetV3LearnableAffineBlock()
+ self.act = PPLCNetV3ActLearnableAffineBlock(activation=activation)
+
+ def forward(self, hidden_state: torch.Tensor):
+ output = None
+
+ if self.identity is not None:
+ output = self.identity(hidden_state)
+
+ if self.conv_small_symmetric is not None:
+ residual = self.conv_small_symmetric(hidden_state)
+ output = residual if output is None else output + residual
+
+ for conv in self.conv_symmetric:
+ residual = conv(hidden_state)
+ output = residual if output is None else output + residual
+
+ hidden_state = self.lab(output)
+ if self.stride != 2:
+ hidden_state = self.act(hidden_state)
+ return hidden_state
+
+
+class PPLCNetV3DepthwiseSeparableConvLayer(PPLCNetDepthwiseSeparableConvLayer):
+ """
+ Depthwise Separable Convolution Layer: Depthwise Conv -> SE Module (optional) -> Pointwise Conv
+ Core component of lightweight models (e.g., MobileNet, PP-LCNet) that significantly reduces
+ the number of parameters and computational cost.
+ """
+
+ def __init__(
+ self,
+ in_channels,
+ out_channels,
+ stride,
+ kernel_size,
+ use_squeeze_excitation,
+ config,
+ ):
+ super().__init__()
+ self.depthwise_convolution = PPLCNetV3LearnableRepLayer(
+ in_channels=in_channels,
+ out_channels=in_channels,
+ kernel_size=kernel_size,
+ stride=stride,
+ groups=in_channels,
+ num_conv_branches=config.conv_symmetric_num,
+ activation=config.hidden_act,
+ )
+ self.pointwise_convolution = PPLCNetV3LearnableRepLayer(
+ in_channels=in_channels,
+ kernel_size=1,
+ out_channels=out_channels,
+ stride=1,
+ num_conv_branches=config.conv_symmetric_num,
+ activation=config.hidden_act,
+ )
+
+
+class PPLCNetV3PreTrainedModel(PPLCNetPreTrainedModel):
+ @torch.no_grad()
+ def _init_weights(self, module):
+ PreTrainedModel._init_weights(module)
+ if isinstance(module, (PPLCNetV3LearnableAffineBlock)):
+ nn.init.ones_(module.scale)
+ nn.init.zeros_(module.bias)
+
+
+class PPLCNetV3Backbone(PPLCNetBackbone):
+ pass
+
+
+class PPLCNetV3Encoder(PPLCNetEncoder):
+ def __init__(self, config: PPLCNetV3Config):
+ super().__init__(config)
+ self.config = config
+
+ # stem
+ self.convolution = PPLCNetV3ConvLayer(
+ in_channels=3,
+ kernel_size=3,
+ out_channels=make_divisible(config.stem_channels * config.scale, config.divisor),
+ stride=config.stem_stride,
+ activation=None,
+ )
+
+
+__all__ = [
+ "PPLCNetV3Backbone",
+ "PPLCNetV3Config",
+ "PPLCNetV3PreTrainedModel",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/prophetnet/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/prophetnet/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..58fa7e8686f2b85eaa956180bad29ea567c0e6f3
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/prophetnet/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/prophetnet/__pycache__/configuration_prophetnet.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/prophetnet/__pycache__/configuration_prophetnet.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3eebe95b63f13004f2339f9e371b5772567980d6
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/prophetnet/__pycache__/configuration_prophetnet.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/prophetnet/__pycache__/modeling_prophetnet.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/prophetnet/__pycache__/modeling_prophetnet.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dd85aefee67e1187f30f4fec7daa705e2c8b46d5
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/prophetnet/__pycache__/modeling_prophetnet.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/prophetnet/__pycache__/tokenization_prophetnet.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/prophetnet/__pycache__/tokenization_prophetnet.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2cc61822e5951916d91d2d8f0b92e3918b388148
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/prophetnet/__pycache__/tokenization_prophetnet.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/qwen2_vl/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/qwen2_vl/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..56b034efa2b8f0797a0742d3d3e99726c58b61aa
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/qwen2_vl/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/qwen2_vl/__pycache__/configuration_qwen2_vl.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/qwen2_vl/__pycache__/configuration_qwen2_vl.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6864538fccc68891b399da8b8675c205333aaae6
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/qwen2_vl/__pycache__/configuration_qwen2_vl.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/qwen2_vl/__pycache__/image_processing_pil_qwen2_vl.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/qwen2_vl/__pycache__/image_processing_pil_qwen2_vl.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..57ffa0b10a550adf35a9a1b7868fb4d486264bf3
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/qwen2_vl/__pycache__/image_processing_pil_qwen2_vl.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/qwen2_vl/__pycache__/image_processing_qwen2_vl.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/qwen2_vl/__pycache__/image_processing_qwen2_vl.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..323634e10e2f8823d1ff8d06371c79aeb4c84c70
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/qwen2_vl/__pycache__/image_processing_qwen2_vl.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/qwen2_vl/__pycache__/processing_qwen2_vl.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/qwen2_vl/__pycache__/processing_qwen2_vl.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bf90fd19ef2e312badcfa8712dbf7bd8391fcbeb
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/qwen2_vl/__pycache__/processing_qwen2_vl.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/qwen2_vl/__pycache__/video_processing_qwen2_vl.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/qwen2_vl/__pycache__/video_processing_qwen2_vl.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..125c93d20f3eab19ca1845c60109dcd41c33c579
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/qwen2_vl/__pycache__/video_processing_qwen2_vl.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/qwen3_vl/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/qwen3_vl/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f81f020c1ffa1c1347b12da641e3f13a44241df3
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/qwen3_vl/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/qwen3_vl/__pycache__/configuration_qwen3_vl.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/qwen3_vl/__pycache__/configuration_qwen3_vl.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fe07a746d382f394f9896443ce18805b6aa29081
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/qwen3_vl/__pycache__/configuration_qwen3_vl.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/qwen3_vl/__pycache__/modeling_qwen3_vl.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/qwen3_vl/__pycache__/modeling_qwen3_vl.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8cbc92ec853856f7bf488bf9226fadf275c96d0e
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/qwen3_vl/__pycache__/modeling_qwen3_vl.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/qwen3_vl/__pycache__/modular_qwen3_vl.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/qwen3_vl/__pycache__/modular_qwen3_vl.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6b32680129cd4769f6c8cab1f1a605fc02141314
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/qwen3_vl/__pycache__/modular_qwen3_vl.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/qwen3_vl/__pycache__/processing_qwen3_vl.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/qwen3_vl/__pycache__/processing_qwen3_vl.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0daefffb0767116d0f8be7b714eece0ae91a4445
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/qwen3_vl/__pycache__/processing_qwen3_vl.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/qwen3_vl/__pycache__/video_processing_qwen3_vl.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/qwen3_vl/__pycache__/video_processing_qwen3_vl.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..40b7e1466754c4021aeb036a6f69f1d3387f409c
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/qwen3_vl/__pycache__/video_processing_qwen3_vl.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/roberta/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/roberta/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..2e8011675176b7e122895b6d6913065f89c2229e
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/roberta/__init__.py
@@ -0,0 +1,28 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_roberta import *
+ from .modeling_roberta import *
+ from .tokenization_roberta import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/roberta/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/roberta/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1bf29965ec06cbe785b5a6711bd3d351a7f3a4c9
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/roberta/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/roberta/__pycache__/configuration_roberta.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/roberta/__pycache__/configuration_roberta.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9d4f5c48eff0bc5093f8520b8f9e9e20b19636b4
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/roberta/__pycache__/configuration_roberta.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/roberta/__pycache__/modeling_roberta.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/roberta/__pycache__/modeling_roberta.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..411f38d91a92de22e874f5adbe454e15df908ab0
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/roberta/__pycache__/modeling_roberta.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/roberta/__pycache__/modular_roberta.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/roberta/__pycache__/modular_roberta.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fdb11ef2eed7ee4bda131fed54aa7b4795491376
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/roberta/__pycache__/modular_roberta.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/roberta/__pycache__/tokenization_roberta.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/roberta/__pycache__/tokenization_roberta.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1ddf79f830625c95ef8dad0a00c738ab29b4cf01
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/roberta/__pycache__/tokenization_roberta.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/roberta/__pycache__/tokenization_roberta_old.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/roberta/__pycache__/tokenization_roberta_old.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..883b5036a8e78f2bd1ff073e88b7466f69c7a910
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/roberta/__pycache__/tokenization_roberta_old.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/roberta/configuration_roberta.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/roberta/configuration_roberta.py
new file mode 100644
index 0000000000000000000000000000000000000000..210a1b3698ebd65f91097752f6bad94148edfa2e
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/roberta/configuration_roberta.py
@@ -0,0 +1,66 @@
+# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
+# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""RoBERTa configuration"""
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring
+
+
+@auto_docstring(checkpoint="FacebookAI/roberta-base")
+@strict
+class RobertaConfig(PreTrainedConfig):
+ r"""
+ Examples:
+
+ ```python
+ >>> from transformers import RobertaConfig, RobertaModel
+
+ >>> # Initializing a RoBERTa configuration
+ >>> configuration = RobertaConfig()
+
+ >>> # Initializing a model (with random weights) from the configuration
+ >>> model = RobertaModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "roberta"
+
+ vocab_size: int = 50265
+ hidden_size: int = 768
+ num_hidden_layers: int = 12
+ num_attention_heads: int = 12
+ intermediate_size: int = 3072
+ hidden_act: str = "gelu"
+ hidden_dropout_prob: float | int = 0.1
+ attention_probs_dropout_prob: float | int = 0.1
+ max_position_embeddings: int = 512
+ type_vocab_size: int = 2
+ initializer_range: float = 0.02
+ layer_norm_eps: float = 1e-12
+ pad_token_id: int | None = 1
+ bos_token_id: int | None = 0
+ eos_token_id: int | list[int] | None = 2
+ use_cache: bool = True
+ classifier_dropout: float | int | None = None
+ is_decoder: bool = False
+ add_cross_attention: bool = False
+ tie_word_embeddings: bool = True
+
+
+__all__ = ["RobertaConfig"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/roberta/modeling_roberta.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/roberta/modeling_roberta.py
new file mode 100644
index 0000000000000000000000000000000000000000..bf891b7dbfe7a19e7767f954dcb831ae8913d4a2
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/roberta/modeling_roberta.py
@@ -0,0 +1,1271 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/roberta/modular_roberta.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_roberta.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
+# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from collections.abc import Callable
+
+import torch
+import torch.nn as nn
+from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
+
+from ... import initialization as init
+from ...activations import ACT2FN, gelu
+from ...cache_utils import Cache, DynamicCache, EncoderDecoderCache
+from ...generation import GenerationMixin
+from ...masking_utils import create_bidirectional_mask, create_causal_mask
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import (
+ BaseModelOutputWithPastAndCrossAttentions,
+ BaseModelOutputWithPoolingAndCrossAttentions,
+ CausalLMOutputWithCrossAttentions,
+ MaskedLMOutput,
+ MultipleChoiceModelOutput,
+ QuestionAnsweringModelOutput,
+ SequenceClassifierOutput,
+ TokenClassifierOutput,
+)
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
+from ...processing_utils import Unpack
+from ...pytorch_utils import apply_chunking_to_forward
+from ...utils import TransformersKwargs, auto_docstring, logging
+from ...utils.generic import can_return_tuple, merge_with_config_defaults
+from ...utils.output_capturing import capture_outputs
+from .configuration_roberta import RobertaConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+class RobertaEmbeddings(nn.Module):
+ """Construct the embeddings from word, position and token_type embeddings."""
+
+ def __init__(self, config):
+ super().__init__()
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
+ self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
+
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
+ self.register_buffer(
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
+ )
+ self.register_buffer(
+ "token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False
+ )
+
+ self.padding_idx = config.pad_token_id
+ self.position_embeddings = nn.Embedding(
+ config.max_position_embeddings, config.hidden_size, padding_idx=self.padding_idx
+ )
+
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ past_key_values_length: int = 0,
+ ) -> torch.Tensor:
+ if position_ids is None:
+ if input_ids is not None:
+ # Create the position ids from the input token ids. Any padded tokens remain padded.
+ position_ids = self.create_position_ids_from_input_ids(
+ input_ids, self.padding_idx, past_key_values_length
+ )
+ else:
+ position_ids = self.create_position_ids_from_inputs_embeds(inputs_embeds, self.padding_idx)
+
+ if input_ids is not None:
+ input_shape = input_ids.size()
+ else:
+ input_shape = inputs_embeds.size()[:-1]
+
+ batch_size, seq_length = input_shape
+
+ # Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
+ # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
+ # issue #5664
+ if token_type_ids is None:
+ if hasattr(self, "token_type_ids"):
+ # NOTE: We assume either pos ids to have bsz == 1 (broadcastable) or bsz == effective bsz (input_shape[0])
+ buffered_token_type_ids = self.token_type_ids.expand(position_ids.shape[0], -1)
+ buffered_token_type_ids = torch.gather(buffered_token_type_ids, dim=1, index=position_ids)
+ token_type_ids = buffered_token_type_ids.expand(batch_size, seq_length)
+ else:
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
+
+ if inputs_embeds is None:
+ inputs_embeds = self.word_embeddings(input_ids)
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
+ embeddings = inputs_embeds + token_type_embeddings
+
+ position_embeddings = self.position_embeddings(position_ids)
+ embeddings = embeddings + position_embeddings
+
+ embeddings = self.LayerNorm(embeddings)
+ embeddings = self.dropout(embeddings)
+ return embeddings
+
+ @staticmethod
+ def create_position_ids_from_inputs_embeds(inputs_embeds, padding_idx):
+ """
+ We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids.
+
+ Args:
+ inputs_embeds: torch.Tensor
+
+ Returns: torch.Tensor
+ """
+ input_shape = inputs_embeds.size()[:-1]
+ sequence_length = input_shape[1]
+
+ position_ids = torch.arange(
+ padding_idx + 1, sequence_length + padding_idx + 1, dtype=torch.long, device=inputs_embeds.device
+ )
+ return position_ids.unsqueeze(0).expand(input_shape)
+
+ @staticmethod
+ def create_position_ids_from_input_ids(input_ids, padding_idx, past_key_values_length=0):
+ """
+ Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols
+ are ignored. This is modified from fairseq's `utils.make_positions`.
+
+ Args:
+ x: torch.Tensor x:
+
+ Returns: torch.Tensor
+ """
+ # The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA.
+ mask = input_ids.ne(padding_idx).int()
+ incremental_indices = (torch.cumsum(mask, dim=1).type_as(mask) + past_key_values_length) * mask
+ return incremental_indices.long() + padding_idx
+
+
+def eager_attention_forward(
+ module: nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: torch.Tensor | None,
+ scaling: float | None = None,
+ dropout: float = 0.0,
+ **kwargs: Unpack[TransformersKwargs],
+):
+ if scaling is None:
+ scaling = query.size(-1) ** -0.5
+
+ # Take the dot product between "query" and "key" to get the raw attention scores.
+ attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
+
+ if attention_mask is not None:
+ attn_weights = attn_weights + attention_mask
+
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
+
+ attn_output = torch.matmul(attn_weights, value)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+
+ return attn_output, attn_weights
+
+
+class RobertaSelfAttention(nn.Module):
+ def __init__(self, config, is_causal=False, layer_idx=None):
+ super().__init__()
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
+ raise ValueError(
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
+ f"heads ({config.num_attention_heads})"
+ )
+ self.config = config
+
+ self.num_attention_heads = config.num_attention_heads
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
+ self.scaling = self.attention_head_size**-0.5
+
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
+
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
+
+ self.is_decoder = config.is_decoder
+ self.is_causal = is_causal
+ self.layer_idx = layer_idx
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.FloatTensor | None = None,
+ past_key_values: Cache | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor]:
+ input_shape = hidden_states.shape[:-1]
+ hidden_shape = (*input_shape, -1, self.attention_head_size)
+
+ # get all proj
+ query_layer = self.query(hidden_states).view(*hidden_shape).transpose(1, 2)
+ key_layer = self.key(hidden_states).view(*hidden_shape).transpose(1, 2)
+ value_layer = self.value(hidden_states).view(*hidden_shape).transpose(1, 2)
+
+ if past_key_values is not None:
+ # decoder-only roberta can have a simple dynamic cache for example
+ current_past_key_values = past_key_values
+ if isinstance(past_key_values, EncoderDecoderCache):
+ current_past_key_values = past_key_values.self_attention_cache
+
+ # save all key/value_layer to cache to be re-used for fast auto-regressive generation
+ key_layer, value_layer = current_past_key_values.update(key_layer, value_layer, self.layer_idx)
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_layer,
+ key_layer,
+ value_layer,
+ attention_mask,
+ dropout=0.0 if not self.training else self.dropout.p,
+ scaling=self.scaling,
+ **kwargs,
+ )
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ return attn_output, attn_weights
+
+
+class RobertaCrossAttention(nn.Module):
+ def __init__(self, config, is_causal=False, layer_idx=None):
+ super().__init__()
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
+ raise ValueError(
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
+ f"heads ({config.num_attention_heads})"
+ )
+ self.config = config
+
+ self.num_attention_heads = config.num_attention_heads
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
+ self.scaling = self.attention_head_size**-0.5
+
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
+
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
+
+ self.is_causal = is_causal
+ self.layer_idx = layer_idx
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ past_key_values: EncoderDecoderCache | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor]:
+ # determine input shapes
+ input_shape = hidden_states.shape[:-1]
+
+ hidden_shape = (*input_shape, -1, self.attention_head_size)
+
+ # get query proj
+ query_layer = self.query(hidden_states).view(hidden_shape).transpose(1, 2)
+
+ is_updated = past_key_values.is_updated.get(self.layer_idx) if past_key_values is not None else False
+ if past_key_values is not None and is_updated:
+ # reuse k,v, cross_attentions
+ key_layer = past_key_values.cross_attention_cache.layers[self.layer_idx].keys
+ value_layer = past_key_values.cross_attention_cache.layers[self.layer_idx].values
+ else:
+ kv_shape = (*encoder_hidden_states.shape[:-1], -1, self.attention_head_size)
+ key_layer = self.key(encoder_hidden_states).view(kv_shape).transpose(1, 2)
+ value_layer = self.value(encoder_hidden_states).view(kv_shape).transpose(1, 2)
+
+ if past_key_values is not None:
+ # save all states to the cache
+ key_layer, value_layer = past_key_values.cross_attention_cache.update(
+ key_layer, value_layer, self.layer_idx
+ )
+ # set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls
+ past_key_values.is_updated[self.layer_idx] = True
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_layer,
+ key_layer,
+ value_layer,
+ attention_mask,
+ dropout=0.0 if not self.training else self.dropout.p,
+ scaling=self.scaling,
+ **kwargs,
+ )
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ return attn_output, attn_weights
+
+
+class RobertaSelfOutput(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
+ return hidden_states
+
+
+class RobertaAttention(nn.Module):
+ def __init__(self, config, is_causal=False, layer_idx=None, is_cross_attention=False):
+ super().__init__()
+ self.is_cross_attention = is_cross_attention
+ attention_class = RobertaCrossAttention if is_cross_attention else RobertaSelfAttention
+ self.self = attention_class(config, is_causal=is_causal, layer_idx=layer_idx)
+ self.output = RobertaSelfOutput(config)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.FloatTensor | None = None,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ encoder_attention_mask: torch.FloatTensor | None = None,
+ past_key_values: Cache | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor]:
+ attention_mask = attention_mask if not self.is_cross_attention else encoder_attention_mask
+ attention_output, attn_weights = self.self(
+ hidden_states,
+ encoder_hidden_states=encoder_hidden_states,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ **kwargs,
+ )
+ attention_output = self.output(attention_output, hidden_states)
+ return attention_output, attn_weights
+
+
+class RobertaIntermediate(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
+ if isinstance(config.hidden_act, str):
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
+ else:
+ self.intermediate_act_fn = config.hidden_act
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.intermediate_act_fn(hidden_states)
+ return hidden_states
+
+
+class RobertaOutput(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
+ return hidden_states
+
+
+class RobertaLayer(GradientCheckpointingLayer):
+ def __init__(self, config, layer_idx=None):
+ super().__init__()
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
+ self.seq_len_dim = 1
+ self.attention = RobertaAttention(config, is_causal=config.is_decoder, layer_idx=layer_idx)
+ self.is_decoder = config.is_decoder
+ self.add_cross_attention = config.add_cross_attention
+ if self.add_cross_attention:
+ if not self.is_decoder:
+ raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
+ self.crossattention = RobertaAttention(
+ config,
+ is_causal=False,
+ layer_idx=layer_idx,
+ is_cross_attention=True,
+ )
+ self.intermediate = RobertaIntermediate(config)
+ self.output = RobertaOutput(config)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.FloatTensor | None = None,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ encoder_attention_mask: torch.FloatTensor | None = None,
+ past_key_values: Cache | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.Tensor:
+ self_attention_output, _ = self.attention(
+ hidden_states,
+ attention_mask,
+ past_key_values=past_key_values,
+ **kwargs,
+ )
+ attention_output = self_attention_output
+
+ if self.is_decoder and encoder_hidden_states is not None:
+ if not hasattr(self, "crossattention"):
+ raise ValueError(
+ f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
+ " by setting `config.add_cross_attention=True`"
+ )
+
+ cross_attention_output, _ = self.crossattention(
+ self_attention_output,
+ None, # attention_mask
+ encoder_hidden_states,
+ encoder_attention_mask,
+ past_key_values=past_key_values,
+ **kwargs,
+ )
+ attention_output = cross_attention_output
+
+ layer_output = apply_chunking_to_forward(
+ self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
+ )
+ return layer_output
+
+ def feed_forward_chunk(self, attention_output):
+ intermediate_output = self.intermediate(attention_output)
+ layer_output = self.output(intermediate_output, attention_output)
+ return layer_output
+
+
+@auto_docstring
+class RobertaPreTrainedModel(PreTrainedModel):
+ config_class = RobertaConfig
+ base_model_prefix = "roberta"
+ supports_gradient_checkpointing = True
+ _supports_flash_attn = True
+ _supports_sdpa = True
+ _supports_flex_attn = True
+ _supports_attention_backend = True
+ _can_record_outputs = {
+ "hidden_states": RobertaLayer,
+ "attentions": RobertaSelfAttention,
+ "cross_attentions": RobertaCrossAttention,
+ }
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ """Initialize the weights"""
+ super()._init_weights(module)
+ if isinstance(module, RobertaLMHead):
+ init.zeros_(module.bias)
+ elif isinstance(module, RobertaEmbeddings):
+ init.copy_(module.position_ids, torch.arange(module.position_ids.shape[-1]).expand((1, -1)))
+ init.zeros_(module.token_type_ids)
+
+
+class RobertaEncoder(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.layer = nn.ModuleList([RobertaLayer(config, layer_idx=i) for i in range(config.num_hidden_layers)])
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.FloatTensor | None = None,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ encoder_attention_mask: torch.FloatTensor | None = None,
+ past_key_values: Cache | None = None,
+ use_cache: bool | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | BaseModelOutputWithPastAndCrossAttentions:
+ for i, layer_module in enumerate(self.layer):
+ hidden_states = layer_module(
+ hidden_states,
+ attention_mask,
+ encoder_hidden_states, # as a positional argument for gradient checkpointing
+ encoder_attention_mask=encoder_attention_mask,
+ past_key_values=past_key_values,
+ **kwargs,
+ )
+
+ return BaseModelOutputWithPastAndCrossAttentions(
+ last_hidden_state=hidden_states,
+ past_key_values=past_key_values if use_cache else None,
+ )
+
+
+class RobertaPooler(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.activation = nn.Tanh()
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ # We "pool" the model by simply taking the hidden state corresponding
+ # to the first token.
+ first_token_tensor = hidden_states[:, 0]
+ pooled_output = self.dense(first_token_tensor)
+ pooled_output = self.activation(pooled_output)
+ return pooled_output
+
+
+@auto_docstring(
+ custom_intro="""
+ The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
+ cross-attention is added between the self-attention layers, following the architecture described in [Attention is
+ all you need](https://huggingface.co/papers/1706.03762) by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
+ Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
+
+ To behave as an decoder the model needs to be initialized with the `is_decoder` argument of the configuration set
+ to `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and
+ `add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass.
+ """
+)
+class RobertaModel(RobertaPreTrainedModel):
+ _no_split_modules = ["RobertaEmbeddings", "RobertaLayer"]
+
+ def __init__(self, config, add_pooling_layer=True):
+ r"""
+ add_pooling_layer (bool, *optional*, defaults to `True`):
+ Whether to add a pooling layer
+ """
+ super().__init__(config)
+ self.config = config
+ self.gradient_checkpointing = False
+
+ self.embeddings = RobertaEmbeddings(config)
+ self.encoder = RobertaEncoder(config)
+
+ self.pooler = RobertaPooler(config) if add_pooling_layer else None
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.embeddings.word_embeddings
+
+ def set_input_embeddings(self, value):
+ self.embeddings.word_embeddings = value
+
+ @merge_with_config_defaults
+ @capture_outputs
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ token_type_ids: torch.Tensor | None = None,
+ position_ids: torch.Tensor | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ encoder_hidden_states: torch.Tensor | None = None,
+ encoder_attention_mask: torch.Tensor | None = None,
+ past_key_values: Cache | None = None,
+ use_cache: bool | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | BaseModelOutputWithPoolingAndCrossAttentions:
+ if (input_ids is None) ^ (inputs_embeds is not None):
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
+
+ if self.config.is_decoder:
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
+ else:
+ use_cache = False
+
+ if use_cache and past_key_values is None:
+ past_key_values = (
+ EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache(config=self.config))
+ if encoder_hidden_states is not None or self.config.is_encoder_decoder
+ else DynamicCache(config=self.config)
+ )
+
+ past_key_values_length = past_key_values.get_seq_length() if past_key_values is not None else 0
+
+ embedding_output = self.embeddings(
+ input_ids=input_ids,
+ position_ids=position_ids,
+ token_type_ids=token_type_ids,
+ inputs_embeds=inputs_embeds,
+ past_key_values_length=past_key_values_length,
+ )
+
+ attention_mask, encoder_attention_mask = self._create_attention_masks(
+ attention_mask=attention_mask,
+ encoder_attention_mask=encoder_attention_mask,
+ embedding_output=embedding_output,
+ encoder_hidden_states=encoder_hidden_states,
+ past_key_values=past_key_values,
+ )
+
+ encoder_outputs = self.encoder(
+ embedding_output,
+ attention_mask=attention_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ position_ids=position_ids,
+ **kwargs,
+ )
+ sequence_output = encoder_outputs.last_hidden_state
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
+
+ return BaseModelOutputWithPoolingAndCrossAttentions(
+ last_hidden_state=sequence_output,
+ pooler_output=pooled_output,
+ past_key_values=encoder_outputs.past_key_values,
+ )
+
+ def _create_attention_masks(
+ self,
+ attention_mask,
+ encoder_attention_mask,
+ embedding_output,
+ encoder_hidden_states,
+ past_key_values,
+ ):
+ if self.config.is_decoder:
+ attention_mask = create_causal_mask(
+ config=self.config,
+ inputs_embeds=embedding_output,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ )
+ else:
+ attention_mask = create_bidirectional_mask(
+ config=self.config,
+ inputs_embeds=embedding_output,
+ attention_mask=attention_mask,
+ )
+
+ if encoder_attention_mask is not None:
+ encoder_attention_mask = create_bidirectional_mask(
+ config=self.config,
+ inputs_embeds=embedding_output,
+ attention_mask=encoder_attention_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ )
+
+ return attention_mask, encoder_attention_mask
+
+
+@auto_docstring(
+ custom_intro="""
+ RoBERTa Model with a `language modeling` head on top for CLM fine-tuning.
+ """
+)
+class RobertaForCausalLM(RobertaPreTrainedModel, GenerationMixin):
+ _tied_weights_keys = {
+ "lm_head.decoder.weight": "roberta.embeddings.word_embeddings.weight",
+ "lm_head.decoder.bias": "lm_head.bias",
+ }
+
+ def __init__(self, config):
+ super().__init__(config)
+
+ if not config.is_decoder:
+ logger.warning("If you want to use `RobertaLMHeadModel` as a standalone, add `is_decoder=True.`")
+
+ self.roberta = RobertaModel(config, add_pooling_layer=False)
+ self.lm_head = RobertaLMHead(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_output_embeddings(self):
+ return self.lm_head.decoder
+
+ def set_output_embeddings(self, new_embeddings):
+ self.lm_head.decoder = new_embeddings
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ encoder_attention_mask: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ past_key_values: tuple[tuple[torch.FloatTensor]] | None = None,
+ use_cache: bool | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | CausalLMOutputWithCrossAttentions:
+ r"""
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,1]`:
+
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token.
+ This parameter can only be used when the model is initialized with `type_vocab_size` parameter with value
+ >= 2. All the value in this tensor should be always < type_vocab_size.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
+ `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
+ ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
+
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, RobertaForCausalLM, AutoConfig
+ >>> import torch
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("FacebookAI/roberta-base")
+ >>> config = AutoConfig.from_pretrained("FacebookAI/roberta-base")
+ >>> config.is_decoder = True
+ >>> model = RobertaForCausalLM.from_pretrained("FacebookAI/roberta-base", config=config)
+
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
+ >>> outputs = model(**inputs)
+
+ >>> prediction_logits = outputs.logits
+ ```"""
+ if labels is not None:
+ use_cache = False
+
+ outputs: BaseModelOutputWithPoolingAndCrossAttentions = self.roberta(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ return_dict=True,
+ **kwargs,
+ )
+
+ hidden_states = outputs.last_hidden_state
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
+
+ return CausalLMOutputWithCrossAttentions(
+ loss=loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ cross_attentions=outputs.cross_attentions,
+ )
+
+
+@auto_docstring
+class RobertaForMaskedLM(RobertaPreTrainedModel):
+ _tied_weights_keys = {
+ "lm_head.decoder.weight": "roberta.embeddings.word_embeddings.weight",
+ "lm_head.decoder.bias": "lm_head.bias",
+ }
+
+ def __init__(self, config):
+ super().__init__(config)
+
+ if config.is_decoder:
+ logger.warning(
+ "If you want to use `RobertaForMaskedLM` make sure `config.is_decoder=False` for "
+ "bi-directional self-attention."
+ )
+
+ self.roberta = RobertaModel(config, add_pooling_layer=False)
+ self.lm_head = RobertaLMHead(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_output_embeddings(self):
+ return self.lm_head.decoder
+
+ def set_output_embeddings(self, new_embeddings):
+ self.lm_head.decoder = new_embeddings
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ encoder_attention_mask: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | MaskedLMOutput:
+ r"""
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,1]`:
+
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token.
+ This parameter can only be used when the model is initialized with `type_vocab_size` parameter with value
+ >= 2. All the value in this tensor should be always < type_vocab_size.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
+ """
+ outputs = self.roberta(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ return_dict=True,
+ **kwargs,
+ )
+ sequence_output = outputs[0]
+ prediction_scores = self.lm_head(sequence_output)
+
+ masked_lm_loss = None
+ if labels is not None:
+ # move labels to correct device
+ labels = labels.to(prediction_scores.device)
+ loss_fct = CrossEntropyLoss()
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
+
+ return MaskedLMOutput(
+ loss=masked_lm_loss,
+ logits=prediction_scores,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+class RobertaLMHead(nn.Module):
+ """Roberta Head for masked language modeling."""
+
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size)
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
+
+ def forward(self, features, **kwargs):
+ x = self.dense(features)
+ x = gelu(x)
+ x = self.layer_norm(x)
+
+ # project back to size of vocabulary with bias
+ x = self.decoder(x)
+
+ return x
+
+
+@auto_docstring(
+ custom_intro="""
+ RoBERTa Model transformer with a sequence classification/regression head on top (a linear layer on top of the
+ pooled output) e.g. for GLUE tasks.
+ """
+)
+class RobertaForSequenceClassification(RobertaPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+ self.config = config
+
+ self.roberta = RobertaModel(config, add_pooling_layer=False)
+ self.classifier = RobertaClassificationHead(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | SequenceClassifierOutput:
+ r"""
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,1]`:
+
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token.
+ This parameter can only be used when the model is initialized with `type_vocab_size` parameter with value
+ >= 2. All the value in this tensor should be always < type_vocab_size.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+ outputs = self.roberta(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ return_dict=True,
+ **kwargs,
+ )
+ sequence_output = outputs[0]
+ logits = self.classifier(sequence_output)
+
+ loss = None
+ if labels is not None:
+ # move labels to correct device
+ labels = labels.to(logits.device)
+ if self.config.problem_type is None:
+ if self.num_labels == 1:
+ self.config.problem_type = "regression"
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
+ self.config.problem_type = "single_label_classification"
+ else:
+ self.config.problem_type = "multi_label_classification"
+
+ if self.config.problem_type == "regression":
+ loss_fct = MSELoss()
+ if self.num_labels == 1:
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
+ else:
+ loss = loss_fct(logits, labels)
+ elif self.config.problem_type == "single_label_classification":
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+ elif self.config.problem_type == "multi_label_classification":
+ loss_fct = BCEWithLogitsLoss()
+ loss = loss_fct(logits, labels)
+
+ return SequenceClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+class RobertaForMultipleChoice(RobertaPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.roberta = RobertaModel(config)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+ self.classifier = nn.Linear(config.hidden_size, 1)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | MultipleChoiceModelOutput:
+ r"""
+ input_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input-ids)
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,1]`:
+
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token.
+ This parameter can only be used when the model is initialized with `type_vocab_size` parameter with value
+ >= 2. All the value in this tensor should be always < type_vocab_size.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
+ num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
+ `input_ids` above)
+ position_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
+ config.max_position_embeddings - 1]`.
+
+ [What are position IDs?](../glossary#position-ids)
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_choices, sequence_length, hidden_size)`, *optional*):
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
+ model's internal embedding lookup matrix.
+ """
+ num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
+
+ flat_input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
+ flat_position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
+ flat_token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
+ flat_attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
+ flat_inputs_embeds = (
+ inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
+ if inputs_embeds is not None
+ else None
+ )
+
+ outputs = self.roberta(
+ flat_input_ids,
+ position_ids=flat_position_ids,
+ token_type_ids=flat_token_type_ids,
+ attention_mask=flat_attention_mask,
+ inputs_embeds=flat_inputs_embeds,
+ return_dict=True,
+ **kwargs,
+ )
+ pooled_output = outputs[1]
+
+ pooled_output = self.dropout(pooled_output)
+ logits = self.classifier(pooled_output)
+ reshaped_logits = logits.view(-1, num_choices)
+
+ loss = None
+ if labels is not None:
+ # move labels to correct device
+ labels = labels.to(reshaped_logits.device)
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(reshaped_logits, labels)
+
+ return MultipleChoiceModelOutput(
+ loss=loss,
+ logits=reshaped_logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+class RobertaForTokenClassification(RobertaPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+
+ self.roberta = RobertaModel(config, add_pooling_layer=False)
+ classifier_dropout = (
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
+ )
+ self.dropout = nn.Dropout(classifier_dropout)
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | TokenClassifierOutput:
+ r"""
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,1]`:
+
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token.
+ This parameter can only be used when the model is initialized with `type_vocab_size` parameter with value
+ >= 2. All the value in this tensor should be always < type_vocab_size.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
+ """
+ outputs = self.roberta(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ return_dict=True,
+ **kwargs,
+ )
+
+ sequence_output = outputs[0]
+
+ sequence_output = self.dropout(sequence_output)
+ logits = self.classifier(sequence_output)
+
+ loss = None
+ if labels is not None:
+ # move labels to correct device
+ labels = labels.to(logits.device)
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+
+ return TokenClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+class RobertaClassificationHead(nn.Module):
+ """Head for sentence-level classification tasks."""
+
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ classifier_dropout = (
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
+ )
+ self.dropout = nn.Dropout(classifier_dropout)
+ self.out_proj = nn.Linear(config.hidden_size, config.num_labels)
+
+ def forward(self, features, **kwargs):
+ x = features[:, 0, :] # take token (equiv. to [CLS])
+ x = self.dropout(x)
+ x = self.dense(x)
+ x = torch.tanh(x)
+ x = self.dropout(x)
+ x = self.out_proj(x)
+ return x
+
+
+@auto_docstring
+class RobertaForQuestionAnswering(RobertaPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+
+ self.roberta = RobertaModel(config, add_pooling_layer=False)
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ start_positions: torch.LongTensor | None = None,
+ end_positions: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | QuestionAnsweringModelOutput:
+ r"""
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,1]`:
+
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token.
+ This parameter can only be used when the model is initialized with `type_vocab_size` parameter with value
+ >= 2. All the value in this tensor should be always < type_vocab_size.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ """
+ outputs = self.roberta(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ return_dict=True,
+ **kwargs,
+ )
+
+ sequence_output = outputs[0]
+
+ logits = self.qa_outputs(sequence_output)
+ start_logits, end_logits = logits.split(1, dim=-1)
+ start_logits = start_logits.squeeze(-1).contiguous()
+ end_logits = end_logits.squeeze(-1).contiguous()
+
+ total_loss = None
+ if start_positions is not None and end_positions is not None:
+ # If we are on multi-GPU, split add a dimension
+ if len(start_positions.size()) > 1:
+ start_positions = start_positions.squeeze(-1)
+ if len(end_positions.size()) > 1:
+ end_positions = end_positions.squeeze(-1)
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
+ ignored_index = start_logits.size(1)
+ start_positions = start_positions.clamp(0, ignored_index)
+ end_positions = end_positions.clamp(0, ignored_index)
+
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
+ start_loss = loss_fct(start_logits, start_positions)
+ end_loss = loss_fct(end_logits, end_positions)
+ total_loss = (start_loss + end_loss) / 2
+
+ return QuestionAnsweringModelOutput(
+ loss=total_loss,
+ start_logits=start_logits,
+ end_logits=end_logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+__all__ = [
+ "RobertaForCausalLM",
+ "RobertaForMaskedLM",
+ "RobertaForMultipleChoice",
+ "RobertaForQuestionAnswering",
+ "RobertaForSequenceClassification",
+ "RobertaForTokenClassification",
+ "RobertaModel",
+ "RobertaPreTrainedModel",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/roberta/modular_roberta.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/roberta/modular_roberta.py
new file mode 100644
index 0000000000000000000000000000000000000000..a215c8e7a0c731af359d0ab923e674d8530b6eee
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/roberta/modular_roberta.py
@@ -0,0 +1,771 @@
+# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
+# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch RoBERTa model."""
+
+import torch
+import torch.nn as nn
+from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
+
+from ... import initialization as init
+from ...activations import gelu
+from ...generation import GenerationMixin
+from ...modeling_outputs import (
+ BaseModelOutputWithPoolingAndCrossAttentions,
+ CausalLMOutputWithCrossAttentions,
+ MaskedLMOutput,
+ MultipleChoiceModelOutput,
+ QuestionAnsweringModelOutput,
+ SequenceClassifierOutput,
+ TokenClassifierOutput,
+)
+from ...modeling_utils import PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import TransformersKwargs, auto_docstring, logging
+from ...utils.generic import can_return_tuple
+from ..bert.modeling_bert import BertCrossAttention, BertEmbeddings, BertLayer, BertModel, BertSelfAttention
+from .configuration_roberta import RobertaConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+class RobertaEmbeddings(BertEmbeddings):
+ def __init__(self, config):
+ super().__init__(config)
+
+ del self.pad_token_id
+ del self.position_embeddings
+
+ self.padding_idx = config.pad_token_id
+ self.position_embeddings = nn.Embedding(
+ config.max_position_embeddings, config.hidden_size, padding_idx=self.padding_idx
+ )
+
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ past_key_values_length: int = 0,
+ ):
+ if position_ids is None:
+ if input_ids is not None:
+ # Create the position ids from the input token ids. Any padded tokens remain padded.
+ position_ids = self.create_position_ids_from_input_ids(
+ input_ids, self.padding_idx, past_key_values_length
+ )
+ else:
+ position_ids = self.create_position_ids_from_inputs_embeds(inputs_embeds, self.padding_idx)
+
+ if input_ids is not None:
+ input_shape = input_ids.size()
+ else:
+ input_shape = inputs_embeds.size()[:-1]
+
+ batch_size, seq_length = input_shape
+
+ # Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
+ # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
+ # issue #5664
+ if token_type_ids is None:
+ if hasattr(self, "token_type_ids"):
+ # NOTE: We assume either pos ids to have bsz == 1 (broadcastable) or bsz == effective bsz (input_shape[0])
+ buffered_token_type_ids = self.token_type_ids.expand(position_ids.shape[0], -1)
+ buffered_token_type_ids = torch.gather(buffered_token_type_ids, dim=1, index=position_ids)
+ token_type_ids = buffered_token_type_ids.expand(batch_size, seq_length)
+ else:
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
+
+ if inputs_embeds is None:
+ inputs_embeds = self.word_embeddings(input_ids)
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
+ embeddings = inputs_embeds + token_type_embeddings
+
+ position_embeddings = self.position_embeddings(position_ids)
+ embeddings = embeddings + position_embeddings
+
+ embeddings = self.LayerNorm(embeddings)
+ embeddings = self.dropout(embeddings)
+ return embeddings
+
+ @staticmethod
+ def create_position_ids_from_inputs_embeds(inputs_embeds, padding_idx):
+ """
+ We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids.
+
+ Args:
+ inputs_embeds: torch.Tensor
+
+ Returns: torch.Tensor
+ """
+ input_shape = inputs_embeds.size()[:-1]
+ sequence_length = input_shape[1]
+
+ position_ids = torch.arange(
+ padding_idx + 1, sequence_length + padding_idx + 1, dtype=torch.long, device=inputs_embeds.device
+ )
+ return position_ids.unsqueeze(0).expand(input_shape)
+
+ @staticmethod
+ def create_position_ids_from_input_ids(input_ids, padding_idx, past_key_values_length=0):
+ """
+ Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols
+ are ignored. This is modified from fairseq's `utils.make_positions`.
+
+ Args:
+ x: torch.Tensor x:
+
+ Returns: torch.Tensor
+ """
+ # The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA.
+ mask = input_ids.ne(padding_idx).int()
+ incremental_indices = (torch.cumsum(mask, dim=1).type_as(mask) + past_key_values_length) * mask
+ return incremental_indices.long() + padding_idx
+
+
+class RobertaSelfAttention(BertSelfAttention):
+ pass
+
+
+class RobertaCrossAttention(BertCrossAttention):
+ pass
+
+
+class RobertaLayer(BertLayer):
+ pass
+
+
+@auto_docstring
+class RobertaPreTrainedModel(PreTrainedModel):
+ config_class = RobertaConfig
+ base_model_prefix = "roberta"
+ supports_gradient_checkpointing = True
+ _supports_flash_attn = True
+ _supports_sdpa = True
+ _supports_flex_attn = True
+ _supports_attention_backend = True
+ _can_record_outputs = {
+ "hidden_states": RobertaLayer,
+ "attentions": RobertaSelfAttention,
+ "cross_attentions": RobertaCrossAttention,
+ }
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ """Initialize the weights"""
+ super()._init_weights(module)
+ if isinstance(module, RobertaLMHead):
+ init.zeros_(module.bias)
+ elif isinstance(module, RobertaEmbeddings):
+ init.copy_(module.position_ids, torch.arange(module.position_ids.shape[-1]).expand((1, -1)))
+ init.zeros_(module.token_type_ids)
+
+
+class RobertaModel(BertModel):
+ def __init__(self, config, add_pooling_layer=True):
+ super().__init__(self, config)
+
+
+@auto_docstring(
+ custom_intro="""
+ RoBERTa Model with a `language modeling` head on top for CLM fine-tuning.
+ """
+)
+class RobertaForCausalLM(RobertaPreTrainedModel, GenerationMixin):
+ _tied_weights_keys = {
+ "lm_head.decoder.weight": "roberta.embeddings.word_embeddings.weight",
+ "lm_head.decoder.bias": "lm_head.bias",
+ }
+
+ def __init__(self, config):
+ super().__init__(config)
+
+ if not config.is_decoder:
+ logger.warning("If you want to use `RobertaLMHeadModel` as a standalone, add `is_decoder=True.`")
+
+ self.roberta = RobertaModel(config, add_pooling_layer=False)
+ self.lm_head = RobertaLMHead(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_output_embeddings(self):
+ return self.lm_head.decoder
+
+ def set_output_embeddings(self, new_embeddings):
+ self.lm_head.decoder = new_embeddings
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ encoder_attention_mask: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ past_key_values: tuple[tuple[torch.FloatTensor]] | None = None,
+ use_cache: bool | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | CausalLMOutputWithCrossAttentions:
+ r"""
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,1]`:
+
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token.
+ This parameter can only be used when the model is initialized with `type_vocab_size` parameter with value
+ >= 2. All the value in this tensor should be always < type_vocab_size.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
+ `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
+ ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
+
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, RobertaForCausalLM, AutoConfig
+ >>> import torch
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("FacebookAI/roberta-base")
+ >>> config = AutoConfig.from_pretrained("FacebookAI/roberta-base")
+ >>> config.is_decoder = True
+ >>> model = RobertaForCausalLM.from_pretrained("FacebookAI/roberta-base", config=config)
+
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
+ >>> outputs = model(**inputs)
+
+ >>> prediction_logits = outputs.logits
+ ```"""
+ if labels is not None:
+ use_cache = False
+
+ outputs: BaseModelOutputWithPoolingAndCrossAttentions = self.roberta(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ return_dict=True,
+ **kwargs,
+ )
+
+ hidden_states = outputs.last_hidden_state
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
+
+ return CausalLMOutputWithCrossAttentions(
+ loss=loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ cross_attentions=outputs.cross_attentions,
+ )
+
+
+@auto_docstring
+class RobertaForMaskedLM(RobertaPreTrainedModel):
+ _tied_weights_keys = {
+ "lm_head.decoder.weight": "roberta.embeddings.word_embeddings.weight",
+ "lm_head.decoder.bias": "lm_head.bias",
+ }
+
+ def __init__(self, config):
+ super().__init__(config)
+
+ if config.is_decoder:
+ logger.warning(
+ "If you want to use `RobertaForMaskedLM` make sure `config.is_decoder=False` for "
+ "bi-directional self-attention."
+ )
+
+ self.roberta = RobertaModel(config, add_pooling_layer=False)
+ self.lm_head = RobertaLMHead(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_output_embeddings(self):
+ return self.lm_head.decoder
+
+ def set_output_embeddings(self, new_embeddings):
+ self.lm_head.decoder = new_embeddings
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ encoder_attention_mask: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | MaskedLMOutput:
+ r"""
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,1]`:
+
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token.
+ This parameter can only be used when the model is initialized with `type_vocab_size` parameter with value
+ >= 2. All the value in this tensor should be always < type_vocab_size.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
+ """
+ outputs = self.roberta(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ return_dict=True,
+ **kwargs,
+ )
+ sequence_output = outputs[0]
+ prediction_scores = self.lm_head(sequence_output)
+
+ masked_lm_loss = None
+ if labels is not None:
+ # move labels to correct device
+ labels = labels.to(prediction_scores.device)
+ loss_fct = CrossEntropyLoss()
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
+
+ return MaskedLMOutput(
+ loss=masked_lm_loss,
+ logits=prediction_scores,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+class RobertaLMHead(nn.Module):
+ """Roberta Head for masked language modeling."""
+
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size)
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
+
+ def forward(self, features, **kwargs):
+ x = self.dense(features)
+ x = gelu(x)
+ x = self.layer_norm(x)
+
+ # project back to size of vocabulary with bias
+ x = self.decoder(x)
+
+ return x
+
+
+@auto_docstring(
+ custom_intro="""
+ RoBERTa Model transformer with a sequence classification/regression head on top (a linear layer on top of the
+ pooled output) e.g. for GLUE tasks.
+ """
+)
+class RobertaForSequenceClassification(RobertaPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+ self.config = config
+
+ self.roberta = RobertaModel(config, add_pooling_layer=False)
+ self.classifier = RobertaClassificationHead(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | SequenceClassifierOutput:
+ r"""
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,1]`:
+
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token.
+ This parameter can only be used when the model is initialized with `type_vocab_size` parameter with value
+ >= 2. All the value in this tensor should be always < type_vocab_size.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+ outputs = self.roberta(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ return_dict=True,
+ **kwargs,
+ )
+ sequence_output = outputs[0]
+ logits = self.classifier(sequence_output)
+
+ loss = None
+ if labels is not None:
+ # move labels to correct device
+ labels = labels.to(logits.device)
+ if self.config.problem_type is None:
+ if self.num_labels == 1:
+ self.config.problem_type = "regression"
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
+ self.config.problem_type = "single_label_classification"
+ else:
+ self.config.problem_type = "multi_label_classification"
+
+ if self.config.problem_type == "regression":
+ loss_fct = MSELoss()
+ if self.num_labels == 1:
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
+ else:
+ loss = loss_fct(logits, labels)
+ elif self.config.problem_type == "single_label_classification":
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+ elif self.config.problem_type == "multi_label_classification":
+ loss_fct = BCEWithLogitsLoss()
+ loss = loss_fct(logits, labels)
+
+ return SequenceClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+class RobertaForMultipleChoice(RobertaPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.roberta = RobertaModel(config)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+ self.classifier = nn.Linear(config.hidden_size, 1)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | MultipleChoiceModelOutput:
+ r"""
+ input_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input-ids)
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,1]`:
+
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token.
+ This parameter can only be used when the model is initialized with `type_vocab_size` parameter with value
+ >= 2. All the value in this tensor should be always < type_vocab_size.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
+ num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
+ `input_ids` above)
+ position_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
+ config.max_position_embeddings - 1]`.
+
+ [What are position IDs?](../glossary#position-ids)
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_choices, sequence_length, hidden_size)`, *optional*):
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
+ model's internal embedding lookup matrix.
+ """
+ num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
+
+ flat_input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
+ flat_position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
+ flat_token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
+ flat_attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
+ flat_inputs_embeds = (
+ inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
+ if inputs_embeds is not None
+ else None
+ )
+
+ outputs = self.roberta(
+ flat_input_ids,
+ position_ids=flat_position_ids,
+ token_type_ids=flat_token_type_ids,
+ attention_mask=flat_attention_mask,
+ inputs_embeds=flat_inputs_embeds,
+ return_dict=True,
+ **kwargs,
+ )
+ pooled_output = outputs[1]
+
+ pooled_output = self.dropout(pooled_output)
+ logits = self.classifier(pooled_output)
+ reshaped_logits = logits.view(-1, num_choices)
+
+ loss = None
+ if labels is not None:
+ # move labels to correct device
+ labels = labels.to(reshaped_logits.device)
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(reshaped_logits, labels)
+
+ return MultipleChoiceModelOutput(
+ loss=loss,
+ logits=reshaped_logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+class RobertaForTokenClassification(RobertaPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+
+ self.roberta = RobertaModel(config, add_pooling_layer=False)
+ classifier_dropout = (
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
+ )
+ self.dropout = nn.Dropout(classifier_dropout)
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | TokenClassifierOutput:
+ r"""
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,1]`:
+
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token.
+ This parameter can only be used when the model is initialized with `type_vocab_size` parameter with value
+ >= 2. All the value in this tensor should be always < type_vocab_size.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
+ """
+ outputs = self.roberta(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ return_dict=True,
+ **kwargs,
+ )
+
+ sequence_output = outputs[0]
+
+ sequence_output = self.dropout(sequence_output)
+ logits = self.classifier(sequence_output)
+
+ loss = None
+ if labels is not None:
+ # move labels to correct device
+ labels = labels.to(logits.device)
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+
+ return TokenClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+class RobertaClassificationHead(nn.Module):
+ """Head for sentence-level classification tasks."""
+
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ classifier_dropout = (
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
+ )
+ self.dropout = nn.Dropout(classifier_dropout)
+ self.out_proj = nn.Linear(config.hidden_size, config.num_labels)
+
+ def forward(self, features, **kwargs):
+ x = features[:, 0, :] # take token (equiv. to [CLS])
+ x = self.dropout(x)
+ x = self.dense(x)
+ x = torch.tanh(x)
+ x = self.dropout(x)
+ x = self.out_proj(x)
+ return x
+
+
+@auto_docstring
+class RobertaForQuestionAnswering(RobertaPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+
+ self.roberta = RobertaModel(config, add_pooling_layer=False)
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ start_positions: torch.LongTensor | None = None,
+ end_positions: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | QuestionAnsweringModelOutput:
+ r"""
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,1]`:
+
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token.
+ This parameter can only be used when the model is initialized with `type_vocab_size` parameter with value
+ >= 2. All the value in this tensor should be always < type_vocab_size.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ """
+ outputs = self.roberta(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ return_dict=True,
+ **kwargs,
+ )
+
+ sequence_output = outputs[0]
+
+ logits = self.qa_outputs(sequence_output)
+ start_logits, end_logits = logits.split(1, dim=-1)
+ start_logits = start_logits.squeeze(-1).contiguous()
+ end_logits = end_logits.squeeze(-1).contiguous()
+
+ total_loss = None
+ if start_positions is not None and end_positions is not None:
+ # If we are on multi-GPU, split add a dimension
+ if len(start_positions.size()) > 1:
+ start_positions = start_positions.squeeze(-1)
+ if len(end_positions.size()) > 1:
+ end_positions = end_positions.squeeze(-1)
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
+ ignored_index = start_logits.size(1)
+ start_positions = start_positions.clamp(0, ignored_index)
+ end_positions = end_positions.clamp(0, ignored_index)
+
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
+ start_loss = loss_fct(start_logits, start_positions)
+ end_loss = loss_fct(end_logits, end_positions)
+ total_loss = (start_loss + end_loss) / 2
+
+ return QuestionAnsweringModelOutput(
+ loss=total_loss,
+ start_logits=start_logits,
+ end_logits=end_logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+__all__ = [
+ "RobertaForCausalLM",
+ "RobertaForMaskedLM",
+ "RobertaForMultipleChoice",
+ "RobertaForQuestionAnswering",
+ "RobertaForSequenceClassification",
+ "RobertaForTokenClassification",
+ "RobertaModel",
+ "RobertaPreTrainedModel",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/roberta/tokenization_roberta.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/roberta/tokenization_roberta.py
new file mode 100644
index 0000000000000000000000000000000000000000..40b4e78426f6152b9ac8eb2d43b48e757b508f67
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/roberta/tokenization_roberta.py
@@ -0,0 +1,178 @@
+# Copyright 2018 The Open AI Team Authors and The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Tokenization classes for RoBERTa."""
+
+from tokenizers import Tokenizer, decoders, pre_tokenizers, processors
+from tokenizers.models import BPE
+
+from ...tokenization_utils_tokenizers import TokenizersBackend
+from ...utils import logging
+
+
+logger = logging.get_logger(__name__)
+
+VOCAB_FILES_NAMES = {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"}
+
+
+class RobertaTokenizer(TokenizersBackend):
+ r"""
+ Construct a RoBERTa tokenizer (backed by HuggingFace's tokenizers library). Based on Byte-Pair-Encoding.
+
+ This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will
+ be encoded differently whether it is at the beginning of the sentence (without space) or not:
+
+ ```python
+ >>> from transformers import RobertaTokenizer
+
+ >>> tokenizer = RobertaTokenizer.from_pretrained("FacebookAI/roberta-base")
+ >>> tokenizer("Hello world")["input_ids"]
+ [0, 31414, 232, 2]
+
+ >>> tokenizer(" Hello world")["input_ids"]
+ [0, 20920, 232, 2]
+ ```
+
+ You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer or when you
+ call it on some text, but since the model was not pretrained this way, it might yield a decrease in performance.
+
+
+
+ When used with `is_split_into_words=True`, this tokenizer needs to be instantiated with `add_prefix_space=True`.
+
+
+
+ This tokenizer inherits from [`TokenizersBackend`] which contains most of the main methods. Users should refer to
+ this superclass for more information regarding those methods.
+
+ Args:
+ vocab (`str`, `dict` or `list`, *optional*):
+ Custom vocabulary dictionary. If not provided, vocabulary is loaded from vocab_file.
+ merges (`str` or `list`, *optional*):
+ Custom merges list. If not provided, merges are loaded from merges_file.
+ errors (`str`, *optional*, defaults to `"replace"`):
+ Paradigm to follow when decoding bytes to UTF-8. See
+ [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
+ bos_token (`str`, *optional*, defaults to `""`):
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
+
+
+
+ When building a sequence using special tokens, this is not the token that is used for the beginning of
+ sequence. The token used is the `cls_token`.
+
+
+
+ eos_token (`str`, *optional*, defaults to `""`):
+ The end of sequence token.
+
+
+
+ When building a sequence using special tokens, this is not the token that is used for the end of sequence.
+ The token used is the `sep_token`.
+
+
+
+ sep_token (`str`, *optional*, defaults to `""`):
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
+ sequence classification or for a text and a question for question answering. It is also used as the last
+ token of a sequence built with special tokens.
+ cls_token (`str`, *optional*, defaults to `""`):
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
+ unk_token (`str`, *optional*, defaults to `""`):
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
+ token instead.
+ pad_token (`str`, *optional*, defaults to `""`):
+ The token used for padding, for example when batching sequences of different lengths.
+ mask_token (`str`, *optional*, defaults to `""`):
+ The token used for masking values. This is the token used when training this model with masked language
+ modeling. This is the token which the model will try to predict.
+ add_prefix_space (`bool`, *optional*, defaults to `False`):
+ Whether or not to add an initial space to the input. This allows to treat the leading word just as any
+ other word. (RoBERTa tokenizer detect beginning of words by the preceding space).
+ trim_offsets (`bool`, *optional*, defaults to `True`):
+ Whether the post processing step should trim offsets to avoid including whitespaces.
+ """
+
+ vocab_files_names = VOCAB_FILES_NAMES
+ model_input_names = ["input_ids", "attention_mask"]
+ model = BPE
+
+ def __init__(
+ self,
+ vocab: str | dict[str, int] | None = None,
+ merges: str | list[str] | None = None,
+ errors: str = "replace",
+ bos_token: str = "",
+ eos_token: str = "",
+ sep_token: str = "",
+ cls_token: str = "",
+ unk_token: str = "",
+ pad_token: str = "",
+ mask_token: str = "",
+ add_prefix_space: bool = False,
+ trim_offsets: bool = True,
+ **kwargs,
+ ):
+ self.add_prefix_space = add_prefix_space
+ self.trim_offsets = trim_offsets
+
+ if vocab is None:
+ vocab = {
+ str(pad_token): 0,
+ str(unk_token): 1,
+ str(cls_token): 2,
+ str(sep_token): 3,
+ str(mask_token): 4,
+ }
+ self._vocab = vocab
+
+ self._merges = merges or []
+
+ self._tokenizer = Tokenizer(
+ BPE(
+ vocab=self._vocab,
+ merges=self._merges,
+ dropout=None,
+ continuing_subword_prefix="",
+ end_of_word_suffix="",
+ fuse_unk=False,
+ )
+ )
+
+ self._tokenizer.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=add_prefix_space)
+ self._tokenizer.decoder = decoders.ByteLevel()
+
+ super().__init__(
+ errors=errors,
+ bos_token=bos_token,
+ eos_token=eos_token,
+ sep_token=sep_token,
+ cls_token=cls_token,
+ unk_token=unk_token,
+ pad_token=pad_token,
+ mask_token=mask_token,
+ add_prefix_space=add_prefix_space,
+ trim_offsets=trim_offsets,
+ **kwargs,
+ )
+ self._tokenizer.post_processor = processors.RobertaProcessing(
+ sep=(str(sep_token), self.sep_token_id),
+ cls=(str(cls_token), self.cls_token_id),
+ add_prefix_space=add_prefix_space,
+ trim_offsets=trim_offsets,
+ )
+
+
+__all__ = ["RobertaTokenizer"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/roberta/tokenization_roberta_old.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/roberta/tokenization_roberta_old.py
new file mode 100644
index 0000000000000000000000000000000000000000..3dceda4c310fe3b53b97048f91ed024bc6503c1f
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/roberta/tokenization_roberta_old.py
@@ -0,0 +1,262 @@
+# Copyright 2018 The Open AI Team Authors and The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Fast Tokenization classes for RoBERTa."""
+
+import json
+
+from tokenizers import processors
+
+from ...tokenization_utils_base import AddedToken, BatchEncoding
+from ...tokenization_utils_tokenizers import PreTrainedTokenizerFast
+from ...utils import logging
+from .tokenization_roberta import RobertaTokenizer
+
+
+logger = logging.get_logger(__name__)
+
+VOCAB_FILES_NAMES = {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"}
+
+
+class RobertaTokenizerFast(PreTrainedTokenizerFast):
+ """
+ Construct a "fast" RoBERTa tokenizer (backed by HuggingFace's *tokenizers* library), derived from the GPT-2
+ tokenizer, using byte-level Byte-Pair-Encoding.
+
+ This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will
+ be encoded differently whether it is at the beginning of the sentence (without space) or not:
+
+ ```python
+ >>> from transformers import RobertaTokenizerFast
+
+ >>> tokenizer = RobertaTokenizerFast.from_pretrained("FacebookAI/roberta-base")
+ >>> tokenizer("Hello world")["input_ids"]
+ [0, 31414, 232, 2]
+
+ >>> tokenizer(" Hello world")["input_ids"]
+ [0, 20920, 232, 2]
+ ```
+
+ You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer or when you
+ call it on some text, but since the model was not pretrained this way, it might yield a decrease in performance.
+
+
+
+ When used with `is_split_into_words=True`, this tokenizer needs to be instantiated with `add_prefix_space=True`.
+
+
+
+ This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
+ refer to this superclass for more information regarding those methods.
+
+ Args:
+ vocab_file (`str`):
+ Path to the vocabulary file.
+ merges_file (`str`):
+ Path to the merges file.
+ errors (`str`, *optional*, defaults to `"replace"`):
+ Paradigm to follow when decoding bytes to UTF-8. See
+ [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
+ bos_token (`str`, *optional*, defaults to `""`):
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
+
+
+
+ When building a sequence using special tokens, this is not the token that is used for the beginning of
+ sequence. The token used is the `cls_token`.
+
+
+
+ eos_token (`str`, *optional*, defaults to `""`):
+ The end of sequence token.
+
+
+
+ When building a sequence using special tokens, this is not the token that is used for the end of sequence.
+ The token used is the `sep_token`.
+
+
+
+ sep_token (`str`, *optional*, defaults to `""`):
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
+ sequence classification or for a text and a question for question answering. It is also used as the last
+ token of a sequence built with special tokens.
+ cls_token (`str`, *optional*, defaults to `""`):
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
+ unk_token (`str`, *optional*, defaults to `""`):
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
+ token instead.
+ pad_token (`str`, *optional*, defaults to `""`):
+ The token used for padding, for example when batching sequences of different lengths.
+ mask_token (`str`, *optional*, defaults to `""`):
+ The token used for masking values. This is the token used when training this model with masked language
+ modeling. This is the token which the model will try to predict.
+ add_prefix_space (`bool`, *optional*, defaults to `False`):
+ Whether or not to add an initial space to the input. This allows to treat the leading word just as any
+ other word. (RoBERTa tokenizer detect beginning of words by the preceding space).
+ trim_offsets (`bool`, *optional*, defaults to `True`):
+ Whether the post processing step should trim offsets to avoid including whitespaces.
+ """
+
+ vocab_files_names = VOCAB_FILES_NAMES
+ model_input_names = ["input_ids", "attention_mask"]
+ slow_tokenizer_class = RobertaTokenizer
+
+ def __init__(
+ self,
+ vocab_file=None,
+ merges_file=None,
+ tokenizer_file=None,
+ errors="replace",
+ bos_token="",
+ eos_token="",
+ sep_token="",
+ cls_token="",
+ unk_token="",
+ pad_token="",
+ mask_token="",
+ add_prefix_space=False,
+ trim_offsets=True,
+ **kwargs,
+ ):
+ mask_token = (
+ AddedToken(mask_token, lstrip=True, rstrip=False, normalized=False)
+ if isinstance(mask_token, str)
+ else mask_token
+ )
+ super().__init__(
+ vocab_file,
+ merges_file,
+ tokenizer_file=tokenizer_file,
+ errors=errors,
+ bos_token=bos_token,
+ eos_token=eos_token,
+ sep_token=sep_token,
+ cls_token=cls_token,
+ unk_token=unk_token,
+ pad_token=pad_token,
+ mask_token=mask_token,
+ add_prefix_space=add_prefix_space,
+ trim_offsets=trim_offsets,
+ **kwargs,
+ )
+
+ tokenizer_component = "post_processor"
+ tokenizer_component_instance = getattr(self.backend_tokenizer, tokenizer_component, None)
+ if tokenizer_component_instance:
+ state = json.loads(tokenizer_component_instance.__getstate__())
+
+ # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class`
+ if "sep" in state:
+ state["sep"] = tuple(state["sep"])
+ if "cls" in state:
+ state["cls"] = tuple(state["cls"])
+
+ changes_to_apply = False
+
+ if state.get("add_prefix_space", add_prefix_space) != add_prefix_space:
+ state["add_prefix_space"] = add_prefix_space
+ changes_to_apply = True
+
+ if state.get("trim_offsets", trim_offsets) != trim_offsets:
+ state["trim_offsets"] = trim_offsets
+ changes_to_apply = True
+
+ if changes_to_apply:
+ component_class = getattr(processors, state.pop("type"))
+ new_value = component_class(**state)
+ setattr(self.backend_tokenizer, tokenizer_component, new_value)
+
+ @property
+ def mask_token(self) -> str:
+ """
+ `str`: Mask token, to use when training a model with masked-language modeling. Log an error if used while not
+ having been set.
+
+ Roberta tokenizer has a special mask token to be usable in the fill-mask pipeline. The mask token will greedily
+ comprise the space before the **.
+ """
+ if self._mask_token is None:
+ if self.verbose:
+ logger.error("Using mask_token, but it is not set yet.")
+ return None
+ return str(self._mask_token)
+
+ @mask_token.setter
+ def mask_token(self, value):
+ """
+ Overriding the default behavior of the mask token to have it eat the space before it.
+
+ This is needed to preserve backward compatibility with all the previously used models based on Roberta.
+ """
+ # Mask token behave like a normal word, i.e. include the space before it
+ # So we set lstrip to True
+ value = AddedToken(value, lstrip=True, rstrip=False) if isinstance(value, str) else value
+ self._mask_token = value
+
+ def _batch_encode_plus(self, *args, **kwargs) -> BatchEncoding:
+ is_split_into_words = kwargs.get("is_split_into_words", False)
+ assert self.add_prefix_space or not is_split_into_words, (
+ f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True "
+ "to use it with pretokenized inputs."
+ )
+
+ return super()._batch_encode_plus(*args, **kwargs)
+
+ def _encode_plus(self, *args, **kwargs) -> BatchEncoding:
+ is_split_into_words = kwargs.get("is_split_into_words", False)
+
+ assert self.add_prefix_space or not is_split_into_words, (
+ f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True "
+ "to use it with pretokenized inputs."
+ )
+
+ return super()._encode_plus(*args, **kwargs)
+
+ def save_vocabulary(self, save_directory: str, filename_prefix: str | None = None) -> tuple[str]:
+ files = self._tokenizer.model.save(save_directory, name=filename_prefix)
+ return tuple(files)
+
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
+ output = [self.bos_token_id] + token_ids_0 + [self.eos_token_id]
+ if token_ids_1 is None:
+ return output
+
+ return output + [self.eos_token_id] + token_ids_1 + [self.eos_token_id]
+
+ def create_token_type_ids_from_sequences(
+ self, token_ids_0: list[int], token_ids_1: list[int] | None = None
+ ) -> list[int]:
+ """
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. RoBERTa does not
+ make use of token type ids, therefore a list of zeros is returned.
+
+ Args:
+ token_ids_0 (`list[int]`):
+ List of IDs.
+ token_ids_1 (`list[int]`, *optional*):
+ Optional second list of IDs for sequence pairs.
+
+ Returns:
+ `list[int]`: List of zeros.
+ """
+ sep = [self.sep_token_id]
+ cls = [self.cls_token_id]
+
+ if token_ids_1 is None:
+ return len(cls + token_ids_0 + sep) * [0]
+ return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]
+
+
+__all__ = ["RobertaTokenizerFast"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/roc_bert/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/roc_bert/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..eb847b03b75587df50ebb17140401da0be4dea22
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/roc_bert/__init__.py
@@ -0,0 +1,28 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_roc_bert import *
+ from .modeling_roc_bert import *
+ from .tokenization_roc_bert import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/roc_bert/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/roc_bert/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bc32913377cf25179a67f343f9dc385c4c68285c
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/roc_bert/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/roc_bert/__pycache__/configuration_roc_bert.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/roc_bert/__pycache__/configuration_roc_bert.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..319a1d9e2b2a07a5a7add9b048f8c9e14fb9b849
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/roc_bert/__pycache__/configuration_roc_bert.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/roc_bert/__pycache__/modeling_roc_bert.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/roc_bert/__pycache__/modeling_roc_bert.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dc471f3874e6b3c3b785f818c73377954eda54c1
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/roc_bert/__pycache__/modeling_roc_bert.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/roc_bert/__pycache__/tokenization_roc_bert.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/roc_bert/__pycache__/tokenization_roc_bert.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..36a033aca32ea96bd4689380e93dcedcd3d55c2f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/roc_bert/__pycache__/tokenization_roc_bert.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/roc_bert/configuration_roc_bert.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/roc_bert/configuration_roc_bert.py
new file mode 100644
index 0000000000000000000000000000000000000000..4600e6cab1eb3390fa6f0dda435d7b573f8263d2
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/roc_bert/configuration_roc_bert.py
@@ -0,0 +1,89 @@
+# Copyright 2022 WeChatAI and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""RoCBert model configuration"""
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring
+
+
+@auto_docstring(checkpoint="weiweishi/roc-bert-base-zh")
+@strict
+class RoCBertConfig(PreTrainedConfig):
+ r"""
+ enable_pronunciation (`bool`, *optional*, defaults to `True`):
+ Whether or not the model use pronunciation embed when training.
+ enable_shape (`bool`, *optional*, defaults to `True`):
+ Whether or not the model use shape embed when training.
+ pronunciation_embed_dim (`int`, *optional*, defaults to 768):
+ Dimension of the pronunciation_embed.
+ pronunciation_vocab_size (`int`, *optional*, defaults to 910):
+ Pronunciation Vocabulary size of the RoCBert model. Defines the number of different tokens that can be
+ represented by the `input_pronunciation_ids` passed when calling [`RoCBertModel`].
+ shape_embed_dim (`int`, *optional*, defaults to 512):
+ Dimension of the shape_embed.
+ shape_vocab_size (`int`, *optional*, defaults to 24858):
+ Shape Vocabulary size of the RoCBert model. Defines the number of different tokens that can be represented
+ by the `input_shape_ids` passed when calling [`RoCBertModel`].
+ concat_input (`bool`, *optional*, defaults to `True`):
+ Defines the way of merging the shape_embed, pronunciation_embed and word_embed, if the value is true,
+ output_embed = torch.cat((word_embed, shape_embed, pronunciation_embed), -1), else output_embed =
+ (word_embed + shape_embed + pronunciation_embed) / 3
+
+ Example:
+
+ ```python
+ >>> from transformers import RoCBertModel, RoCBertConfig
+
+ >>> # Initializing a RoCBert weiweishi/roc-bert-base-zh style configuration
+ >>> configuration = RoCBertConfig()
+
+ >>> # Initializing a model from the weiweishi/roc-bert-base-zh style configuration
+ >>> model = RoCBertModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "roc_bert"
+
+ vocab_size: int = 30522
+ hidden_size: int = 768
+ num_hidden_layers: int = 12
+ num_attention_heads: int = 12
+ intermediate_size: int = 3072
+ hidden_act: str = "gelu"
+ hidden_dropout_prob: float | int = 0.1
+ attention_probs_dropout_prob: float | int = 0.1
+ max_position_embeddings: int = 512
+ type_vocab_size: int = 2
+ initializer_range: float = 0.02
+ layer_norm_eps: float = 1e-12
+ use_cache: bool = True
+ pad_token_id: int | None = 0
+ classifier_dropout: float | int | None = None
+ enable_pronunciation: bool = True
+ enable_shape: bool = True
+ pronunciation_embed_dim: int = 768
+ pronunciation_vocab_size: int = 910
+ shape_embed_dim: int = 512
+ shape_vocab_size: int = 24858
+ concat_input: bool = True
+ is_decoder: bool = False
+ add_cross_attention: bool = False
+ tie_word_embeddings: bool = True
+
+
+__all__ = ["RoCBertConfig"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/roc_bert/modeling_roc_bert.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/roc_bert/modeling_roc_bert.py
new file mode 100644
index 0000000000000000000000000000000000000000..40bd4dcf5964f936205075237a4b514308cda8ae
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/roc_bert/modeling_roc_bert.py
@@ -0,0 +1,1660 @@
+# Copyright 2022 WeChatAI The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch RoCBert model."""
+
+from collections.abc import Callable
+
+import torch
+from torch import nn
+from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...cache_utils import Cache, DynamicCache, EncoderDecoderCache
+from ...generation import GenerationMixin
+from ...masking_utils import create_bidirectional_mask, create_causal_mask
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import (
+ BaseModelOutputWithPastAndCrossAttentions,
+ BaseModelOutputWithPoolingAndCrossAttentions,
+ CausalLMOutputWithCrossAttentions,
+ MaskedLMOutput,
+ MultipleChoiceModelOutput,
+ QuestionAnsweringModelOutput,
+ SequenceClassifierOutput,
+ TokenClassifierOutput,
+)
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
+from ...processing_utils import Unpack
+from ...pytorch_utils import apply_chunking_to_forward
+from ...utils import TransformersKwargs, auto_docstring, logging
+from ...utils.generic import can_return_tuple, merge_with_config_defaults
+from ...utils.output_capturing import capture_outputs
+from .configuration_roc_bert import RoCBertConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+class RoCBertEmbeddings(nn.Module):
+ """Construct the embeddings from word, position, shape, pronunciation and token_type embeddings."""
+
+ def __init__(self, config):
+ super().__init__()
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
+ self.pronunciation_embed = nn.Embedding(
+ config.pronunciation_vocab_size, config.pronunciation_embed_dim, padding_idx=config.pad_token_id
+ )
+ self.shape_embed = nn.Embedding(
+ config.shape_vocab_size, config.shape_embed_dim, padding_idx=config.pad_token_id
+ )
+ self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
+ self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
+
+ self.enable_pronunciation = config.enable_pronunciation
+ self.enable_shape = config.enable_shape
+
+ if config.concat_input:
+ input_dim = config.hidden_size
+ if self.enable_pronunciation:
+ pronunciation_dim = config.pronunciation_embed_dim
+ input_dim += pronunciation_dim
+ if self.enable_shape:
+ shape_dim = config.shape_embed_dim
+ input_dim += shape_dim
+ self.map_inputs_layer = torch.nn.Linear(input_dim, config.hidden_size)
+ else:
+ self.map_inputs_layer = None
+
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
+ self.register_buffer(
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
+ )
+ self.register_buffer(
+ "token_type_ids",
+ torch.zeros(self.position_ids.size(), dtype=torch.long, device=self.position_ids.device),
+ persistent=False,
+ )
+
+ def forward(
+ self,
+ input_ids=None,
+ input_shape_ids=None,
+ input_pronunciation_ids=None,
+ token_type_ids=None,
+ position_ids=None,
+ inputs_embeds=None,
+ past_key_values_length=0,
+ ):
+ if input_ids is not None:
+ input_shape = input_ids.size()
+ else:
+ input_shape = inputs_embeds.size()[:-1]
+
+ batch_size, seq_length = input_shape
+
+ if position_ids is None:
+ position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length]
+
+ # Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
+ # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
+ # issue #5664
+ if token_type_ids is None:
+ if hasattr(self, "token_type_ids"):
+ # NOTE: We assume either pos ids to have bsz == 1 (broadcastable) or bsz == effective bsz (input_shape[0])
+ buffered_token_type_ids = self.token_type_ids.expand(position_ids.shape[0], -1)
+ buffered_token_type_ids = torch.gather(buffered_token_type_ids, dim=1, index=position_ids)
+ token_type_ids = buffered_token_type_ids.expand(batch_size, seq_length)
+ else:
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
+
+ if self.map_inputs_layer is None:
+ if inputs_embeds is None:
+ inputs_embeds = self.word_embeddings(input_ids)
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
+ embeddings = inputs_embeds + token_type_embeddings
+ position_embeddings = self.position_embeddings(position_ids)
+ embeddings = embeddings + position_embeddings
+ embeddings = self.LayerNorm(embeddings)
+ embeddings = self.dropout(embeddings)
+
+ denominator = 1
+ embedding_in = torch.clone(embeddings)
+ if self.enable_shape and input_shape_ids is not None:
+ embedding_shape = self.shape_embed(input_shape_ids)
+ embedding_in += embedding_shape
+ denominator += 1
+ if self.enable_pronunciation and input_pronunciation_ids is not None:
+ embedding_pronunciation = self.pronunciation_embed(input_pronunciation_ids)
+ embedding_in += embedding_pronunciation
+ denominator += 1
+
+ embedding_in /= denominator
+ return embedding_in
+ else:
+ if inputs_embeds is None:
+ inputs_embeds = self.word_embeddings(input_ids) # embedding_word
+ device = inputs_embeds.device
+
+ embedding_in = torch.clone(inputs_embeds)
+ if self.enable_shape:
+ if input_shape_ids is None:
+ input_shape_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
+ embedding_shape = self.shape_embed(input_shape_ids)
+ embedding_in = torch.cat((embedding_in, embedding_shape), -1)
+ if self.enable_pronunciation:
+ if input_pronunciation_ids is None:
+ input_pronunciation_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
+ embedding_pronunciation = self.pronunciation_embed(input_pronunciation_ids)
+ embedding_in = torch.cat((embedding_in, embedding_pronunciation), -1)
+
+ embedding_in = self.map_inputs_layer(embedding_in) # batch_size * seq_len * hidden_dim
+
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
+ embedding_in += token_type_embeddings
+ position_embeddings = self.position_embeddings(position_ids)
+ embedding_in += position_embeddings
+
+ embedding_in = self.LayerNorm(embedding_in)
+ embedding_in = self.dropout(embedding_in)
+ return embedding_in
+
+
+# Copied from transformers.models.bert.modeling_bert.eager_attention_forward
+def eager_attention_forward(
+ module: nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: torch.Tensor | None,
+ scaling: float | None = None,
+ dropout: float = 0.0,
+ **kwargs: Unpack[TransformersKwargs],
+):
+ if scaling is None:
+ scaling = query.size(-1) ** -0.5
+
+ # Take the dot product between "query" and "key" to get the raw attention scores.
+ attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
+
+ if attention_mask is not None:
+ attn_weights = attn_weights + attention_mask
+
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
+
+ attn_output = torch.matmul(attn_weights, value)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+
+ return attn_output, attn_weights
+
+
+# Copied from transformers.models.bert.modeling_bert.BertSelfAttention with Bert->RoCBert
+class RoCBertSelfAttention(nn.Module):
+ def __init__(self, config, is_causal=False, layer_idx=None):
+ super().__init__()
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
+ raise ValueError(
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
+ f"heads ({config.num_attention_heads})"
+ )
+ self.config = config
+
+ self.num_attention_heads = config.num_attention_heads
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
+ self.scaling = self.attention_head_size**-0.5
+
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
+
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
+
+ self.is_decoder = config.is_decoder
+ self.is_causal = is_causal
+ self.layer_idx = layer_idx
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.FloatTensor | None = None,
+ past_key_values: Cache | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor]:
+ input_shape = hidden_states.shape[:-1]
+ hidden_shape = (*input_shape, -1, self.attention_head_size)
+
+ # get all proj
+ query_layer = self.query(hidden_states).view(*hidden_shape).transpose(1, 2)
+ key_layer = self.key(hidden_states).view(*hidden_shape).transpose(1, 2)
+ value_layer = self.value(hidden_states).view(*hidden_shape).transpose(1, 2)
+
+ if past_key_values is not None:
+ # decoder-only bert can have a simple dynamic cache for example
+ current_past_key_values = past_key_values
+ if isinstance(past_key_values, EncoderDecoderCache):
+ current_past_key_values = past_key_values.self_attention_cache
+
+ # save all key/value_layer to cache to be re-used for fast auto-regressive generation
+ key_layer, value_layer = current_past_key_values.update(key_layer, value_layer, self.layer_idx)
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_layer,
+ key_layer,
+ value_layer,
+ attention_mask,
+ dropout=0.0 if not self.training else self.dropout.p,
+ scaling=self.scaling,
+ **kwargs,
+ )
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ return attn_output, attn_weights
+
+
+# Copied from transformers.models.bert.modeling_bert.BertCrossAttention with Bert->RoCBert
+class RoCBertCrossAttention(nn.Module):
+ def __init__(self, config, is_causal=False, layer_idx=None):
+ super().__init__()
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
+ raise ValueError(
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
+ f"heads ({config.num_attention_heads})"
+ )
+ self.config = config
+
+ self.num_attention_heads = config.num_attention_heads
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
+ self.scaling = self.attention_head_size**-0.5
+
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
+
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
+
+ self.is_causal = is_causal
+ self.layer_idx = layer_idx
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ past_key_values: EncoderDecoderCache | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor]:
+ # determine input shapes
+ input_shape = hidden_states.shape[:-1]
+
+ hidden_shape = (*input_shape, -1, self.attention_head_size)
+
+ # get query proj
+ query_layer = self.query(hidden_states).view(hidden_shape).transpose(1, 2)
+
+ is_updated = past_key_values.is_updated.get(self.layer_idx) if past_key_values is not None else False
+ if past_key_values is not None and is_updated:
+ # reuse k,v, cross_attentions
+ key_layer = past_key_values.cross_attention_cache.layers[self.layer_idx].keys
+ value_layer = past_key_values.cross_attention_cache.layers[self.layer_idx].values
+ else:
+ kv_shape = (*encoder_hidden_states.shape[:-1], -1, self.attention_head_size)
+ key_layer = self.key(encoder_hidden_states).view(kv_shape).transpose(1, 2)
+ value_layer = self.value(encoder_hidden_states).view(kv_shape).transpose(1, 2)
+
+ if past_key_values is not None:
+ # save all states to the cache
+ key_layer, value_layer = past_key_values.cross_attention_cache.update(
+ key_layer, value_layer, self.layer_idx
+ )
+ # set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls
+ past_key_values.is_updated[self.layer_idx] = True
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_layer,
+ key_layer,
+ value_layer,
+ attention_mask,
+ dropout=0.0 if not self.training else self.dropout.p,
+ scaling=self.scaling,
+ **kwargs,
+ )
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ return attn_output, attn_weights
+
+
+# Copied from transformers.models.bert.modeling_bert.BertSelfOutput with Bert->RoCBert
+class RoCBertSelfOutput(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
+ return hidden_states
+
+
+# Copied from transformers.models.bert.modeling_bert.BertAttention with Bert->RoCBert,BERT->ROC_BERT
+class RoCBertAttention(nn.Module):
+ def __init__(self, config, is_causal=False, layer_idx=None, is_cross_attention=False):
+ super().__init__()
+ self.is_cross_attention = is_cross_attention
+ attention_class = RoCBertCrossAttention if is_cross_attention else RoCBertSelfAttention
+ self.self = attention_class(config, is_causal=is_causal, layer_idx=layer_idx)
+ self.output = RoCBertSelfOutput(config)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.FloatTensor | None = None,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ encoder_attention_mask: torch.FloatTensor | None = None,
+ past_key_values: Cache | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor]:
+ attention_mask = attention_mask if not self.is_cross_attention else encoder_attention_mask
+ attention_output, attn_weights = self.self(
+ hidden_states,
+ encoder_hidden_states=encoder_hidden_states,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ **kwargs,
+ )
+ attention_output = self.output(attention_output, hidden_states)
+ return attention_output, attn_weights
+
+
+# Copied from transformers.models.bert.modeling_bert.BertIntermediate with Bert->RoCBert
+class RoCBertIntermediate(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
+ if isinstance(config.hidden_act, str):
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
+ else:
+ self.intermediate_act_fn = config.hidden_act
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.intermediate_act_fn(hidden_states)
+ return hidden_states
+
+
+# Copied from transformers.models.bert.modeling_bert.BertOutput with Bert->RoCBert
+class RoCBertOutput(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
+ return hidden_states
+
+
+# Copied from transformers.models.bert.modeling_bert.BertLayer with Bert->RoCBert
+class RoCBertLayer(GradientCheckpointingLayer):
+ def __init__(self, config, layer_idx=None):
+ super().__init__()
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
+ self.seq_len_dim = 1
+ self.attention = RoCBertAttention(config, is_causal=config.is_decoder, layer_idx=layer_idx)
+ self.is_decoder = config.is_decoder
+ self.add_cross_attention = config.add_cross_attention
+ if self.add_cross_attention:
+ if not self.is_decoder:
+ raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
+ self.crossattention = RoCBertAttention(
+ config,
+ is_causal=False,
+ layer_idx=layer_idx,
+ is_cross_attention=True,
+ )
+ self.intermediate = RoCBertIntermediate(config)
+ self.output = RoCBertOutput(config)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.FloatTensor | None = None,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ encoder_attention_mask: torch.FloatTensor | None = None,
+ past_key_values: Cache | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.Tensor:
+ self_attention_output, _ = self.attention(
+ hidden_states,
+ attention_mask,
+ past_key_values=past_key_values,
+ **kwargs,
+ )
+ attention_output = self_attention_output
+
+ if self.is_decoder and encoder_hidden_states is not None:
+ if not hasattr(self, "crossattention"):
+ raise ValueError(
+ f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
+ " by setting `config.add_cross_attention=True`"
+ )
+
+ cross_attention_output, _ = self.crossattention(
+ self_attention_output,
+ None, # attention_mask
+ encoder_hidden_states,
+ encoder_attention_mask,
+ past_key_values=past_key_values,
+ **kwargs,
+ )
+ attention_output = cross_attention_output
+
+ layer_output = apply_chunking_to_forward(
+ self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
+ )
+ return layer_output
+
+ def feed_forward_chunk(self, attention_output):
+ intermediate_output = self.intermediate(attention_output)
+ layer_output = self.output(intermediate_output, attention_output)
+ return layer_output
+
+
+# Copied from transformers.models.bert.modeling_bert.BertEncoder with Bert->RoCBert
+class RoCBertEncoder(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.layer = nn.ModuleList([RoCBertLayer(config, layer_idx=i) for i in range(config.num_hidden_layers)])
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.FloatTensor | None = None,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ encoder_attention_mask: torch.FloatTensor | None = None,
+ past_key_values: Cache | None = None,
+ use_cache: bool | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | BaseModelOutputWithPastAndCrossAttentions:
+ for i, layer_module in enumerate(self.layer):
+ hidden_states = layer_module(
+ hidden_states,
+ attention_mask,
+ encoder_hidden_states, # as a positional argument for gradient checkpointing
+ encoder_attention_mask=encoder_attention_mask,
+ past_key_values=past_key_values,
+ **kwargs,
+ )
+
+ return BaseModelOutputWithPastAndCrossAttentions(
+ last_hidden_state=hidden_states,
+ past_key_values=past_key_values if use_cache else None,
+ )
+
+
+# Copied from transformers.models.bert.modeling_bert.BertPooler with Bert->RoCBert
+class RoCBertPooler(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.activation = nn.Tanh()
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ # We "pool" the model by simply taking the hidden state corresponding
+ # to the first token.
+ first_token_tensor = hidden_states[:, 0]
+ pooled_output = self.dense(first_token_tensor)
+ pooled_output = self.activation(pooled_output)
+ return pooled_output
+
+
+# Copied from transformers.models.bert.modeling_bert.BertPredictionHeadTransform with Bert->RoCBert
+class RoCBertPredictionHeadTransform(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ if isinstance(config.hidden_act, str):
+ self.transform_act_fn = ACT2FN[config.hidden_act]
+ else:
+ self.transform_act_fn = config.hidden_act
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.transform_act_fn(hidden_states)
+ hidden_states = self.LayerNorm(hidden_states)
+ return hidden_states
+
+
+# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->RoCBert
+class RoCBertLMPredictionHead(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.transform = RoCBertPredictionHeadTransform(config)
+
+ # The output weights are the same as the input embeddings, but there is
+ # an output-only bias for each token.
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=True)
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
+
+ def forward(self, hidden_states):
+ hidden_states = self.transform(hidden_states)
+ hidden_states = self.decoder(hidden_states)
+ return hidden_states
+
+
+# Copied from transformers.models.bert.modeling_bert.BertOnlyMLMHead with Bert->RoCBert
+class RoCBertOnlyMLMHead(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.predictions = RoCBertLMPredictionHead(config)
+
+ def forward(self, sequence_output: torch.Tensor) -> torch.Tensor:
+ prediction_scores = self.predictions(sequence_output)
+ return prediction_scores
+
+
+@auto_docstring
+class RoCBertPreTrainedModel(PreTrainedModel):
+ config_class = RoCBertConfig
+ base_model_prefix = "roc_bert"
+ supports_gradient_checkpointing = True
+ _supports_flash_attn = True
+ _supports_sdpa = True
+ _supports_flex_attn = True
+ _supports_attention_backend = True
+ _can_record_outputs = {
+ "hidden_states": RoCBertLayer,
+ "attentions": RoCBertSelfAttention,
+ "cross_attentions": RoCBertCrossAttention,
+ }
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ """Initialize the weights"""
+ super()._init_weights(module)
+ if isinstance(module, RoCBertLMPredictionHead):
+ init.zeros_(module.bias)
+ elif isinstance(module, RoCBertEmbeddings):
+ init.copy_(module.position_ids, torch.arange(module.position_ids.shape[-1]).expand((1, -1)))
+ init.zeros_(module.token_type_ids)
+
+
+@auto_docstring(
+ custom_intro="""
+
+ The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
+ cross-attention is added between the self-attention layers, following the architecture described in [Attention is
+ all you need](https://huggingface.co/papers/1706.03762) by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
+ Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
+
+ To behave as an decoder the model needs to be initialized with the `is_decoder` argument of the configuration set
+ to `True`. To be used in a Seq2Seq model, the model needs to be initialized with both `is_decoder` argument and
+ `add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass.
+ """
+)
+class RoCBertModel(RoCBertPreTrainedModel):
+ def __init__(self, config, add_pooling_layer=True):
+ r"""
+ add_pooling_layer (bool, *optional*, defaults to `True`):
+ Whether to add a pooling layer
+ """
+ super().__init__(config)
+ self.config = config
+ self.gradient_checkpointing = False
+
+ self.embeddings = RoCBertEmbeddings(config)
+ self.encoder = RoCBertEncoder(config)
+
+ self.pooler = RoCBertPooler(config) if add_pooling_layer else None
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ # Copied from transformers.models.bert.modeling_bert.BertModel.get_input_embeddings
+ def get_input_embeddings(self):
+ return self.embeddings.word_embeddings
+
+ # Copied from transformers.models.bert.modeling_bert.BertModel.set_input_embeddings
+ def set_input_embeddings(self, value):
+ self.embeddings.word_embeddings = value
+
+ def get_pronunciation_embeddings(self):
+ return self.embeddings.pronunciation_embed
+
+ def set_pronunciation_embeddings(self, value):
+ self.embeddings.pronunciation_embed = value
+
+ def get_shape_embeddings(self):
+ return self.embeddings.shape_embed
+
+ def set_shape_embeddings(self, value):
+ self.embeddings.shape_embed = value
+
+ @merge_with_config_defaults
+ @capture_outputs
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ input_shape_ids: torch.Tensor | None = None,
+ input_pronunciation_ids: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ token_type_ids: torch.Tensor | None = None,
+ position_ids: torch.Tensor | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ encoder_hidden_states: torch.Tensor | None = None,
+ encoder_attention_mask: torch.Tensor | None = None,
+ past_key_values: Cache | None = None,
+ use_cache: bool | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | BaseModelOutputWithPoolingAndCrossAttentions:
+ r"""
+ input_shape_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ Indices of input sequence tokens in the shape vocabulary.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input_shape_ids)
+ input_pronunciation_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ Indices of input sequence tokens in the pronunciation vocabulary.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input_pronunciation_ids)
+ """
+ if (input_ids is None) ^ (inputs_embeds is not None):
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
+
+ if self.config.is_decoder:
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
+ else:
+ use_cache = False
+
+ if use_cache and past_key_values is None:
+ past_key_values = EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache(config=self.config))
+
+ past_key_values_length = past_key_values.get_seq_length() if past_key_values is not None else 0
+
+ embedding_output = self.embeddings(
+ input_ids=input_ids,
+ input_shape_ids=input_shape_ids,
+ input_pronunciation_ids=input_pronunciation_ids,
+ position_ids=position_ids,
+ token_type_ids=token_type_ids,
+ inputs_embeds=inputs_embeds,
+ past_key_values_length=past_key_values_length,
+ )
+
+ attention_mask, encoder_attention_mask = self._create_attention_masks(
+ attention_mask=attention_mask,
+ encoder_attention_mask=encoder_attention_mask,
+ embedding_output=embedding_output,
+ encoder_hidden_states=encoder_hidden_states,
+ past_key_values=past_key_values,
+ )
+
+ encoder_outputs = self.encoder(
+ embedding_output,
+ attention_mask=attention_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ position_ids=position_ids,
+ **kwargs,
+ )
+ sequence_output = encoder_outputs[0]
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
+
+ return BaseModelOutputWithPoolingAndCrossAttentions(
+ last_hidden_state=sequence_output,
+ pooler_output=pooled_output,
+ past_key_values=encoder_outputs.past_key_values,
+ )
+
+ # Copied from transformers.models.bert.modeling_bert.BertModel._create_attention_masks
+ def _create_attention_masks(
+ self,
+ attention_mask,
+ encoder_attention_mask,
+ embedding_output,
+ encoder_hidden_states,
+ past_key_values,
+ ):
+ if self.config.is_decoder:
+ attention_mask = create_causal_mask(
+ config=self.config,
+ inputs_embeds=embedding_output,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ )
+ else:
+ attention_mask = create_bidirectional_mask(
+ config=self.config,
+ inputs_embeds=embedding_output,
+ attention_mask=attention_mask,
+ )
+
+ if encoder_attention_mask is not None:
+ encoder_attention_mask = create_bidirectional_mask(
+ config=self.config,
+ inputs_embeds=embedding_output,
+ attention_mask=encoder_attention_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ )
+
+ return attention_mask, encoder_attention_mask
+
+
+@auto_docstring(
+ custom_intro="""
+ RoCBert Model with contrastive loss and masked_lm_loss during the pretraining.
+ """
+)
+class RoCBertForPreTraining(RoCBertPreTrainedModel):
+ _tied_weights_keys = {
+ "cls.predictions.decoder.bias": "cls.predictions.bias",
+ "cls.predictions.decoder.weight": "roc_bert.embeddings.word_embeddings.weight",
+ }
+
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.roc_bert = RoCBertModel(config)
+ self.cls = RoCBertOnlyMLMHead(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ # Copied from transformers.models.bert.modeling_bert.BertForPreTraining.get_output_embeddings
+ def get_output_embeddings(self):
+ return self.cls.predictions.decoder
+
+ # Copied from transformers.models.bert.modeling_bert.BertForPreTraining.set_output_embeddings
+ def set_output_embeddings(self, new_embeddings):
+ self.cls.predictions.decoder = new_embeddings
+ self.cls.predictions.bias = new_embeddings.bias
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ input_shape_ids: torch.Tensor | None = None,
+ input_pronunciation_ids: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ token_type_ids: torch.Tensor | None = None,
+ attack_input_ids: torch.Tensor | None = None,
+ attack_input_shape_ids: torch.Tensor | None = None,
+ attack_input_pronunciation_ids: torch.Tensor | None = None,
+ attack_attention_mask: torch.Tensor | None = None,
+ attack_token_type_ids: torch.Tensor | None = None,
+ position_ids: torch.Tensor | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ labels_input_ids: torch.Tensor | None = None,
+ labels_input_shape_ids: torch.Tensor | None = None,
+ labels_input_pronunciation_ids: torch.Tensor | None = None,
+ labels_attention_mask: torch.Tensor | None = None,
+ labels_token_type_ids: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | MaskedLMOutput:
+ r"""
+ input_shape_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ Indices of input sequence tokens in the shape vocabulary.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input_shape_ids)
+ input_pronunciation_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ Indices of input sequence tokens in the pronunciation vocabulary.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input_pronunciation_ids)
+ attack_input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ attack sample ids for computing the contrastive loss. Indices should be in `[-100, 0, ...,
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked),
+ the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
+ attack_input_shape_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ attack sample shape ids for computing the contrastive loss. Indices should be in `[-100, 0, ...,
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked),
+ the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
+ attack_input_pronunciation_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ attack sample pronunciation ids for computing the contrastive loss. Indices should be in `[-100, 0,
+ ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
+ attack_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Mask to avoid performing attention on padding token indices for the attack sample. Mask values selected in
+ `[0, 1]`: `1` for tokens that are NOT MASKED, `0` for MASKED tokens.
+ attack_token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Segment token indices to indicate different portions of the attack inputs. Indices are selected in `[0, 1]`:
+ `0` corresponds to a sentence A token, `1` corresponds to a sentence B token.
+ labels_input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ target ids for computing the contrastive loss and masked_lm_loss . Indices should be in `[-100, 0, ...,
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked),
+ the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
+ labels_input_shape_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ target shape ids for computing the contrastive loss and masked_lm_loss . Indices should be in `[-100,
+ 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
+ labels_input_pronunciation_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ target pronunciation ids for computing the contrastive loss and masked_lm_loss . Indices should be in
+ `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
+ ignored (masked), the loss is only computed for the tokens with labels in `[0, ...,
+ config.vocab_size]`
+ labels_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Mask to avoid performing attention on padding token indices for the label sample. Mask values selected in
+ `[0, 1]`: `1` for tokens that are NOT MASKED, `0` for MASKED tokens.
+ labels_token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Segment token indices to indicate different portions of the label inputs. Indices are selected in `[0, 1]`:
+ `0` corresponds to a sentence A token, `1` corresponds to a sentence B token.
+
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, RoCBertForPreTraining
+ >>> import torch
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("weiweishi/roc-bert-base-zh")
+ >>> model = RoCBertForPreTraining.from_pretrained("weiweishi/roc-bert-base-zh")
+
+ >>> inputs = tokenizer("你好,很高兴认识你", return_tensors="pt")
+ >>> attack_inputs = {}
+ >>> for key in list(inputs.keys()):
+ ... attack_inputs[f"attack_{key}"] = inputs[key]
+ >>> label_inputs = {}
+ >>> for key in list(inputs.keys()):
+ ... label_inputs[f"labels_{key}"] = inputs[key]
+
+ >>> inputs.update(label_inputs)
+ >>> inputs.update(attack_inputs)
+ >>> outputs = model(**inputs)
+
+ >>> logits = outputs.logits
+ >>> logits.shape
+ torch.Size([1, 11, 21128])
+ ```
+ """
+ outputs = self.roc_bert(
+ input_ids,
+ input_shape_ids=input_shape_ids,
+ input_pronunciation_ids=input_pronunciation_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ return_dict=True,
+ **kwargs,
+ )
+
+ sequence_output, pooled_output = outputs[:2]
+ prediction_scores = self.cls(sequence_output)
+
+ loss = None
+ if labels_input_ids is not None:
+ loss_fct = CrossEntropyLoss() # -100 index = padding token
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels_input_ids.view(-1))
+
+ if attack_input_ids is not None:
+ batch_size, _ = labels_input_ids.shape
+ device = labels_input_ids.device
+
+ target_inputs = torch.clone(labels_input_ids)
+ target_inputs[target_inputs == -100] = self.config.pad_token_id
+
+ labels_output = self.roc_bert(
+ target_inputs,
+ input_shape_ids=labels_input_shape_ids,
+ input_pronunciation_ids=labels_input_pronunciation_ids,
+ attention_mask=labels_attention_mask,
+ token_type_ids=labels_token_type_ids,
+ )
+ attack_output = self.roc_bert(
+ attack_input_ids,
+ input_shape_ids=attack_input_shape_ids,
+ input_pronunciation_ids=attack_input_pronunciation_ids,
+ attention_mask=attack_attention_mask,
+ token_type_ids=attack_token_type_ids,
+ )
+
+ labels_pooled_output = labels_output[1]
+ attack_pooled_output = attack_output[1]
+
+ pooled_output_norm = torch.nn.functional.normalize(pooled_output, dim=-1)
+ labels_pooled_output_norm = torch.nn.functional.normalize(labels_pooled_output, dim=-1)
+ attack_pooled_output_norm = torch.nn.functional.normalize(attack_pooled_output, dim=-1)
+
+ sim_matrix = torch.matmul(pooled_output_norm, attack_pooled_output_norm.T) # batch_size * hidden_dim
+ sim_matrix_target = torch.matmul(labels_pooled_output_norm, attack_pooled_output_norm.T)
+ batch_labels = torch.tensor(list(range(batch_size)), device=device)
+ contrastive_loss = (
+ loss_fct(100 * sim_matrix.view(batch_size, -1), batch_labels.view(-1))
+ + loss_fct(100 * sim_matrix_target.view(batch_size, -1), batch_labels.view(-1))
+ ) / 2
+
+ loss = contrastive_loss + masked_lm_loss
+ else:
+ loss = masked_lm_loss
+
+ return MaskedLMOutput(
+ loss=loss,
+ logits=prediction_scores,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+class RoCBertForMaskedLM(RoCBertPreTrainedModel):
+ _tied_weights_keys = {
+ "cls.predictions.decoder.bias": "cls.predictions.bias",
+ "cls.predictions.decoder.weight": "roc_bert.embeddings.word_embeddings.weight",
+ }
+
+ # Copied from transformers.models.bert.modeling_bert.BertForMaskedLM.__init__ with Bert->RoCBert,bert->roc_bert
+ def __init__(self, config):
+ super().__init__(config)
+
+ if config.is_decoder:
+ logger.warning(
+ "If you want to use `RoCBertForMaskedLM` make sure `config.is_decoder=False` for "
+ "bi-directional self-attention."
+ )
+
+ self.roc_bert = RoCBertModel(config, add_pooling_layer=False)
+ self.cls = RoCBertOnlyMLMHead(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ # Copied from transformers.models.bert.modeling_bert.BertForMaskedLM.get_output_embeddings
+ def get_output_embeddings(self):
+ return self.cls.predictions.decoder
+
+ # Copied from transformers.models.bert.modeling_bert.BertForMaskedLM.set_output_embeddings
+ def set_output_embeddings(self, new_embeddings):
+ self.cls.predictions.decoder = new_embeddings
+ self.cls.predictions.bias = new_embeddings.bias
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ input_shape_ids: torch.Tensor | None = None,
+ input_pronunciation_ids: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ token_type_ids: torch.Tensor | None = None,
+ position_ids: torch.Tensor | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ encoder_hidden_states: torch.Tensor | None = None,
+ encoder_attention_mask: torch.Tensor | None = None,
+ labels: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | MaskedLMOutput:
+ r"""
+ input_shape_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ Indices of input sequence tokens in the shape vocabulary.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input_shape_ids)
+ input_pronunciation_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ Indices of input sequence tokens in the pronunciation vocabulary.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input_pronunciation_ids)
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
+
+ Example:
+ ```python
+ >>> from transformers import AutoTokenizer, RoCBertForMaskedLM
+ >>> import torch
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("weiweishi/roc-bert-base-zh")
+ >>> model = RoCBertForMaskedLM.from_pretrained("weiweishi/roc-bert-base-zh")
+
+ >>> inputs = tokenizer("法国是首都[MASK].", return_tensors="pt")
+
+ >>> with torch.no_grad():
+ ... logits = model(**inputs).logits
+
+ >>> # retrieve index of {mask}
+ >>> mask_token_index = (inputs.input_ids == tokenizer.mask_token_id)[0].nonzero(as_tuple=True)[0]
+
+ >>> predicted_token_id = logits[0, mask_token_index].argmax(axis=-1)
+ >>> tokenizer.decode(predicted_token_id)
+ '.'
+ ```
+ """
+ outputs = self.roc_bert(
+ input_ids,
+ input_shape_ids=input_shape_ids,
+ input_pronunciation_ids=input_pronunciation_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ return_dict=True,
+ **kwargs,
+ )
+
+ sequence_output = outputs[0]
+ prediction_scores = self.cls(sequence_output)
+
+ masked_lm_loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss() # -100 index = padding token
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
+
+ return MaskedLMOutput(
+ loss=masked_lm_loss,
+ logits=prediction_scores,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ RoCBert Model with a `language modeling` head on top for CLM fine-tuning.
+ """
+)
+class RoCBertForCausalLM(RoCBertPreTrainedModel, GenerationMixin):
+ _tied_weights_keys = {
+ "cls.predictions.decoder.bias": "cls.predictions.bias",
+ "cls.predictions.decoder.weight": "roc_bert.embeddings.word_embeddings.weight",
+ }
+
+ # Copied from transformers.models.bert.modeling_bert.BertLMHeadModel.__init__ with BertLMHeadModel->RoCBertForCausalLM,Bert->RoCBert,bert->roc_bert
+ def __init__(self, config):
+ super().__init__(config)
+
+ if not config.is_decoder:
+ logger.warning("If you want to use `RoCRoCBertForCausalLM` as a standalone, add `is_decoder=True.`")
+
+ self.roc_bert = RoCBertModel(config, add_pooling_layer=False)
+ self.cls = RoCBertOnlyMLMHead(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ # Copied from transformers.models.bert.modeling_bert.BertLMHeadModel.get_output_embeddings
+ def get_output_embeddings(self):
+ return self.cls.predictions.decoder
+
+ # Copied from transformers.models.bert.modeling_bert.BertLMHeadModel.set_output_embeddings
+ def set_output_embeddings(self, new_embeddings):
+ self.cls.predictions.decoder = new_embeddings
+ self.cls.predictions.bias = new_embeddings.bias
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ input_shape_ids: torch.Tensor | None = None,
+ input_pronunciation_ids: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ token_type_ids: torch.Tensor | None = None,
+ position_ids: torch.Tensor | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ encoder_hidden_states: torch.Tensor | None = None,
+ encoder_attention_mask: torch.Tensor | None = None,
+ past_key_values: list[torch.Tensor] | None = None,
+ labels: torch.Tensor | None = None,
+ use_cache: bool | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | CausalLMOutputWithCrossAttentions:
+ r"""
+ input_shape_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ Indices of input sequence tokens in the shape vocabulary.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input_shape_ids)
+ input_pronunciation_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ Indices of input sequence tokens in the pronunciation vocabulary.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input_pronunciation_ids)
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
+ `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
+ ignored (masked), the loss is only computed for the tokens with labels n `[0, ..., config.vocab_size]`.
+
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, RoCBertForCausalLM, RoCBertConfig
+ >>> import torch
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("weiweishi/roc-bert-base-zh")
+ >>> config = RoCBertConfig.from_pretrained("weiweishi/roc-bert-base-zh")
+ >>> config.is_decoder = True
+ >>> model = RoCBertForCausalLM.from_pretrained("weiweishi/roc-bert-base-zh", config=config)
+
+ >>> inputs = tokenizer("你好,很高兴认识你", return_tensors="pt")
+ >>> outputs = model(**inputs)
+
+ >>> prediction_logits = outputs.logits
+ ```
+ """
+ outputs: BaseModelOutputWithPoolingAndCrossAttentions = self.roc_bert(
+ input_ids,
+ input_shape_ids=input_shape_ids,
+ input_pronunciation_ids=input_pronunciation_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ return_dict=True,
+ **kwargs,
+ )
+
+ hidden_states = outputs.last_hidden_state
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
+ logits = self.cls(hidden_states[:, slice_indices, :])
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
+
+ return CausalLMOutputWithCrossAttentions(
+ loss=loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ cross_attentions=outputs.cross_attentions,
+ )
+
+ def prepare_inputs_for_generation(
+ self,
+ input_ids,
+ input_shape_ids=None,
+ input_pronunciation_ids=None,
+ past_key_values=None,
+ attention_mask=None,
+ **model_kwargs,
+ ):
+ # Overwritten -- `input_pronunciation_ids`
+
+ model_inputs = super().prepare_inputs_for_generation(
+ input_ids=input_ids,
+ past_key_values=past_key_values,
+ attention_mask=attention_mask,
+ **model_kwargs,
+ )
+
+ # cut decoder_input_ids if past_key_values is used
+ if past_key_values is not None:
+ if input_shape_ids is not None:
+ model_inputs["input_shape_ids"] = input_shape_ids[:, -1:]
+ if input_pronunciation_ids is not None:
+ model_inputs["input_pronunciation_ids"] = input_pronunciation_ids[:, -1:]
+
+ return model_inputs
+
+
+@auto_docstring(
+ custom_intro="""
+ RoCBert Model transformer with a sequence classification/regression head on top (a linear layer on top of
+ the pooled output) e.g. for GLUE tasks.
+ """
+)
+class RoCBertForSequenceClassification(RoCBertPreTrainedModel):
+ # Copied from transformers.models.bert.modeling_bert.BertForSequenceClassification.__init__ with Bert->RoCBert,bert->roc_bert
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+ self.config = config
+
+ self.roc_bert = RoCBertModel(config)
+ classifier_dropout = (
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
+ )
+ self.dropout = nn.Dropout(classifier_dropout)
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ input_shape_ids: torch.Tensor | None = None,
+ input_pronunciation_ids: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ token_type_ids: torch.Tensor | None = None,
+ position_ids: torch.Tensor | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ labels: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | SequenceClassifierOutput:
+ r"""
+ input_shape_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ Indices of input sequence tokens in the shape vocabulary.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input_shape_ids)
+ input_pronunciation_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ Indices of input sequence tokens in the pronunciation vocabulary.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input_pronunciation_ids)
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+ outputs = self.roc_bert(
+ input_ids,
+ input_shape_ids=input_shape_ids,
+ input_pronunciation_ids=input_pronunciation_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ return_dict=True,
+ **kwargs,
+ )
+
+ pooled_output = outputs[1]
+
+ pooled_output = self.dropout(pooled_output)
+ logits = self.classifier(pooled_output)
+
+ loss = None
+ if labels is not None:
+ if self.config.problem_type is None:
+ if self.num_labels == 1:
+ self.config.problem_type = "regression"
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
+ self.config.problem_type = "single_label_classification"
+ else:
+ self.config.problem_type = "multi_label_classification"
+
+ if self.config.problem_type == "regression":
+ loss_fct = MSELoss()
+ if self.num_labels == 1:
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
+ else:
+ loss = loss_fct(logits, labels)
+ elif self.config.problem_type == "single_label_classification":
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+ elif self.config.problem_type == "multi_label_classification":
+ loss_fct = BCEWithLogitsLoss()
+ loss = loss_fct(logits, labels)
+
+ return SequenceClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+class RoCBertForMultipleChoice(RoCBertPreTrainedModel):
+ # Copied from transformers.models.bert.modeling_bert.BertForMultipleChoice.__init__ with Bert->RoCBert,bert->roc_bert
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.roc_bert = RoCBertModel(config)
+ classifier_dropout = (
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
+ )
+ self.dropout = nn.Dropout(classifier_dropout)
+ self.classifier = nn.Linear(config.hidden_size, 1)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ input_shape_ids: torch.Tensor | None = None,
+ input_pronunciation_ids: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ token_type_ids: torch.Tensor | None = None,
+ position_ids: torch.Tensor | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ labels: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | MultipleChoiceModelOutput:
+ r"""
+ input_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input-ids)
+ input_shape_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`):
+ Indices of input sequence tokens in the shape vocabulary.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input_shape_ids)
+ input_pronunciation_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`):
+ Indices of input sequence tokens in the pronunciation vocabulary.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input_pronunciation_ids)
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
+ 1]`:
+
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ position_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
+ config.max_position_embeddings - 1]`.
+
+ [What are position IDs?](../glossary#position-ids)
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_choices, sequence_length, hidden_size)`, *optional*):
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
+ is useful if you want more control over how to convert *input_ids* indices into associated vectors than the
+ model's internal embedding lookup matrix.
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
+ num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
+ `input_ids` above)
+ """
+ num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
+
+ input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
+ input_shape_ids = input_shape_ids.view(-1, input_shape_ids.size(-1)) if input_shape_ids is not None else None
+ input_pronunciation_ids = (
+ input_pronunciation_ids.view(-1, input_pronunciation_ids.size(-1))
+ if input_pronunciation_ids is not None
+ else None
+ )
+ attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
+ token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
+ position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
+ inputs_embeds = (
+ inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
+ if inputs_embeds is not None
+ else None
+ )
+
+ outputs = self.roc_bert(
+ input_ids,
+ input_shape_ids=input_shape_ids,
+ input_pronunciation_ids=input_pronunciation_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ return_dict=True,
+ **kwargs,
+ )
+
+ pooled_output = outputs[1]
+
+ pooled_output = self.dropout(pooled_output)
+ logits = self.classifier(pooled_output)
+ reshaped_logits = logits.view(-1, num_choices)
+
+ loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(reshaped_logits, labels)
+
+ return MultipleChoiceModelOutput(
+ loss=loss,
+ logits=reshaped_logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+class RoCBertForTokenClassification(RoCBertPreTrainedModel):
+ # Copied from transformers.models.bert.modeling_bert.BertForTokenClassification.__init__ with Bert->RoCBert,bert->roc_bert
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+
+ self.roc_bert = RoCBertModel(config, add_pooling_layer=False)
+ classifier_dropout = (
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
+ )
+ self.dropout = nn.Dropout(classifier_dropout)
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ input_shape_ids: torch.Tensor | None = None,
+ input_pronunciation_ids: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ token_type_ids: torch.Tensor | None = None,
+ position_ids: torch.Tensor | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ labels: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | TokenClassifierOutput:
+ r"""
+ input_shape_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ Indices of input sequence tokens in the shape vocabulary.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input_shape_ids)
+ input_pronunciation_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ Indices of input sequence tokens in the pronunciation vocabulary.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input_pronunciation_ids)
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
+ """
+ outputs = self.roc_bert(
+ input_ids,
+ input_shape_ids=input_shape_ids,
+ input_pronunciation_ids=input_pronunciation_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ return_dict=True,
+ **kwargs,
+ )
+
+ sequence_output = outputs[0]
+
+ sequence_output = self.dropout(sequence_output)
+ logits = self.classifier(sequence_output)
+
+ loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+
+ return TokenClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+class RoCBertForQuestionAnswering(RoCBertPreTrainedModel):
+ # Copied from transformers.models.bert.modeling_bert.BertForQuestionAnswering.__init__ with Bert->RoCBert,bert->roc_bert
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+
+ self.roc_bert = RoCBertModel(config, add_pooling_layer=False)
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ input_shape_ids: torch.Tensor | None = None,
+ input_pronunciation_ids: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ token_type_ids: torch.Tensor | None = None,
+ position_ids: torch.Tensor | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ start_positions: torch.Tensor | None = None,
+ end_positions: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor] | QuestionAnsweringModelOutput:
+ r"""
+ input_shape_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ Indices of input sequence tokens in the shape vocabulary.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input_shape_ids)
+ input_pronunciation_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ Indices of input sequence tokens in the pronunciation vocabulary.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input_pronunciation_ids)
+ """
+ outputs = self.roc_bert(
+ input_ids,
+ input_shape_ids=input_shape_ids,
+ input_pronunciation_ids=input_pronunciation_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ return_dict=True,
+ **kwargs,
+ )
+
+ sequence_output = outputs[0]
+
+ logits = self.qa_outputs(sequence_output)
+ start_logits, end_logits = logits.split(1, dim=-1)
+ start_logits = start_logits.squeeze(-1)
+ end_logits = end_logits.squeeze(-1)
+
+ total_loss = None
+ if start_positions is not None and end_positions is not None:
+ # If we are on multi-GPU, split add a dimension
+ if len(start_positions.size()) > 1:
+ start_positions = start_positions.squeeze(-1)
+ if len(end_positions.size()) > 1:
+ end_positions = end_positions.squeeze(-1)
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
+ ignored_index = start_logits.size(1)
+ start_positions = start_positions.clamp(0, ignored_index)
+ end_positions = end_positions.clamp(0, ignored_index)
+
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
+ start_loss = loss_fct(start_logits, start_positions)
+ end_loss = loss_fct(end_logits, end_positions)
+ total_loss = (start_loss + end_loss) / 2
+
+ return QuestionAnsweringModelOutput(
+ loss=total_loss,
+ start_logits=start_logits,
+ end_logits=end_logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+__all__ = [
+ "RoCBertForCausalLM",
+ "RoCBertForMaskedLM",
+ "RoCBertForMultipleChoice",
+ "RoCBertForPreTraining",
+ "RoCBertForQuestionAnswering",
+ "RoCBertForSequenceClassification",
+ "RoCBertForTokenClassification",
+ "RoCBertLayer",
+ "RoCBertModel",
+ "RoCBertPreTrainedModel",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/roc_bert/tokenization_roc_bert.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/roc_bert/tokenization_roc_bert.py
new file mode 100644
index 0000000000000000000000000000000000000000..3663ee35f21be3b04af3a931a2e32cee8c39bc46
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/roc_bert/tokenization_roc_bert.py
@@ -0,0 +1,1319 @@
+# Copyright 2022 WeChatAI and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Tokenization classes for RoCBert."""
+
+import collections
+import itertools
+import json
+import os
+import unicodedata
+
+from ...tokenization_python import PreTrainedTokenizer, _is_control, _is_punctuation, _is_whitespace
+from ...tokenization_utils_base import (
+ ENCODE_KWARGS_DOCSTRING,
+ ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING,
+ BatchEncoding,
+ EncodedInput,
+ EncodedInputPair,
+ PaddingStrategy,
+ PreTokenizedInput,
+ PreTokenizedInputPair,
+ TensorType,
+ TextInput,
+ TextInputPair,
+ TruncationStrategy,
+)
+from ...utils import add_end_docstrings, logging
+
+
+logger = logging.get_logger(__name__)
+
+VOCAB_FILES_NAMES = {
+ "vocab_file": "vocab.txt",
+ "word_shape_file": "word_shape.json",
+ "word_pronunciation_file": "word_pronunciation.json",
+}
+
+
+def load_vocab(vocab_file):
+ """Loads a vocabulary file into a dictionary."""
+ vocab = collections.OrderedDict()
+ with open(vocab_file, "r", encoding="utf-8") as reader:
+ tokens = reader.readlines()
+ for index, token in enumerate(tokens):
+ token = token.rstrip("\n")
+ vocab[token] = index
+ return vocab
+
+
+def whitespace_tokenize(text):
+ """Runs basic whitespace cleaning and splitting on a piece of text."""
+ text = text.strip()
+ if not text:
+ return []
+ tokens = text.split()
+ return tokens
+
+
+class RoCBertTokenizer(PreTrainedTokenizer):
+ r"""
+ Args:
+ Construct a RoCBert tokenizer. Based on WordPiece. This tokenizer inherits from [`PreTrainedTokenizer`] which
+ contains most of the main methods. Users should refer to this superclass for more information regarding those
+ methods.
+ vocab_file (`str`):
+ File containing the vocabulary.
+ word_shape_file (`str`):
+ File containing the word => shape info.
+ word_pronunciation_file (`str`):
+ File containing the word => pronunciation info.
+ do_lower_case (`bool`, *optional*, defaults to `True`):
+ Whether or not to lowercase the input when tokenizing.
+ do_basic_tokenize (`bool`, *optional*, defaults to `True`):
+ Whether or not to do basic tokenization before WordPiece.
+ never_split (`Iterable`, *optional*):
+ Collection of tokens which will never be split during tokenization. Only has an effect when
+ `do_basic_tokenize=True`
+ unk_token (`str`, *optional*, defaults to `"[UNK]"`):
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
+ token instead.
+ sep_token (`str`, *optional*, defaults to `"[SEP]"`):
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
+ sequence classification or for a text and a question for question answering. It is also used as the last
+ token of a sequence built with special tokens.
+ pad_token (`str`, *optional*, defaults to `"[PAD]"`):
+ The token used for padding, for example when batching sequences of different lengths.
+ cls_token (`str`, *optional*, defaults to `"[CLS]"`):
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
+ mask_token (`str`, *optional*, defaults to `"[MASK]"`):
+ The token used for masking values. This is the token used when training this model with masked language
+ modeling. This is the token which the model will try to predict.
+ tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
+ Whether or not to tokenize Chinese characters. This should likely be deactivated for Japanese (see this
+ [issue](https://github.com/huggingface/transformers/issues/328)).
+ strip_accents (`bool`, *optional*):
+ Whether or not to strip all accents. If this option is not specified, then it will be determined by the
+ value for `lowercase` (as in the original BERT).
+ """
+
+ vocab_files_names = VOCAB_FILES_NAMES
+
+ def __init__(
+ self,
+ vocab_file,
+ word_shape_file,
+ word_pronunciation_file,
+ do_lower_case=True,
+ do_basic_tokenize=True,
+ never_split=None,
+ unk_token="[UNK]",
+ sep_token="[SEP]",
+ pad_token="[PAD]",
+ cls_token="[CLS]",
+ mask_token="[MASK]",
+ tokenize_chinese_chars=True,
+ strip_accents=None,
+ **kwargs,
+ ):
+ for cur_file in [vocab_file, word_shape_file, word_pronunciation_file]:
+ if cur_file is None or not os.path.isfile(cur_file):
+ raise ValueError(
+ f"Can't find a vocabulary file at path '{vocab_file}'. To load the vocabulary from a Google "
+ "pretrained model use `tokenizer = RoCBertTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`"
+ )
+
+ self.vocab = load_vocab(vocab_file)
+
+ with open(word_shape_file, "r", encoding="utf8") as in_file:
+ self.word_shape = json.load(in_file)
+
+ with open(word_pronunciation_file, "r", encoding="utf8") as in_file:
+ self.word_pronunciation = json.load(in_file)
+
+ self.ids_to_tokens = collections.OrderedDict([(ids, tok) for tok, ids in self.vocab.items()])
+
+ self.do_basic_tokenize = do_basic_tokenize
+ if do_basic_tokenize:
+ self.basic_tokenizer = RoCBertBasicTokenizer(
+ do_lower_case=do_lower_case,
+ never_split=never_split,
+ tokenize_chinese_chars=tokenize_chinese_chars,
+ strip_accents=strip_accents,
+ )
+ self.wordpiece_tokenizer = RoCBertWordpieceTokenizer(vocab=self.vocab, unk_token=str(unk_token))
+ super().__init__(
+ do_lower_case=do_lower_case,
+ do_basic_tokenize=do_basic_tokenize,
+ never_split=never_split,
+ unk_token=unk_token,
+ sep_token=sep_token,
+ pad_token=pad_token,
+ cls_token=cls_token,
+ mask_token=mask_token,
+ tokenize_chinese_chars=tokenize_chinese_chars,
+ strip_accents=strip_accents,
+ **kwargs,
+ )
+
+ @add_end_docstrings(ENCODE_KWARGS_DOCSTRING, ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
+ def __call__(
+ self,
+ text: TextInput | list[TextInput],
+ text_pair: TextInput | list[TextInput] | None = None,
+ text_target: TextInput | list[TextInput] | None = None,
+ add_special_tokens: bool = True,
+ padding: bool | str | PaddingStrategy = False,
+ truncation: bool | str | TruncationStrategy = None,
+ max_length: int | None = None,
+ max_target_length: int | None = None,
+ stride: int = 0,
+ is_split_into_words: bool = False,
+ pad_to_multiple_of: int | None = None,
+ padding_side: str | None = None,
+ return_tensors: str | TensorType | None = None,
+ return_token_type_ids: bool | None = None,
+ return_attention_mask: bool | None = None,
+ return_overflowing_tokens: bool = False,
+ return_special_tokens_mask: bool = False,
+ return_offsets_mapping: bool = False,
+ return_length: bool = False,
+ verbose: bool = True,
+ **kwargs,
+ ) -> BatchEncoding:
+ # Handle text_target for seq2seq tasks
+ if text_target is not None:
+ # Tokenize source text
+ encodings = self.__call__(
+ text=text,
+ text_pair=text_pair,
+ add_special_tokens=add_special_tokens,
+ padding=padding,
+ truncation=truncation,
+ max_length=max_length,
+ stride=stride,
+ is_split_into_words=is_split_into_words,
+ pad_to_multiple_of=pad_to_multiple_of,
+ padding_side=padding_side,
+ return_tensors=return_tensors,
+ return_token_type_ids=return_token_type_ids,
+ return_attention_mask=return_attention_mask,
+ return_overflowing_tokens=return_overflowing_tokens,
+ return_special_tokens_mask=return_special_tokens_mask,
+ return_offsets_mapping=return_offsets_mapping,
+ return_length=return_length,
+ verbose=verbose,
+ **kwargs,
+ )
+ # Tokenize target text
+ target_length = max_target_length if max_target_length is not None else max_length
+ target_encodings = self.__call__(
+ text=text_target,
+ add_special_tokens=add_special_tokens,
+ padding=padding,
+ truncation=truncation if target_length is not None else False,
+ max_length=target_length,
+ stride=0,
+ is_split_into_words=is_split_into_words,
+ pad_to_multiple_of=pad_to_multiple_of,
+ padding_side=padding_side,
+ return_tensors=return_tensors,
+ return_token_type_ids=False,
+ return_attention_mask=return_attention_mask,
+ return_overflowing_tokens=False,
+ return_special_tokens_mask=False,
+ return_offsets_mapping=False,
+ return_length=False,
+ verbose=verbose,
+ **kwargs,
+ )
+ # Add labels from target input_ids
+ encodings["labels"] = target_encodings["input_ids"]
+ return encodings
+
+ # Detect batch vs single
+ is_batched = isinstance(text, (list, tuple)) and (
+ not is_split_into_words or (len(text) > 0 and isinstance(text[0], (list, tuple)))
+ )
+
+ if is_batched:
+ # Build batch tuples of (text, text_pair) if provided
+ batch_text_or_text_pairs = list(zip(text, text_pair)) if text_pair is not None else text
+ return self.batch_encode_plus(
+ batch_text_or_text_pairs=batch_text_or_text_pairs, # type: ignore[arg-type]
+ add_special_tokens=add_special_tokens,
+ padding=padding,
+ truncation=truncation,
+ max_length=max_length,
+ stride=stride,
+ is_split_into_words=is_split_into_words,
+ pad_to_multiple_of=pad_to_multiple_of,
+ padding_side=padding_side,
+ return_tensors=return_tensors,
+ return_token_type_ids=return_token_type_ids,
+ return_attention_mask=return_attention_mask,
+ return_overflowing_tokens=return_overflowing_tokens,
+ return_special_tokens_mask=return_special_tokens_mask,
+ return_offsets_mapping=return_offsets_mapping,
+ return_length=return_length,
+ verbose=verbose,
+ **kwargs,
+ )
+ else:
+ return self.encode_plus(
+ text=text,
+ text_pair=text_pair,
+ add_special_tokens=add_special_tokens,
+ padding=padding,
+ truncation=truncation,
+ max_length=max_length,
+ stride=stride,
+ is_split_into_words=is_split_into_words,
+ pad_to_multiple_of=pad_to_multiple_of,
+ padding_side=padding_side,
+ return_tensors=return_tensors,
+ return_token_type_ids=return_token_type_ids,
+ return_attention_mask=return_attention_mask,
+ return_overflowing_tokens=return_overflowing_tokens,
+ return_special_tokens_mask=return_special_tokens_mask,
+ return_offsets_mapping=return_offsets_mapping,
+ return_length=return_length,
+ verbose=verbose,
+ **kwargs,
+ )
+
+ def encode_plus(
+ self,
+ text: TextInput | PreTokenizedInput | EncodedInput,
+ text_pair: TextInput | PreTokenizedInput | EncodedInput | None = None,
+ add_special_tokens: bool = True,
+ padding: bool | str | PaddingStrategy = False,
+ truncation: bool | str | TruncationStrategy = None,
+ max_length: int | None = None,
+ stride: int = 0,
+ is_split_into_words: bool = False,
+ pad_to_multiple_of: int | None = None,
+ padding_side: str | None = None,
+ return_tensors: str | TensorType | None = None,
+ return_token_type_ids: bool | None = None,
+ return_attention_mask: bool | None = None,
+ return_overflowing_tokens: bool = False,
+ return_special_tokens_mask: bool = False,
+ return_offsets_mapping: bool = False,
+ return_length: bool = False,
+ verbose: bool = True,
+ **kwargs,
+ ) -> BatchEncoding:
+ padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(
+ padding=padding,
+ truncation=truncation,
+ max_length=max_length,
+ pad_to_multiple_of=pad_to_multiple_of,
+ verbose=verbose,
+ **kwargs,
+ )
+
+ return self._encode_plus(
+ text=text,
+ text_pair=text_pair,
+ add_special_tokens=add_special_tokens,
+ padding_strategy=padding_strategy,
+ truncation_strategy=truncation_strategy,
+ max_length=max_length,
+ stride=stride,
+ is_split_into_words=is_split_into_words,
+ pad_to_multiple_of=pad_to_multiple_of,
+ padding_side=padding_side,
+ return_tensors=return_tensors,
+ return_token_type_ids=return_token_type_ids,
+ return_attention_mask=return_attention_mask,
+ return_overflowing_tokens=return_overflowing_tokens,
+ return_special_tokens_mask=return_special_tokens_mask,
+ return_offsets_mapping=return_offsets_mapping,
+ return_length=return_length,
+ verbose=verbose,
+ **kwargs,
+ )
+
+ def batch_encode_plus(
+ self,
+ batch_text_or_text_pairs: list[TextInput]
+ | list[TextInputPair]
+ | list[PreTokenizedInput]
+ | list[PreTokenizedInputPair]
+ | list[EncodedInput]
+ | list[EncodedInputPair],
+ add_special_tokens: bool = True,
+ padding: bool | str | PaddingStrategy = False,
+ truncation: bool | str | TruncationStrategy = None,
+ max_length: int | None = None,
+ stride: int = 0,
+ is_split_into_words: bool = False,
+ pad_to_multiple_of: int | None = None,
+ padding_side: str | None = None,
+ return_tensors: str | TensorType | None = None,
+ return_token_type_ids: bool | None = None,
+ return_attention_mask: bool | None = None,
+ return_overflowing_tokens: bool = False,
+ return_special_tokens_mask: bool = False,
+ return_offsets_mapping: bool = False,
+ return_length: bool = False,
+ verbose: bool = True,
+ **kwargs,
+ ) -> BatchEncoding:
+ padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(
+ padding=padding,
+ truncation=truncation,
+ max_length=max_length,
+ pad_to_multiple_of=pad_to_multiple_of,
+ verbose=verbose,
+ **kwargs,
+ )
+
+ return self._batch_encode_plus(
+ batch_text_or_text_pairs=batch_text_or_text_pairs,
+ add_special_tokens=add_special_tokens,
+ padding_strategy=padding_strategy,
+ truncation_strategy=truncation_strategy,
+ max_length=max_length,
+ stride=stride,
+ is_split_into_words=is_split_into_words,
+ pad_to_multiple_of=pad_to_multiple_of,
+ padding_side=padding_side,
+ return_tensors=return_tensors,
+ return_token_type_ids=return_token_type_ids,
+ return_attention_mask=return_attention_mask,
+ return_overflowing_tokens=return_overflowing_tokens,
+ return_special_tokens_mask=return_special_tokens_mask,
+ return_offsets_mapping=return_offsets_mapping,
+ return_length=return_length,
+ verbose=verbose,
+ **kwargs,
+ )
+
+ @property
+ def do_lower_case(self):
+ return self.basic_tokenizer.do_lower_case
+
+ @property
+ def vocab_size(self):
+ return len(self.vocab)
+
+ def get_vocab(self):
+ return dict(self.vocab, **self.added_tokens_encoder)
+
+ def _tokenize(self, text, split_special_tokens=False):
+ split_tokens = []
+ if self.do_basic_tokenize:
+ for token in self.basic_tokenizer.tokenize(
+ text, never_split=self.all_special_tokens if not split_special_tokens else None
+ ):
+ # If the token is part of the never_split set
+ if token in self.basic_tokenizer.never_split:
+ split_tokens.append(token)
+ else:
+ split_tokens += self.wordpiece_tokenizer.tokenize(token)
+ else:
+ split_tokens = self.wordpiece_tokenizer.tokenize(text)
+ return split_tokens
+
+ def _encode_plus(
+ self,
+ text: TextInput | PreTokenizedInput | EncodedInput,
+ text_pair: TextInput | PreTokenizedInput | EncodedInput | None = None,
+ add_special_tokens: bool = True,
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
+ truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
+ max_length: int | None = None,
+ stride: int = 0,
+ is_split_into_words: bool = False,
+ pad_to_multiple_of: int | None = None,
+ padding_side: str | None = None,
+ return_tensors: str | TensorType | None = None,
+ return_token_type_ids: bool | None = None,
+ return_attention_mask: bool | None = None,
+ return_overflowing_tokens: bool = False,
+ return_special_tokens_mask: bool = False,
+ return_offsets_mapping: bool = False,
+ return_length: bool = False,
+ verbose: bool = True,
+ **kwargs,
+ ) -> BatchEncoding:
+ def get_input_ids(text):
+ if isinstance(text, str):
+ tokens = self.tokenize(text, **kwargs)
+ tokens_ids = self.convert_tokens_to_ids(tokens)
+ tokens_shape_ids = self.convert_tokens_to_shape_ids(tokens)
+ tokens_proun_ids = self.convert_tokens_to_pronunciation_ids(tokens)
+ return tokens_ids, tokens_shape_ids, tokens_proun_ids
+ elif isinstance(text, (list, tuple)) and len(text) > 0 and isinstance(text[0], str):
+ if is_split_into_words:
+ tokens = list(
+ itertools.chain(*(self.tokenize(t, is_split_into_words=True, **kwargs) for t in text))
+ )
+ tokens_ids = self.convert_tokens_to_ids(tokens)
+ tokens_shape_ids = self.convert_tokens_to_shape_ids(tokens)
+ tokens_proun_ids = self.convert_tokens_to_pronunciation_ids(tokens)
+ return tokens_ids, tokens_shape_ids, tokens_proun_ids
+ else:
+ tokens_ids = self.convert_tokens_to_ids(text)
+ tokens_shape_ids = self.convert_tokens_to_shape_ids(text)
+ tokens_proun_ids = self.convert_tokens_to_pronunciation_ids(text)
+ return tokens_ids, tokens_shape_ids, tokens_proun_ids
+ elif isinstance(text, (list, tuple)) and len(text) > 0 and isinstance(text[0], int):
+ return text, [0] * len(text), [0] * len(text) # shape and proun id is pad_value
+ else:
+ if is_split_into_words:
+ raise ValueError(
+ f"Input {text} is not valid. Should be a string or a list/tuple of strings when"
+ " `is_split_into_words=True`."
+ )
+ else:
+ raise ValueError(
+ f"Input {text} is not valid. Should be a string, a list/tuple of strings or a list/tuple of"
+ " integers."
+ )
+
+ if return_offsets_mapping:
+ raise NotImplementedError(
+ "return_offset_mapping is not available when using Python tokenizers. "
+ "To use this feature, change your tokenizer to one deriving from "
+ "transformers.PreTrainedTokenizerFast. "
+ "More information on available tokenizers at "
+ "https://github.com/huggingface/transformers/pull/2674"
+ )
+
+ first_ids, first_shape_ids, first_proun_ids = get_input_ids(text)
+ if text_pair is not None:
+ second_ids, second_shape_ids, second_proun_ids = get_input_ids(text_pair)
+ else:
+ second_ids, second_shape_ids, second_proun_ids = None, None, None
+
+ return self.prepare_for_model(
+ first_ids,
+ first_shape_ids,
+ first_proun_ids,
+ pair_ids=second_ids,
+ pair_shape_ids=second_shape_ids,
+ pair_pronunciation_ids=second_proun_ids,
+ add_special_tokens=add_special_tokens,
+ padding=padding_strategy.value,
+ truncation=truncation_strategy.value,
+ max_length=max_length,
+ stride=stride,
+ pad_to_multiple_of=pad_to_multiple_of,
+ padding_side=padding_side,
+ return_tensors=return_tensors,
+ prepend_batch_axis=True,
+ return_attention_mask=return_attention_mask,
+ return_token_type_ids=return_token_type_ids,
+ return_overflowing_tokens=return_overflowing_tokens,
+ return_special_tokens_mask=return_special_tokens_mask,
+ return_length=return_length,
+ verbose=verbose,
+ )
+
+ @add_end_docstrings(ENCODE_KWARGS_DOCSTRING, ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
+ def prepare_for_model(
+ self,
+ ids: list[int],
+ shape_ids: list[int],
+ pronunciation_ids: list[int],
+ pair_ids: list[int] | None = None,
+ pair_shape_ids: list[int] | None = None,
+ pair_pronunciation_ids: list[int] | None = None,
+ add_special_tokens: bool = True,
+ padding: bool | str | PaddingStrategy = False,
+ truncation: bool | str | TruncationStrategy = None,
+ max_length: int | None = None,
+ stride: int = 0,
+ pad_to_multiple_of: int | None = None,
+ padding_side: str | None = None,
+ return_tensors: str | TensorType | None = None,
+ return_token_type_ids: bool | None = None,
+ return_attention_mask: bool | None = None,
+ return_overflowing_tokens: bool = False,
+ return_special_tokens_mask: bool = False,
+ return_offsets_mapping: bool = False,
+ return_length: bool = False,
+ verbose: bool = True,
+ prepend_batch_axis: bool = False,
+ **kwargs,
+ ) -> BatchEncoding:
+ """
+ Prepares a sequence of input id, or a pair of sequences of inputs ids so that it can be used by the model. It
+ adds special tokens, truncates sequences if overflowing while taking into account the special tokens and
+ manages a moving window (with user defined stride) for overflowing tokens. Please Note, for *pair_ids*
+ different than `None` and *truncation_strategy = longest_first* or `True`, it is not possible to return
+ overflowing tokens. Such a combination of arguments will raise an error.
+
+ Args:
+ ids (`List[int]`):
+ Tokenized input ids of the first sequence. Can be obtained from a string by chaining the `tokenize` and
+ `convert_tokens_to_id` methods.
+ shape_ids (`List[int]`):
+ Tokenized input ids of the first sequence. Can be obtained from a string by chaining the `tokenize` and
+ `convert_token_to_shape_id` methods.
+ pronunciation_ids (`List[int]`):
+ Tokenized input ids of the first sequence. Can be obtained from a string by chaining the `tokenize` and
+ `convert_token_to_pronunciation_id` methods.
+ pair_ids (`List[int]`, *optional*):
+ Tokenized input ids of the second sequence. Can be obtained from a string by chaining the `tokenize`
+ and `convert_tokens_to_id` methods.
+ pair_shape_ids (`List[int]`, *optional*):
+ Tokenized input ids of the second sequence. Can be obtained from a string by chaining the `tokenize`
+ and `convert_token_to_shape_id` methods.
+ pair_pronunciation_ids (`List[int]`, *optional*):
+ Tokenized input ids of the second sequence. Can be obtained from a string by chaining the `tokenize`
+ and `convert_token_to_pronunciation_id` methods.
+ """
+
+ # Backward compatibility for 'truncation_strategy', 'pad_to_max_length'
+ padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(
+ padding=padding,
+ truncation=truncation,
+ max_length=max_length,
+ pad_to_multiple_of=pad_to_multiple_of,
+ verbose=verbose,
+ **kwargs,
+ )
+
+ pair = bool(pair_ids is not None)
+ len_ids = len(ids)
+ len_pair_ids = len(pair_ids) if pair else 0
+
+ if return_token_type_ids and not add_special_tokens:
+ raise ValueError(
+ "Asking to return token_type_ids while setting add_special_tokens to False "
+ "results in an undefined behavior. Please set add_special_tokens to True or "
+ "set return_token_type_ids to None."
+ )
+
+ if (
+ return_overflowing_tokens
+ and truncation_strategy == TruncationStrategy.LONGEST_FIRST
+ and pair_ids is not None
+ ):
+ raise ValueError(
+ "Not possible to return overflowing tokens for pair of sequences with the "
+ "`longest_first`. Please select another truncation strategy than `longest_first`, "
+ "for instance `only_second` or `only_first`."
+ )
+
+ # Load from model defaults
+ if return_token_type_ids is None:
+ return_token_type_ids = "token_type_ids" in self.model_input_names
+ if return_attention_mask is None:
+ return_attention_mask = "attention_mask" in self.model_input_names
+
+ encoded_inputs = {}
+
+ # Compute the total size of the returned encodings
+ total_len = len_ids + len_pair_ids + (self.num_special_tokens_to_add(pair=pair) if add_special_tokens else 0)
+
+ # Truncation: Handle max sequence length
+ overflowing_tokens = []
+ if truncation_strategy != TruncationStrategy.DO_NOT_TRUNCATE and max_length and total_len > max_length:
+ ids, pair_ids, overflowing_tokens = self.truncate_sequences(
+ ids,
+ pair_ids=pair_ids,
+ num_tokens_to_remove=total_len - max_length,
+ truncation_strategy=truncation_strategy,
+ stride=stride,
+ )
+ shape_ids, pair_shape_ids, _ = self.truncate_sequences(
+ shape_ids,
+ pair_ids=pair_shape_ids,
+ num_tokens_to_remove=total_len - max_length,
+ truncation_strategy=truncation_strategy,
+ stride=stride,
+ )
+ pronunciation_ids, pair_pronunciation_ids, _ = self.truncate_sequences(
+ pronunciation_ids,
+ pair_ids=pair_pronunciation_ids,
+ num_tokens_to_remove=total_len - max_length,
+ truncation_strategy=truncation_strategy,
+ stride=stride,
+ )
+
+ if return_overflowing_tokens and not return_tensors and overflowing_tokens:
+ encoded_inputs["overflowing_tokens"] = overflowing_tokens
+ encoded_inputs["num_truncated_tokens"] = total_len - max_length if max_length else 0
+
+ # Add special tokens
+ if add_special_tokens:
+ sequence = self.build_inputs_with_special_tokens(ids, pair_ids)
+ token_type_ids = self.create_token_type_ids_from_sequences(ids, pair_ids)
+ input_shape_ids = self.build_inputs_with_special_tokens(
+ shape_ids, pair_shape_ids, self.word_shape["[UNK]"], self.word_shape["[UNK]"]
+ )
+ input_pronunciation_ids = self.build_inputs_with_special_tokens(
+ pronunciation_ids,
+ pair_pronunciation_ids,
+ self.word_pronunciation["[UNK]"],
+ self.word_pronunciation["[UNK]"],
+ )
+ else:
+ sequence = ids + pair_ids if pair_ids else ids
+ token_type_ids = [0] * len(ids) + ([0] * len(pair_ids) if pair_ids else [])
+ input_shape_ids = shape_ids + pair_shape_ids if pair_shape_ids else shape_ids
+ input_pronunciation_ids = (
+ pronunciation_ids + pair_pronunciation_ids if pair_pronunciation_ids else pronunciation_ids
+ )
+
+ # Build output dictionary
+ encoded_inputs["input_ids"] = sequence
+ encoded_inputs["input_shape_ids"] = input_shape_ids
+ encoded_inputs["input_pronunciation_ids"] = input_pronunciation_ids
+ if return_token_type_ids:
+ encoded_inputs["token_type_ids"] = token_type_ids
+ if return_special_tokens_mask:
+ if add_special_tokens:
+ encoded_inputs["special_tokens_mask"] = self.get_special_tokens_mask(ids, pair_ids)
+ else:
+ encoded_inputs["special_tokens_mask"] = [0] * len(sequence)
+
+ # Check lengths
+ self._eventual_warn_about_too_long_sequence(encoded_inputs["input_ids"], max_length, verbose)
+
+ # Padding
+ if padding_strategy != PaddingStrategy.DO_NOT_PAD or return_attention_mask:
+ encoded_inputs = self.pad(
+ encoded_inputs,
+ max_length=max_length,
+ padding=padding_strategy.value,
+ pad_to_multiple_of=pad_to_multiple_of,
+ padding_side=padding_side,
+ return_attention_mask=return_attention_mask,
+ )
+
+ if return_length:
+ encoded_inputs["length"] = len(encoded_inputs["input_ids"])
+
+ batch_outputs = BatchEncoding(
+ encoded_inputs, tensor_type=return_tensors, prepend_batch_axis=prepend_batch_axis
+ )
+
+ return batch_outputs
+
+ def _pad(
+ self,
+ encoded_inputs: dict[str, EncodedInput] | BatchEncoding,
+ max_length: int | None = None,
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
+ pad_to_multiple_of: int | None = None,
+ padding_side: str | None = None,
+ return_attention_mask: bool | None = None,
+ ) -> dict:
+ # Load from model defaults
+ if return_attention_mask is None:
+ return_attention_mask = "attention_mask" in self.model_input_names
+
+ required_input = encoded_inputs[self.model_input_names[0]]
+
+ if padding_strategy == PaddingStrategy.LONGEST:
+ max_length = len(required_input)
+
+ if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
+ max_length = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of
+
+ needs_to_be_padded = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(required_input) != max_length
+
+ # Initialize attention mask if not present.
+ if return_attention_mask and "attention_mask" not in encoded_inputs:
+ encoded_inputs["attention_mask"] = [1] * len(required_input)
+
+ if needs_to_be_padded:
+ difference = max_length - len(required_input)
+ padding_side = padding_side if padding_side is not None else self.padding_side
+
+ if padding_side == "right":
+ if return_attention_mask:
+ encoded_inputs["attention_mask"] = encoded_inputs["attention_mask"] + [0] * difference
+ if "token_type_ids" in encoded_inputs:
+ encoded_inputs["token_type_ids"] = (
+ encoded_inputs["token_type_ids"] + [self.pad_token_type_id] * difference
+ )
+ if "special_tokens_mask" in encoded_inputs:
+ encoded_inputs["special_tokens_mask"] = encoded_inputs["special_tokens_mask"] + [1] * difference
+ for key in ["input_shape_ids", "input_pronunciation_ids"]:
+ if key in encoded_inputs:
+ encoded_inputs[key] = encoded_inputs[key] + [self.pad_token_id] * difference
+ encoded_inputs[self.model_input_names[0]] = required_input + [self.pad_token_id] * difference
+ elif padding_side == "left":
+ if return_attention_mask:
+ encoded_inputs["attention_mask"] = [0] * difference + encoded_inputs["attention_mask"]
+ if "token_type_ids" in encoded_inputs:
+ encoded_inputs["token_type_ids"] = [self.pad_token_type_id] * difference + encoded_inputs[
+ "token_type_ids"
+ ]
+ if "special_tokens_mask" in encoded_inputs:
+ encoded_inputs["special_tokens_mask"] = [1] * difference + encoded_inputs["special_tokens_mask"]
+ for key in ["input_shape_ids", "input_pronunciation_ids"]:
+ if key in encoded_inputs:
+ encoded_inputs[key] = [self.pad_token_id] * difference + encoded_inputs[key]
+ encoded_inputs[self.model_input_names[0]] = [self.pad_token_id] * difference + required_input
+ else:
+ raise ValueError("Invalid padding strategy:" + str(padding_side))
+
+ return encoded_inputs
+
+ def _batch_encode_plus(
+ self,
+ batch_text_or_text_pairs: list[TextInput]
+ | list[TextInputPair]
+ | list[PreTokenizedInput]
+ | list[PreTokenizedInputPair]
+ | list[EncodedInput]
+ | list[EncodedInputPair],
+ add_special_tokens: bool = True,
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
+ truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
+ max_length: int | None = None,
+ stride: int = 0,
+ is_split_into_words: bool = False,
+ pad_to_multiple_of: int | None = None,
+ padding_side: str | None = None,
+ return_tensors: str | TensorType | None = None,
+ return_token_type_ids: bool | None = None,
+ return_attention_mask: bool | None = None,
+ return_overflowing_tokens: bool = False,
+ return_special_tokens_mask: bool = False,
+ return_offsets_mapping: bool = False,
+ return_length: bool = False,
+ verbose: bool = True,
+ **kwargs,
+ ) -> BatchEncoding:
+ def get_input_ids(text):
+ if isinstance(text, str):
+ tokens = self.tokenize(text, **kwargs)
+ tokens_ids = self.convert_tokens_to_ids(tokens)
+ tokens_shape_ids = self.convert_tokens_to_shape_ids(tokens)
+ tokens_proun_ids = self.convert_tokens_to_pronunciation_ids(tokens)
+ return tokens_ids, tokens_shape_ids, tokens_proun_ids
+ elif isinstance(text, (list, tuple)) and len(text) > 0 and isinstance(text[0], str):
+ if is_split_into_words:
+ tokens = list(
+ itertools.chain(*(self.tokenize(t, is_split_into_words=True, **kwargs) for t in text))
+ )
+ tokens_ids = self.convert_tokens_to_ids(tokens)
+ tokens_shape_ids = self.convert_tokens_to_shape_ids(tokens)
+ tokens_proun_ids = self.convert_tokens_to_pronunciation_ids(tokens)
+ return tokens_ids, tokens_shape_ids, tokens_proun_ids
+ else:
+ tokens_ids = self.convert_tokens_to_ids(text)
+ tokens_shape_ids = self.convert_tokens_to_shape_ids(text)
+ tokens_proun_ids = self.convert_tokens_to_pronunciation_ids(text)
+ return tokens_ids, tokens_shape_ids, tokens_proun_ids
+ elif isinstance(text, (list, tuple)) and len(text) > 0 and isinstance(text[0], int):
+ return text, [0] * len(text), [0] * len(text) # shape and proun id is pad_value
+ else:
+ raise ValueError(
+ "Input is not valid. Should be a string, a list/tuple of strings or a list/tuple of integers."
+ )
+
+ if return_offsets_mapping:
+ raise NotImplementedError(
+ "return_offset_mapping is not available when using Python tokenizers. "
+ "To use this feature, change your tokenizer to one deriving from "
+ "transformers.PreTrainedTokenizerFast."
+ )
+
+ input_ids = []
+ input_shape_ids = []
+ input_pronunciation_ids = []
+ for ids_or_pair_ids in batch_text_or_text_pairs:
+ if not isinstance(ids_or_pair_ids, (list, tuple)):
+ ids, pair_ids = ids_or_pair_ids, None
+ elif is_split_into_words and not isinstance(ids_or_pair_ids[0], (list, tuple)):
+ ids, pair_ids = ids_or_pair_ids, None
+ else:
+ ids, pair_ids = ids_or_pair_ids
+
+ first_ids, first_shape_ids, first_proun_ids = get_input_ids(ids)
+ if pair_ids is not None:
+ second_ids, second_shape_ids, second_proun_ids = get_input_ids(pair_ids)
+ else:
+ second_ids, second_shape_ids, second_proun_ids = None, None, None
+
+ input_ids.append((first_ids, second_ids))
+ input_shape_ids.append((first_shape_ids, second_shape_ids))
+ input_pronunciation_ids.append((first_proun_ids, second_proun_ids))
+
+ batch_outputs = self._batch_prepare_for_model(
+ input_ids,
+ batch_shape_ids_pairs=input_shape_ids,
+ batch_pronunciation_ids_pairs=input_pronunciation_ids,
+ add_special_tokens=add_special_tokens,
+ padding_strategy=padding_strategy,
+ truncation_strategy=truncation_strategy,
+ max_length=max_length,
+ stride=stride,
+ pad_to_multiple_of=pad_to_multiple_of,
+ padding_side=padding_side,
+ return_attention_mask=return_attention_mask,
+ return_token_type_ids=return_token_type_ids,
+ return_overflowing_tokens=return_overflowing_tokens,
+ return_special_tokens_mask=return_special_tokens_mask,
+ return_length=return_length,
+ return_tensors=return_tensors,
+ verbose=verbose,
+ )
+
+ return batch_outputs
+
+ @add_end_docstrings(ENCODE_KWARGS_DOCSTRING, ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
+ def _batch_prepare_for_model(
+ self,
+ batch_ids_pairs: list[PreTokenizedInputPair | tuple[list[int], None]],
+ batch_shape_ids_pairs: list[PreTokenizedInputPair | tuple[list[int], None]],
+ batch_pronunciation_ids_pairs: list[PreTokenizedInputPair | tuple[list[int], None]],
+ add_special_tokens: bool = True,
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
+ truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
+ max_length: int | None = None,
+ stride: int = 0,
+ pad_to_multiple_of: int | None = None,
+ padding_side: str | None = None,
+ return_tensors: str | None = None,
+ return_token_type_ids: bool | None = None,
+ return_attention_mask: bool | None = None,
+ return_overflowing_tokens: bool = False,
+ return_special_tokens_mask: bool = False,
+ return_length: bool = False,
+ verbose: bool = True,
+ ) -> BatchEncoding:
+ """
+ Prepares a sequence of input id, or a pair of sequences of inputs ids so that it can be used by the model. It
+ adds special tokens, truncates sequences if overflowing while taking into account the special tokens and
+ manages a moving window (with user defined stride) for overflowing tokens
+
+ Args:
+ batch_ids_pairs: list of tokenized input ids or input ids pairs
+ batch_shape_ids_pairs: list of tokenized input shape ids or input shape ids pairs
+ batch_pronunciation_ids_pairs: list of tokenized input pronunciation ids or input pronunciation ids pairs
+ """
+
+ batch_outputs = {}
+ for i, (first_ids, second_ids) in enumerate(batch_ids_pairs):
+ first_shape_ids, second_shape_ids = batch_shape_ids_pairs[i]
+ first_pronunciation_ids, second_pronunciation_ids = batch_pronunciation_ids_pairs[i]
+ outputs = self.prepare_for_model(
+ first_ids,
+ first_shape_ids,
+ first_pronunciation_ids,
+ pair_ids=second_ids,
+ pair_shape_ids=second_shape_ids,
+ pair_pronunciation_ids=second_pronunciation_ids,
+ add_special_tokens=add_special_tokens,
+ padding=PaddingStrategy.DO_NOT_PAD.value, # we pad in batch afterward
+ truncation=truncation_strategy.value,
+ max_length=max_length,
+ stride=stride,
+ pad_to_multiple_of=None, # we pad in batch afterward
+ padding_side=None, # we pad in batch afterward
+ return_attention_mask=False, # we pad in batch afterward
+ return_token_type_ids=return_token_type_ids,
+ return_overflowing_tokens=return_overflowing_tokens,
+ return_special_tokens_mask=return_special_tokens_mask,
+ return_length=return_length,
+ return_tensors=None, # We convert the whole batch to tensors at the end
+ prepend_batch_axis=False,
+ verbose=verbose,
+ )
+
+ for key, value in outputs.items():
+ if key not in batch_outputs:
+ batch_outputs[key] = []
+ batch_outputs[key].append(value)
+
+ batch_outputs = self.pad(
+ batch_outputs,
+ padding=padding_strategy.value,
+ max_length=max_length,
+ pad_to_multiple_of=pad_to_multiple_of,
+ padding_side=padding_side,
+ return_attention_mask=return_attention_mask,
+ )
+
+ # Remove overflow-related keys before tensor conversion if return_tensors is set
+ # Slow tokenizers don't support returning these as tensors
+ if return_tensors and return_overflowing_tokens:
+ batch_outputs.pop("overflowing_tokens", None)
+ batch_outputs.pop("num_truncated_tokens", None)
+
+ batch_outputs = BatchEncoding(batch_outputs, tensor_type=return_tensors)
+
+ return batch_outputs
+
+ def _convert_token_to_id(self, token):
+ """Converts a token (str) in an id using the vocab."""
+ return self.vocab.get(token, self.vocab.get(self.unk_token))
+
+ def _convert_token_to_shape_id(self, token):
+ """Converts a token (str) in an shape_id using the shape vocab."""
+ return self.word_shape.get(token, self.word_shape.get(self.unk_token))
+
+ def convert_tokens_to_shape_ids(self, tokens: str | list[str]) -> int | list[int]:
+ if tokens is None:
+ return None
+
+ ids = []
+ for token in tokens:
+ ids.append(self._convert_token_to_shape_id(token))
+ return ids
+
+ def _convert_token_to_pronunciation_id(self, token):
+ """Converts a token (str) in an shape_id using the shape vocab."""
+ return self.word_pronunciation.get(token, self.word_pronunciation.get(self.unk_token))
+
+ def convert_tokens_to_pronunciation_ids(self, tokens: str | list[str]) -> int | list[int]:
+ if tokens is None:
+ return None
+
+ ids = []
+ for token in tokens:
+ ids.append(self._convert_token_to_pronunciation_id(token))
+ return ids
+
+ def _convert_id_to_token(self, index):
+ """Converts an index (integer) in a token (str) using the vocab."""
+ return self.ids_to_tokens.get(index, self.unk_token)
+
+ def convert_tokens_to_string(self, tokens):
+ """Converts a sequence of tokens (string) in a single string."""
+ out_string = " ".join(tokens).replace(" ##", "").strip()
+ return out_string
+
+ def build_inputs_with_special_tokens(
+ self,
+ token_ids_0: list[int],
+ token_ids_1: list[int] | None = None,
+ cls_token_id: int | None = None,
+ sep_token_id: int | None = None,
+ ) -> list[int]:
+ """
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
+ adding special tokens. A BERT sequence has the following format:
+
+ - single sequence: `[CLS] X [SEP]`
+ - pair of sequences: `[CLS] A [SEP] B [SEP]`
+
+ Args:
+ token_ids_0 (`List[int]`):
+ List of IDs to which the special tokens will be added.
+ token_ids_1 (`List[int]`, *optional*):
+ Optional second list of IDs for sequence pairs.
+
+ Returns:
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
+ """
+ cls = [self.cls_token_id] if cls_token_id is None else [cls_token_id]
+ sep = [self.sep_token_id] if sep_token_id is None else [sep_token_id]
+ if token_ids_1 is None:
+ return cls + token_ids_0 + sep
+ return cls + token_ids_0 + sep + token_ids_1 + sep
+
+ def get_special_tokens_mask(
+ self, token_ids_0: list[int], token_ids_1: list[int] | None = None, already_has_special_tokens: bool = False
+ ) -> list[int]:
+ """
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
+ special tokens using the tokenizer `prepare_for_model` method.
+
+ Args:
+ token_ids_0 (`List[int]`):
+ List of IDs.
+ token_ids_1 (`List[int]`, *optional*):
+ Optional second list of IDs for sequence pairs.
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
+ Whether or not the token list is already formatted with special tokens for the model.
+
+ Returns:
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
+ """
+
+ if already_has_special_tokens:
+ return super().get_special_tokens_mask(
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
+ )
+
+ if token_ids_1 is not None:
+ return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
+ return [1] + ([0] * len(token_ids_0)) + [1]
+
+ def save_vocabulary(self, save_directory: str, filename_prefix: str | None = None) -> tuple[str, str, str]:
+ index = 0
+ if os.path.isdir(save_directory):
+ vocab_file = os.path.join(
+ save_directory,
+ (filename_prefix + "-" if filename_prefix else "") + self.vocab_files_names["vocab_file"],
+ )
+ word_shape_file = os.path.join(
+ save_directory,
+ (filename_prefix + "-" if filename_prefix else "") + self.vocab_files_names["word_shape_file"],
+ )
+ word_pronunciation_file = os.path.join(
+ save_directory,
+ (filename_prefix + "-" if filename_prefix else "") + self.vocab_files_names["word_pronunciation_file"],
+ )
+ else:
+ raise ValueError(
+ f"Can't find a directory at path '{save_directory}'. To load the vocabulary from a Google "
+ "pretrained model use `tokenizer = RoCBertTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`"
+ )
+
+ with open(vocab_file, "w", encoding="utf-8") as writer:
+ for token, token_index in sorted(self.vocab.items(), key=lambda kv: kv[1]):
+ if index != token_index:
+ logger.warning(
+ f"Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive."
+ " Please check that the vocabulary is not corrupted!"
+ )
+ index = token_index
+ writer.write(token + "\n")
+ index += 1
+
+ with open(word_shape_file, "w", encoding="utf8") as writer:
+ json.dump(self.word_shape, writer, ensure_ascii=False, indent=4, separators=(", ", ": "))
+
+ with open(word_pronunciation_file, "w", encoding="utf8") as writer:
+ json.dump(self.word_pronunciation, writer, ensure_ascii=False, indent=4, separators=(", ", ": "))
+
+ return (
+ vocab_file,
+ word_shape_file,
+ word_pronunciation_file,
+ )
+
+
+class RoCBertBasicTokenizer:
+ """
+ Constructs a RoCBertBasicTokenizer that will run basic tokenization (punctuation splitting, lower casing, etc.).
+
+ Args:
+ do_lower_case (`bool`, *optional*, defaults to `True`):
+ Whether or not to lowercase the input when tokenizing.
+ never_split (`Iterable`, *optional*):
+ Collection of tokens which will never be split during tokenization. Only has an effect when
+ `do_basic_tokenize=True`
+ tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
+ Whether or not to tokenize Chinese characters.
+
+ This should likely be deactivated for Japanese (see this
+ [issue](https://github.com/huggingface/transformers/issues/328)).
+ strip_accents (`bool`, *optional*):
+ Whether or not to strip all accents. If this option is not specified, then it will be determined by the
+ value for `lowercase` (as in the original BERT).
+ do_split_on_punc (`bool`, *optional*, defaults to `True`):
+ In some instances we want to skip the basic punctuation splitting so that later tokenization can capture
+ the full context of the words, such as contractions.
+ """
+
+ def __init__(
+ self,
+ do_lower_case=True,
+ never_split=None,
+ tokenize_chinese_chars=True,
+ strip_accents=None,
+ do_split_on_punc=True,
+ ):
+ if never_split is None:
+ never_split = []
+ self.do_lower_case = do_lower_case
+ self.never_split = set(never_split)
+ self.tokenize_chinese_chars = tokenize_chinese_chars
+ self.strip_accents = strip_accents
+ self.do_split_on_punc = do_split_on_punc
+
+ def tokenize(self, text, never_split=None):
+ """
+ Basic Tokenization of a piece of text. For sub-word tokenization, see WordPieceTokenizer.
+
+ Args:
+ never_split (`List[str]`, *optional*)
+ Kept for backward compatibility purposes. Now implemented directly at the base class level (see
+ [`PreTrainedTokenizer.tokenize`]) List of token not to split.
+ """
+ # union() returns a new set by concatenating the two sets.
+ never_split = self.never_split.union(set(never_split)) if never_split else self.never_split
+ text = self._clean_text(text)
+
+ # This was added on November 1st, 2018 for the multilingual and Chinese
+ # models. This is also applied to the English models now, but it doesn't
+ # matter since the English models were not trained on any Chinese data
+ # and generally don't have any Chinese data in them (there are Chinese
+ # characters in the vocabulary because Wikipedia does have some Chinese
+ # words in the English Wikipedia.).
+ if self.tokenize_chinese_chars:
+ text = self._tokenize_chinese_chars(text)
+ # prevents treating the same character with different unicode codepoints as different characters
+ unicode_normalized_text = unicodedata.normalize("NFC", text)
+ orig_tokens = whitespace_tokenize(unicode_normalized_text)
+ split_tokens = []
+ for token in orig_tokens:
+ if token not in never_split:
+ if self.do_lower_case:
+ token = token.lower()
+ if self.strip_accents is not False:
+ token = self._run_strip_accents(token)
+ elif self.strip_accents:
+ token = self._run_strip_accents(token)
+ split_tokens.extend(self._run_split_on_punc(token, never_split))
+
+ output_tokens = whitespace_tokenize(" ".join(split_tokens))
+ return output_tokens
+
+ def _run_strip_accents(self, text):
+ """Strips accents from a piece of text."""
+ text = unicodedata.normalize("NFD", text)
+ output = []
+ for char in text:
+ cat = unicodedata.category(char)
+ if cat == "Mn":
+ continue
+ output.append(char)
+ return "".join(output)
+
+ def _run_split_on_punc(self, text, never_split=None):
+ """Splits punctuation on a piece of text."""
+ if not self.do_split_on_punc or (never_split is not None and text in never_split):
+ return [text]
+ chars = list(text)
+ i = 0
+ start_new_word = True
+ output = []
+ while i < len(chars):
+ char = chars[i]
+ if _is_punctuation(char):
+ output.append([char])
+ start_new_word = True
+ else:
+ if start_new_word:
+ output.append([])
+ start_new_word = False
+ output[-1].append(char)
+ i += 1
+
+ return ["".join(x) for x in output]
+
+ def _tokenize_chinese_chars(self, text):
+ """Adds whitespace around any CJK character."""
+ output = []
+ for char in text:
+ cp = ord(char)
+ if self._is_chinese_char(cp):
+ output.append(" ")
+ output.append(char)
+ output.append(" ")
+ else:
+ output.append(char)
+ return "".join(output)
+
+ def _is_chinese_char(self, cp):
+ """Checks whether CP is the codepoint of a CJK character."""
+ # This defines a "chinese character" as anything in the CJK Unicode block:
+ # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
+ #
+ # Note that the CJK Unicode block is NOT all Japanese and Korean characters,
+ # despite its name. The modern Korean Hangul alphabet is a different block,
+ # as is Japanese Hiragana and Katakana. Those alphabets are used to write
+ # space-separated words, so they are not treated specially and handled
+ # like the all of the other languages.
+ if (
+ (cp >= 0x4E00 and cp <= 0x9FFF)
+ or (cp >= 0x3400 and cp <= 0x4DBF)
+ or (cp >= 0x20000 and cp <= 0x2A6DF)
+ or (cp >= 0x2A700 and cp <= 0x2B73F)
+ or (cp >= 0x2B740 and cp <= 0x2B81F)
+ or (cp >= 0x2B820 and cp <= 0x2CEAF)
+ or (cp >= 0xF900 and cp <= 0xFAFF)
+ or (cp >= 0x2F800 and cp <= 0x2FA1F)
+ ):
+ return True
+
+ return False
+
+ def _clean_text(self, text):
+ """Performs invalid character removal and whitespace cleanup on text."""
+ output = []
+ for char in text:
+ cp = ord(char)
+ if cp == 0 or cp == 0xFFFD or _is_control(char):
+ continue
+ if _is_whitespace(char):
+ output.append(" ")
+ else:
+ output.append(char)
+ return "".join(output)
+
+
+class RoCBertWordpieceTokenizer:
+ """Runs WordPiece tokenization."""
+
+ def __init__(self, vocab, unk_token, max_input_chars_per_word=100):
+ self.vocab = vocab
+ self.unk_token = unk_token
+ self.max_input_chars_per_word = max_input_chars_per_word
+
+ def tokenize(self, text):
+ """
+ Tokenizes a piece of text into its word pieces. This uses a greedy longest-match-first algorithm to perform
+ tokenization using the given vocabulary.
+
+ For example, `input = "unaffable"` will return as output `["un", "##aff", "##able"]`.
+
+ Args:
+ text: A single token or whitespace separated tokens. This should have
+ already been passed through *BasicTokenizer*.
+
+ Returns:
+ A list of wordpiece tokens.
+ """
+
+ output_tokens = []
+ for token in whitespace_tokenize(text):
+ chars = list(token)
+ if len(chars) > self.max_input_chars_per_word:
+ output_tokens.append(self.unk_token)
+ continue
+
+ is_bad = False
+ start = 0
+ sub_tokens = []
+ while start < len(chars):
+ end = len(chars)
+ cur_substr = None
+ while start < end:
+ substr = "".join(chars[start:end])
+ if start > 0:
+ substr = "##" + substr
+ if substr in self.vocab:
+ cur_substr = substr
+ break
+ end -= 1
+ if cur_substr is None:
+ is_bad = True
+ break
+ sub_tokens.append(cur_substr)
+ start = end
+
+ if is_bad:
+ output_tokens.append(self.unk_token)
+ else:
+ output_tokens.extend(sub_tokens)
+ return output_tokens
+
+
+__all__ = ["RoCBertTokenizer"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/rt_detr/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/rt_detr/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..49c22dc17c4572c25ca00addaa6158941c97a621
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/rt_detr/__init__.py
@@ -0,0 +1,33 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_rt_detr import *
+ from .configuration_rt_detr_resnet import *
+ from .image_processing_pil_rt_detr import *
+ from .image_processing_rt_detr import *
+ from .modeling_rt_detr import *
+ from .modeling_rt_detr_resnet import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/rt_detr/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/rt_detr/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..492646a0ac3fb2274a2dd485bf49280b27431f2f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/rt_detr/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/rt_detr/__pycache__/configuration_rt_detr.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/rt_detr/__pycache__/configuration_rt_detr.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1eb1e98d19c54372205e4ce69a6322f4645c92ad
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/rt_detr/__pycache__/configuration_rt_detr.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/rt_detr/__pycache__/configuration_rt_detr_resnet.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/rt_detr/__pycache__/configuration_rt_detr_resnet.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1d97bb82676a551234f1f90794ab9d71c1899b6f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/rt_detr/__pycache__/configuration_rt_detr_resnet.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/rt_detr/__pycache__/image_processing_pil_rt_detr.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/rt_detr/__pycache__/image_processing_pil_rt_detr.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..04f8dfa879d9da0172ad6d062f1414a42942bd5e
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/rt_detr/__pycache__/image_processing_pil_rt_detr.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/rt_detr/__pycache__/image_processing_rt_detr.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/rt_detr/__pycache__/image_processing_rt_detr.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e835f759b23ca2874129201407776480854c00dc
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/rt_detr/__pycache__/image_processing_rt_detr.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/rt_detr/__pycache__/modeling_rt_detr_resnet.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/rt_detr/__pycache__/modeling_rt_detr_resnet.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..73de40136143696f14d7bdbfbe49c789c38031f3
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/rt_detr/__pycache__/modeling_rt_detr_resnet.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/rt_detr/configuration_rt_detr.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/rt_detr/configuration_rt_detr.py
new file mode 100644
index 0000000000000000000000000000000000000000..6ed021380cdd9f80de9261b443e5b3154502b05f
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/rt_detr/configuration_rt_detr.py
@@ -0,0 +1,187 @@
+# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""RT-DETR model configuration"""
+
+from huggingface_hub.dataclasses import strict
+
+from ...backbone_utils import consolidate_backbone_kwargs_to_config
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring
+from ..auto import AutoConfig
+
+
+@auto_docstring(checkpoint="PekingU/rtdetr_r50vd")
+@strict
+class RTDetrConfig(PreTrainedConfig):
+ r"""
+ initializer_bias_prior_prob (`float`, *optional*):
+ The prior probability used by the bias initializer to initialize biases for `enc_score_head` and `class_embed`.
+ If `None`, `prior_prob` computed as `prior_prob = 1 / (num_labels + 1)` while initializing model weights.
+ freeze_backbone_batch_norms (`bool`, *optional*, defaults to `True`):
+ Whether to freeze the batch normalization layers in the backbone.
+ encoder_in_channels (`list`, *optional*, defaults to `[512, 1024, 2048]`):
+ Multi level features input for encoder.
+ feat_strides (`list[int]`, *optional*, defaults to `[8, 16, 32]`):
+ Strides used in each feature map.
+ encode_proj_layers (`list[int]`, *optional*, defaults to `[2]`):
+ Indexes of the projected layers to be used in the encoder.
+ positional_encoding_temperature (`int`, *optional*, defaults to 10000):
+ The temperature parameter used to create the positional encodings.
+ encoder_activation_function (`str`, *optional*, defaults to `"gelu"`):
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
+ eval_size (`tuple[int, int]`, *optional*):
+ Height and width used to computes the effective height and width of the position embeddings after taking
+ into account the stride.
+ normalize_before (`bool`, *optional*, defaults to `False`):
+ Determine whether to apply layer normalization in the transformer encoder layer before self-attention and
+ feed-forward modules.
+ hidden_expansion (`float`, *optional*, defaults to 1.0):
+ Expansion ratio to enlarge the dimension size of RepVGGBlock and CSPRepLayer.
+ num_queries (`int`, *optional*, defaults to 300):
+ Number of object queries.
+ decoder_in_channels (`list`, *optional*, defaults to `[256, 256, 256]`):
+ Multi level features dimension for decoder
+ num_feature_levels (`int`, *optional*, defaults to 3):
+ The number of input feature levels.
+ decoder_n_points (`int`, *optional*, defaults to 4):
+ The number of sampled keys in each feature level for each attention head in the decoder.
+ decoder_activation_function (`str`, *optional*, defaults to `"relu"`):
+ The non-linear activation function (function or string) in the decoder. If string, `"gelu"`,
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
+ num_denoising (`int`, *optional*, defaults to 100):
+ The total number of denoising tasks or queries to be used for contrastive denoising.
+ label_noise_ratio (`float`, *optional*, defaults to 0.5):
+ The fraction of denoising labels to which random noise should be added.
+ box_noise_scale (`float`, *optional*, defaults to 1.0):
+ Scale or magnitude of noise to be added to the bounding boxes.
+ learn_initial_query (`bool`, *optional*, defaults to `False`):
+ Indicates whether the initial query embeddings for the decoder should be learned during training
+ anchor_image_size (`tuple[int, int]`, *optional*):
+ Height and width of the input image used during evaluation to generate the bounding box anchors. If None, automatic generate anchor is applied.
+ disable_custom_kernels (`bool`, *optional*, defaults to `True`):
+ Whether to disable custom kernels.
+ with_box_refine (`bool`, *optional*, defaults to `True`):
+ Whether to apply iterative bounding box refinement, where each decoder layer refines the bounding boxes
+ based on the predictions from the previous layer.
+ matcher_alpha (`float`, *optional*, defaults to 0.25):
+ Parameter alpha used by the Hungarian Matcher.
+ matcher_gamma (`float`, *optional*, defaults to 2.0):
+ Parameter gamma used by the Hungarian Matcher.
+ matcher_class_cost (`float`, *optional*, defaults to 2.0):
+ The relative weight of the class loss used by the Hungarian Matcher.
+ matcher_bbox_cost (`float`, *optional*, defaults to 5.0):
+ The relative weight of the bounding box loss used by the Hungarian Matcher.
+ matcher_giou_cost (`float`, *optional*, defaults to 2.0):
+ The relative weight of the giou loss of used by the Hungarian Matcher.
+ use_focal_loss (`bool`, *optional*, defaults to `True`):
+ Parameter informing if focal focal should be used.
+ focal_loss_alpha (`float`, *optional*, defaults to 0.75):
+ Parameter alpha used to compute the focal loss.
+ focal_loss_gamma (`float`, *optional*, defaults to 2.0):
+ Parameter gamma used to compute the focal loss.
+ weight_loss_vfl (`float`, *optional*, defaults to 1.0):
+ Relative weight of the varifocal loss in the object detection loss.
+ weight_loss_bbox (`float`, *optional*, defaults to 5.0):
+ Relative weight of the L1 bounding box loss in the object detection loss.
+ weight_loss_giou (`float`, *optional*, defaults to 2.0):
+ Relative weight of the generalized IoU loss in the object detection loss.
+
+ Examples:
+
+ ```python
+ >>> from transformers import RTDetrConfig, RTDetrModel
+
+ >>> # Initializing a RT-DETR configuration
+ >>> configuration = RTDetrConfig()
+
+ >>> # Initializing a model (with random weights) from the configuration
+ >>> model = RTDetrModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "rt_detr"
+ sub_configs = {"backbone_config": AutoConfig}
+ layer_types = ["basic", "bottleneck"]
+ attribute_map = {
+ "hidden_size": "d_model",
+ "num_attention_heads": "encoder_attention_heads",
+ }
+
+ initializer_range: float = 0.01
+ initializer_bias_prior_prob: float | None = None
+ layer_norm_eps: float = 1e-5
+ batch_norm_eps: float = 1e-5
+ backbone_config: dict | PreTrainedConfig | None = None
+ freeze_backbone_batch_norms: bool = True
+ encoder_hidden_dim: int = 256
+ encoder_in_channels: list[int] | tuple[int, ...] = (512, 1024, 2048)
+ feat_strides: list[int] | tuple[int, ...] = (8, 16, 32)
+ encoder_layers: int = 1
+ encoder_ffn_dim: int = 1024
+ encoder_attention_heads: int = 8
+ dropout: float | int = 0.0
+ activation_dropout: float | int = 0.0
+ encode_proj_layers: list[int] | tuple[int, ...] = (2,)
+ positional_encoding_temperature: int = 10000
+ encoder_activation_function: str = "gelu"
+ activation_function: str = "silu"
+ eval_size: int | None = None
+ normalize_before: bool = False
+ hidden_expansion: float = 1.0
+ d_model: int = 256
+ num_queries: int = 300
+ decoder_in_channels: list[int] | tuple[int, ...] = (256, 256, 256)
+ decoder_ffn_dim: int = 1024
+ num_feature_levels: int = 3
+ decoder_n_points: int = 4
+ decoder_layers: int = 6
+ decoder_attention_heads: int = 8
+ decoder_activation_function: str = "relu"
+ attention_dropout: float | int = 0.0
+ num_denoising: int = 100
+ label_noise_ratio: float = 0.5
+ box_noise_scale: float = 1.0
+ learn_initial_query: bool = False
+ anchor_image_size: int | list[int] | None = None
+ disable_custom_kernels: bool = True
+ with_box_refine: bool = True
+ is_encoder_decoder: bool = True
+ matcher_alpha: float = 0.25
+ matcher_gamma: float = 2.0
+ matcher_class_cost: float = 2.0
+ matcher_bbox_cost: float = 5.0
+ matcher_giou_cost: float = 2.0
+ use_focal_loss: bool = True
+ auxiliary_loss: bool = True
+ focal_loss_alpha: float = 0.75
+ focal_loss_gamma: float = 2.0
+ weight_loss_vfl: float = 1.0
+ weight_loss_bbox: float = 5.0
+ weight_loss_giou: float = 2.0
+ eos_coefficient: float = 1e-4
+
+ def __post_init__(self, **kwargs):
+ self.backbone_config, kwargs = consolidate_backbone_kwargs_to_config(
+ backbone_config=self.backbone_config,
+ default_config_type="rt_detr_resnet",
+ default_config_kwargs={"out_indices": [2, 3, 4]},
+ **kwargs,
+ )
+ super().__post_init__(**kwargs)
+
+
+__all__ = ["RTDetrConfig"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/rt_detr/configuration_rt_detr_resnet.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/rt_detr/configuration_rt_detr_resnet.py
new file mode 100644
index 0000000000000000000000000000000000000000..6bf2fd9b21da83a6db2e9c0185098953c794b7de
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/rt_detr/configuration_rt_detr_resnet.py
@@ -0,0 +1,83 @@
+# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""RT-DETR ResNet model configuration"""
+
+from huggingface_hub.dataclasses import strict
+
+from ...backbone_utils import BackboneConfigMixin
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring
+
+
+@auto_docstring(checkpoint="microsoft/resnet-50")
+@strict
+class RTDetrResNetConfig(BackboneConfigMixin, PreTrainedConfig):
+ r"""
+ depths (`list[int]`, *optional*, defaults to `[3, 4, 6, 3]`):
+ Depth (number of layers) for each stage.
+ layer_type (`str`, *optional*, defaults to `"bottleneck"`):
+ The layer to use, it can be either `"basic"` (used for smaller models, like resnet-18 or resnet-34) or
+ `"bottleneck"` (used for larger models like resnet-50 and above).
+ hidden_act (`str`, *optional*, defaults to `"relu"`):
+ The non-linear activation function in each block. If string, `"gelu"`, `"relu"`, `"selu"` and `"gelu_new"`
+ are supported.
+ downsample_in_first_stage (`bool`, *optional*, defaults to `False`):
+ If `True`, the first stage will downsample the inputs using a `stride` of 2.
+ downsample_in_bottleneck (`bool`, *optional*, defaults to `False`):
+ If `True`, the first conv 1x1 in ResNetBottleNeckLayer will downsample the inputs using a `stride` of 2.
+
+ Example:
+ ```python
+ >>> from transformers import RTDetrResNetConfig, RTDetrResnetBackbone
+
+ >>> # Initializing a ResNet resnet-50 style configuration
+ >>> configuration = RTDetrResNetConfig()
+
+ >>> # Initializing a model (with random weights) from the resnet-50 style configuration
+ >>> model = RTDetrResnetBackbone(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```
+ """
+
+ model_type = "rt_detr_resnet"
+ layer_types = ["basic", "bottleneck"]
+
+ num_channels: int = 3
+ embedding_size: int = 64
+ hidden_sizes: list[int] | tuple[int, ...] = (256, 512, 1024, 2048)
+ depths: list[int] | tuple[int, ...] = (3, 4, 6, 3)
+ layer_type: str = "bottleneck"
+ hidden_act: str = "relu"
+ downsample_in_first_stage: bool = False
+ downsample_in_bottleneck: bool = False
+ _out_features: list[str] | None = None
+ _out_indices: list[int] | None = None
+
+ def __post_init__(self, **kwargs):
+ self.stage_names = ["stem"] + [f"stage{idx}" for idx in range(1, len(self.depths) + 1)]
+ self.set_output_features_output_indices(
+ out_indices=kwargs.pop("out_indices", None), out_features=kwargs.pop("out_features", None)
+ )
+ self.hidden_sizes = list(self.hidden_sizes)
+ super().__post_init__(**kwargs)
+
+ def validate_architecture(self):
+ """Part of `@strict`-powered validation. Validates the architecture of the config."""
+ if self.layer_type not in self.layer_types:
+ raise ValueError(f"layer_type={self.layer_type} is not one of {','.join(self.layer_types)}")
+
+
+__all__ = ["RTDetrResNetConfig"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/rt_detr/image_processing_pil_rt_detr.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/rt_detr/image_processing_pil_rt_detr.py
new file mode 100644
index 0000000000000000000000000000000000000000..669843e9f949b34e7030d4c86150e63ff20c06cb
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/rt_detr/image_processing_pil_rt_detr.py
@@ -0,0 +1,581 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/rt_detr/modular_rt_detr.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_rt_detr.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2024 Baidu Inc and The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import pathlib
+from typing import Any, Optional
+
+import numpy as np
+
+from ...image_processing_backends import PilBackend
+from ...image_processing_utils import BatchFeature, SizeDict
+from ...image_transforms import (
+ PaddingMode,
+ center_to_corners_format,
+ corners_to_center_format,
+ get_size_with_aspect_ratio,
+ pad,
+ resize,
+ safe_squeeze,
+)
+from ...image_utils import (
+ IMAGENET_DEFAULT_MEAN,
+ IMAGENET_DEFAULT_STD,
+ AnnotationFormat,
+ AnnotationType,
+ ChannelDimension,
+ ImageInput,
+ PILImageResampling,
+ get_image_size,
+ get_image_size_for_max_height_width,
+ get_max_height_width,
+ validate_annotations,
+)
+from ...processing_utils import ImagesKwargs, Unpack
+from ...utils import TensorType, auto_docstring, is_torch_available, requires_backends
+from ...utils.import_utils import requires
+
+
+if is_torch_available():
+ import torch
+
+SUPPORTED_ANNOTATION_FORMATS = (AnnotationFormat.COCO_DETECTION, AnnotationFormat.COCO_PANOPTIC)
+
+
+class RTDetrImageProcessorKwargs(ImagesKwargs, total=False):
+ r"""
+ format (`str`, *optional*, defaults to `AnnotationFormat.COCO_DETECTION`):
+ Data format of the annotations. One of "coco_detection" or "coco_panoptic".
+ do_convert_annotations (`bool`, *optional*, defaults to `True`):
+ Controls whether to convert the annotations to the format expected by the RT_DETR model. Converts the
+ bounding boxes to the format `(center_x, center_y, width, height)` and in the range `[0, 1]`.
+ Can be overridden by the `do_convert_annotations` parameter in the `preprocess` method.
+ """
+
+ format: str | AnnotationFormat
+ do_convert_annotations: bool
+
+
+def prepare_coco_detection_annotation_pil(
+ image,
+ target,
+ return_segmentation_masks: bool = False,
+ input_data_format: ChannelDimension | str | None = None,
+):
+ """
+ Convert the target in COCO format into the format expected by RTDETR.
+ """
+ image_height, image_width = get_image_size(image, channel_dim=input_data_format)
+
+ image_id = target["image_id"]
+ image_id = np.asarray([image_id], dtype=np.int64)
+
+ # Get all COCO annotations for the given image.
+ annotations = target["annotations"]
+ annotations = [obj for obj in annotations if "iscrowd" not in obj or obj["iscrowd"] == 0]
+
+ classes = [obj["category_id"] for obj in annotations]
+ classes = np.asarray(classes, dtype=np.int64)
+
+ # for conversion to coco api
+ area = np.asarray([obj["area"] for obj in annotations], dtype=np.float32)
+ iscrowd = np.asarray([obj.get("iscrowd", 0) for obj in annotations], dtype=np.int64)
+
+ boxes = [obj["bbox"] for obj in annotations]
+ # guard against no boxes via resizing
+ boxes = np.asarray(boxes, dtype=np.float32).reshape(-1, 4)
+ boxes[:, 2:] += boxes[:, :2]
+ boxes[:, 0::2] = boxes[:, 0::2].clip(min=0, max=image_width)
+ boxes[:, 1::2] = boxes[:, 1::2].clip(min=0, max=image_height)
+
+ keep = (boxes[:, 3] > boxes[:, 1]) & (boxes[:, 2] > boxes[:, 0])
+
+ new_target = {}
+ new_target["image_id"] = image_id
+ new_target["class_labels"] = classes[keep]
+ new_target["boxes"] = boxes[keep]
+ new_target["area"] = area[keep]
+ new_target["iscrowd"] = iscrowd[keep]
+ new_target["orig_size"] = np.asarray([int(image_height), int(image_width)], dtype=np.int64)
+
+ if annotations and "keypoints" in annotations[0]:
+ keypoints = [obj["keypoints"] for obj in annotations]
+ # Converting the filtered keypoints list to a numpy array
+ keypoints = np.asarray(keypoints, dtype=np.float32)
+ # Apply the keep mask here to filter the relevant annotations
+ keypoints = keypoints[keep]
+ num_keypoints = keypoints.shape[0]
+ keypoints = keypoints.reshape((-1, 3)) if num_keypoints else keypoints
+ new_target["keypoints"] = keypoints
+
+ return new_target
+
+
+@requires(backends=("torch",))
+class RTDetrImageProcessorPil(PilBackend):
+ resample = PILImageResampling.BILINEAR
+ image_mean = IMAGENET_DEFAULT_MEAN
+ image_std = IMAGENET_DEFAULT_STD
+ format = AnnotationFormat.COCO_DETECTION
+ do_resize = True
+ do_rescale = True
+ do_normalize = False
+ do_pad = False
+ size = {"height": 640, "width": 640}
+ default_to_square = False
+ model_input_names = ["pixel_values", "pixel_mask"]
+ valid_kwargs = RTDetrImageProcessorKwargs
+ do_convert_annotations = True
+
+ def __init__(self, **kwargs: Unpack[RTDetrImageProcessorKwargs]) -> None:
+ # Backwards compatibility
+ do_convert_annotations = kwargs.get("do_convert_annotations")
+ do_normalize = kwargs.get("do_normalize")
+ if do_convert_annotations is None and getattr(self, "do_convert_annotations", None) is None:
+ self.do_convert_annotations = do_normalize if do_normalize is not None else self.do_normalize
+
+ super().__init__(**kwargs)
+
+ def prepare_annotation(
+ self,
+ image: np.ndarray,
+ target: dict,
+ format: AnnotationFormat | None = None,
+ return_segmentation_masks: bool | None = None,
+ masks_path: str | pathlib.Path | None = None,
+ input_data_format: str | ChannelDimension | None = None,
+ ) -> dict:
+ """
+ Prepare an annotation for feeding into RT_DETR model.
+ """
+ format = format if format is not None else self.format
+
+ if format == AnnotationFormat.COCO_DETECTION:
+ return_segmentation_masks = False if return_segmentation_masks is None else return_segmentation_masks
+ target = prepare_coco_detection_annotation_pil(
+ image, target, return_segmentation_masks, input_data_format=input_data_format
+ )
+ else:
+ raise ValueError(f"Format {format} is not supported.")
+ return target
+
+ def resize(
+ self,
+ image: np.ndarray,
+ size: SizeDict,
+ resample: Optional["PILImageResampling"] = None,
+ **kwargs,
+ ) -> np.ndarray:
+ """
+ Resize the image to the given size. Size can be `min_size` (scalar) or `(height, width)` tuple. If size is an
+ int, smaller edge of the image will be matched to this number.
+
+ Args:
+ image (`np.ndarray`):
+ Image to resize.
+ size (`SizeDict`):
+ Size of the image's `(height, width)` dimensions after resizing. Available options are:
+ - `{"height": int, "width": int}`: The image will be resized to the exact size `(height, width)`.
+ Do NOT keep the aspect ratio.
+ - `{"shortest_edge": int, "longest_edge": int}`: The image will be resized to a maximum size respecting
+ the aspect ratio and keeping the shortest edge less or equal to `shortest_edge` and the longest edge
+ less or equal to `longest_edge`.
+ - `{"max_height": int, "max_width": int}`: The image will be resized to the maximum size respecting the
+ aspect ratio and keeping the height less or equal to `max_height` and the width less or equal to
+ `max_width`.
+ resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`):
+ Resampling filter to use if resizing the image.
+ """
+ resample = resample if resample is not None else self.resample
+
+ if size.shortest_edge and size.longest_edge:
+ # Resize the image so that the shortest edge or the longest edge is of the given size
+ # while maintaining the aspect ratio of the original image.
+ new_size = get_size_with_aspect_ratio(
+ image.shape[-2:],
+ size.shortest_edge,
+ size.longest_edge or size.shortest_edge,
+ )
+ elif size.max_height and size.max_width:
+ new_size = get_image_size_for_max_height_width(image.shape[-2:], size.max_height, size.max_width)
+ elif size.height and size.width:
+ new_size = (size.height, size.width)
+ else:
+ raise ValueError(
+ f"Size must contain 'height' and 'width' keys or 'shortest_edge' and 'longest_edge' keys. Got {size}."
+ )
+
+ image = super().resize(
+ image,
+ size=SizeDict(height=new_size[0], width=new_size[1]),
+ resample=resample,
+ **kwargs,
+ )
+ return image
+
+ def resize_annotation(
+ self,
+ annotation: dict[str, Any],
+ orig_size: tuple[int, int],
+ target_size: tuple[int, int],
+ threshold: float = 0.5,
+ resample: Optional["PILImageResampling"] = PILImageResampling.NEAREST,
+ ):
+ """
+ Resizes an annotation to a target size.
+
+ Args:
+ annotation (`dict[str, Any]`):
+ The annotation dictionary.
+ orig_size (`tuple[int, int]`):
+ The original size of the input image.
+ target_size (`tuple[int, int]`):
+ The target size of the image, as returned by the preprocessing `resize` step.
+ threshold (`float`, *optional*, defaults to 0.5):
+ The threshold used to binarize the segmentation masks.
+ resample (`PILImageResampling`, defaults to `PILImageResampling.NEAREST`):
+ The resampling filter to use when resizing the masks.
+ """
+ ratios = tuple(float(s) / float(s_orig) for s, s_orig in zip(target_size, orig_size))
+ ratio_height, ratio_width = ratios
+
+ new_annotation = {}
+ new_annotation["size"] = target_size
+
+ for key, value in annotation.items():
+ if key == "boxes":
+ boxes = value
+ scaled_boxes = boxes * np.asarray(
+ [ratio_width, ratio_height, ratio_width, ratio_height], dtype=np.float32
+ )
+ new_annotation["boxes"] = scaled_boxes
+ elif key == "area":
+ area = value
+ scaled_area = area * (ratio_width * ratio_height)
+ new_annotation["area"] = scaled_area
+ elif key == "masks":
+ masks = value[:, None]
+ masks = np.array([resize(mask, target_size, resample=resample) for mask in masks])
+ masks = masks.astype(np.float32)
+ masks = masks[:, 0] > threshold
+ new_annotation["masks"] = masks
+ elif key == "size":
+ new_annotation["size"] = target_size
+ else:
+ new_annotation[key] = value
+
+ return new_annotation
+
+ def normalize_annotation(self, annotation: dict, image_size: tuple[int, int]) -> dict:
+ image_height, image_width = image_size
+ norm_annotation = {}
+ for key, value in annotation.items():
+ if key == "boxes":
+ boxes = value
+ boxes = corners_to_center_format(boxes)
+ boxes /= np.asarray([image_width, image_height, image_width, image_height], dtype=np.float32)
+ norm_annotation[key] = boxes
+ else:
+ norm_annotation[key] = value
+ return norm_annotation
+
+ def _update_annotation_for_padded_image(
+ self,
+ annotation: dict,
+ input_image_size: tuple[int, int],
+ output_image_size: tuple[int, int],
+ padding,
+ update_bboxes,
+ ) -> dict:
+ """
+ Update the annotation for a padded image.
+ """
+ new_annotation = {}
+ new_annotation["size"] = output_image_size
+ ratio_height, ratio_width = (input / output for output, input in zip(output_image_size, input_image_size))
+
+ for key, value in annotation.items():
+ if key == "masks":
+ masks = value
+ masks = pad(
+ masks,
+ padding,
+ mode=PaddingMode.CONSTANT,
+ constant_values=0,
+ input_data_format=ChannelDimension.FIRST,
+ )
+ masks = safe_squeeze(masks, 1)
+ new_annotation["masks"] = masks
+ elif key == "boxes" and update_bboxes:
+ boxes = value
+ boxes *= np.asarray(
+ [
+ input_image_size[1] / output_image_size[1],
+ input_image_size[0] / output_image_size[0],
+ input_image_size[1] / output_image_size[1],
+ input_image_size[0] / output_image_size[0],
+ ]
+ )
+ new_annotation["boxes"] = boxes
+ elif key == "size":
+ new_annotation["size"] = output_image_size
+ else:
+ new_annotation[key] = value
+ return new_annotation
+
+ def pad(
+ self,
+ image: np.ndarray,
+ padded_size: tuple[int, int],
+ annotation: dict[str, Any] | None = None,
+ update_bboxes: bool = True,
+ fill: int = 0,
+ ):
+ input_height, input_width = get_image_size(image, channel_dim=ChannelDimension.FIRST)
+ output_height, output_width = padded_size
+ padding_bottom = output_height - input_height
+ padding_right = output_width - input_width
+ if padding_bottom < 0 or padding_right < 0:
+ raise ValueError(
+ f"Padding dimensions are negative. Please make sure that the padded size is larger than the "
+ f"original size. Got padded size: {padded_size}, original size: {(input_height, input_width)}."
+ )
+ if (input_height, input_width) != padded_size:
+ padding = ((0, padding_bottom), (0, padding_right))
+ image = pad(
+ image,
+ padding,
+ mode=PaddingMode.CONSTANT,
+ constant_values=fill,
+ data_format=ChannelDimension.FIRST,
+ input_data_format=ChannelDimension.FIRST,
+ )
+ if annotation is not None:
+ annotation = self._update_annotation_for_padded_image(
+ annotation, (input_height, input_width), (output_height, output_width), padding, update_bboxes
+ )
+
+ # Make a pixel mask for the image, where 1 indicates a valid pixel and 0 indicates padding.
+ pixel_mask = np.zeros(padded_size, dtype=np.int64)
+ pixel_mask[:input_height, :input_width] = 1
+
+ return image, pixel_mask, annotation
+
+ @auto_docstring
+ def preprocess(
+ self,
+ images: ImageInput,
+ annotations: AnnotationType | list[AnnotationType] | None = None,
+ return_segmentation_masks: bool | None = None,
+ masks_path: str | pathlib.Path | None = None,
+ **kwargs: Unpack[RTDetrImageProcessorKwargs],
+ ) -> BatchFeature:
+ r"""
+ annotations (`AnnotationType` or `list[AnnotationType]`, *optional*):
+ Annotations to transform according to the padding that is applied to the images.
+ return_segmentation_masks (`bool`, *optional*, defaults to `self.return_segmentation_masks`):
+ Whether to return segmentation masks.
+ masks_path (`str` or `pathlib.Path`, *optional*):
+ Path to the directory containing the segmentation masks.
+ """
+ return super().preprocess(images, annotations, return_segmentation_masks, masks_path, **kwargs)
+
+ def _preprocess(
+ self,
+ images: list[np.ndarray],
+ annotations: AnnotationType | list[AnnotationType] | None,
+ return_segmentation_masks: bool,
+ masks_path: str | pathlib.Path | None,
+ do_resize: bool,
+ size: SizeDict,
+ resample: "PILImageResampling | None",
+ do_rescale: bool,
+ rescale_factor: float,
+ do_normalize: bool,
+ do_convert_annotations: bool,
+ image_mean: float | list[float] | None,
+ image_std: float | list[float] | None,
+ do_pad: bool,
+ pad_size: SizeDict | None,
+ format: str | AnnotationFormat | None,
+ return_tensors: str | TensorType | None,
+ **kwargs,
+ ) -> BatchFeature:
+ """
+ Preprocess an image or a batch of images so that it can be used by the model.
+ """
+
+ if annotations is not None and isinstance(annotations, dict):
+ annotations = [annotations]
+
+ if annotations is not None and len(images) != len(annotations):
+ raise ValueError(
+ f"The number of images ({len(images)}) and annotations ({len(annotations)}) do not match."
+ )
+
+ format = AnnotationFormat(format)
+ if annotations is not None:
+ validate_annotations(format, SUPPORTED_ANNOTATION_FORMATS, annotations)
+
+ data = {}
+ processed_images = []
+ processed_annotations = []
+ pixel_masks = [] # Initialize pixel_masks here
+ for image, annotation in zip(images, annotations if annotations is not None else [None] * len(images)):
+ # prepare (COCO annotations as a list of Dict -> DETR target as a single Dict per image)
+ if annotations is not None:
+ annotation = self.prepare_annotation(
+ image,
+ annotation,
+ format,
+ return_segmentation_masks=return_segmentation_masks,
+ masks_path=masks_path,
+ input_data_format=ChannelDimension.FIRST,
+ )
+
+ if do_resize:
+ resized_image = self.resize(image, size=size, resample=resample)
+ if annotations is not None:
+ annotation = self.resize_annotation(
+ annotation,
+ orig_size=image.shape[-2:],
+ target_size=resized_image.shape[-2:],
+ )
+ image = resized_image
+
+ if do_rescale:
+ image = self.rescale(image, rescale_factor)
+ if do_normalize:
+ image = self.normalize(image, image_mean, image_std)
+ if do_convert_annotations and annotations is not None:
+ annotation = self.normalize_annotation(annotation, get_image_size(image, ChannelDimension.FIRST))
+
+ processed_images.append(image)
+ processed_annotations.append(annotation)
+ images = processed_images
+ annotations = processed_annotations if annotations is not None else None
+
+ if do_pad:
+ # depends on all resized image shapes so we need another loop
+ if pad_size is not None:
+ padded_size = (pad_size.height, pad_size.width)
+ else:
+ padded_size = get_max_height_width(images)
+
+ padded_images = []
+ padded_annotations = []
+ for image, annotation in zip(images, annotations if annotations is not None else [None] * len(images)):
+ # Pads images and returns their mask: {'pixel_values': ..., 'pixel_mask': ...}
+ if padded_size == image.shape[-2:]:
+ padded_images.append(image)
+ pixel_masks.append(np.ones(padded_size, dtype=np.int64))
+ padded_annotations.append(annotation)
+ continue
+ image, pixel_mask, annotation = self.pad(
+ image, padded_size, annotation=annotation, update_bboxes=do_convert_annotations
+ )
+ padded_images.append(image)
+ padded_annotations.append(annotation)
+ pixel_masks.append(pixel_mask)
+ images = padded_images
+ annotations = padded_annotations if annotations is not None else None
+ data.update({"pixel_mask": pixel_masks})
+
+ data.update({"pixel_values": images})
+ encoded_inputs = BatchFeature(data, tensor_type=return_tensors)
+ if annotations is not None:
+ encoded_inputs["labels"] = [
+ BatchFeature(annotation, tensor_type=return_tensors) for annotation in annotations
+ ]
+ return encoded_inputs
+
+ @requires(backends=("torch",))
+ def post_process_object_detection(
+ self,
+ outputs,
+ threshold: float = 0.5,
+ target_sizes: TensorType | list[tuple] = None,
+ use_focal_loss: bool = True,
+ ):
+ """
+ Converts the raw output of [`DetrForObjectDetection`] into final bounding boxes in (top_left_x, top_left_y,
+ bottom_right_x, bottom_right_y) format. Only supports PyTorch.
+
+ Args:
+ outputs ([`DetrObjectDetectionOutput`]):
+ Raw outputs of the model.
+ threshold (`float`, *optional*, defaults to 0.5):
+ Score threshold to keep object detection predictions.
+ target_sizes (`torch.Tensor` or `list[tuple[int, int]]`, *optional*):
+ Tensor of shape `(batch_size, 2)` or list of tuples (`tuple[int, int]`) containing the target size
+ `(height, width)` of each image in the batch. If unset, predictions will not be resized.
+ use_focal_loss (`bool` defaults to `True`):
+ Variable informing if the focal loss was used to predict the outputs. If `True`, a sigmoid is applied
+ to compute the scores of each detection, otherwise, a softmax function is used.
+
+ Returns:
+ `list[Dict]`: A list of dictionaries, each dictionary containing the scores, labels and boxes for an image
+ in the batch as predicted by the model.
+ """
+ requires_backends(self, ["torch"])
+ out_logits, out_bbox = outputs.logits, outputs.pred_boxes
+ # convert from relative cxcywh to absolute xyxy
+ boxes = center_to_corners_format(out_bbox)
+ if target_sizes is not None:
+ if len(out_logits) != len(target_sizes):
+ raise ValueError(
+ "Make sure that you pass in as many target sizes as the batch dimension of the logits"
+ )
+ if isinstance(target_sizes, list):
+ img_h, img_w = torch.as_tensor(target_sizes).unbind(1)
+ else:
+ img_h, img_w = target_sizes.unbind(1)
+ scale_fct = torch.stack([img_w, img_h, img_w, img_h], dim=1).to(boxes.device)
+ boxes = boxes * scale_fct[:, None, :]
+
+ num_top_queries = out_logits.shape[1]
+ num_classes = out_logits.shape[2]
+
+ if use_focal_loss:
+ scores = torch.nn.functional.sigmoid(out_logits)
+ scores, index = torch.topk(scores.flatten(1), num_top_queries, axis=-1)
+ labels = index % num_classes
+ index = index // num_classes
+ boxes = boxes.gather(dim=1, index=index.unsqueeze(-1).repeat(1, 1, boxes.shape[-1]))
+ else:
+ scores = torch.nn.functional.softmax(out_logits)[:, :, :-1]
+ scores, labels = scores.max(dim=-1)
+ if scores.shape[1] > num_top_queries:
+ scores, index = torch.topk(scores, num_top_queries, dim=-1)
+ labels = torch.gather(labels, dim=1, index=index)
+ boxes = torch.gather(boxes, dim=1, index=index.unsqueeze(-1).tile(1, 1, boxes.shape[-1]))
+
+ results = []
+ for score, label, box in zip(scores, labels, boxes):
+ results.append(
+ {
+ "scores": score[score > threshold],
+ "labels": label[score > threshold],
+ "boxes": box[score > threshold],
+ }
+ )
+
+ return results
+
+
+__all__ = ["RTDetrImageProcessorPil"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/rt_detr/image_processing_rt_detr.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/rt_detr/image_processing_rt_detr.py
new file mode 100644
index 0000000000000000000000000000000000000000..0aadd7ece2e90620927934e5ad896f8af6125276
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/rt_detr/image_processing_rt_detr.py
@@ -0,0 +1,555 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/rt_detr/modular_rt_detr.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_rt_detr.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2024 Baidu Inc and The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import pathlib
+from typing import Any, Optional
+
+import torch
+from torchvision.transforms.v2 import functional as tvF
+
+from ...image_processing_backends import TorchvisionBackend
+from ...image_processing_utils import BatchFeature, SizeDict
+from ...image_transforms import (
+ center_to_corners_format,
+ corners_to_center_format,
+ get_size_with_aspect_ratio,
+ safe_squeeze,
+)
+from ...image_utils import (
+ IMAGENET_DEFAULT_MEAN,
+ IMAGENET_DEFAULT_STD,
+ AnnotationFormat,
+ AnnotationType,
+ ChannelDimension,
+ ImageInput,
+ PILImageResampling,
+ get_image_size,
+ get_image_size_for_max_height_width,
+ get_max_height_width,
+ validate_annotations,
+)
+from ...processing_utils import ImagesKwargs, Unpack
+from ...utils import TensorType, auto_docstring, requires_backends
+
+
+class RTDetrImageProcessorKwargs(ImagesKwargs, total=False):
+ r"""
+ format (`str`, *optional*, defaults to `AnnotationFormat.COCO_DETECTION`):
+ Data format of the annotations. One of "coco_detection" or "coco_panoptic".
+ do_convert_annotations (`bool`, *optional*, defaults to `True`):
+ Controls whether to convert the annotations to the format expected by the RT_DETR model. Converts the
+ bounding boxes to the format `(center_x, center_y, width, height)` and in the range `[0, 1]`.
+ Can be overridden by the `do_convert_annotations` parameter in the `preprocess` method.
+ """
+
+ format: str | AnnotationFormat
+ do_convert_annotations: bool
+
+
+SUPPORTED_ANNOTATION_FORMATS = (AnnotationFormat.COCO_DETECTION, AnnotationFormat.COCO_PANOPTIC)
+
+
+def prepare_coco_detection_annotation(
+ image,
+ target,
+ return_segmentation_masks: bool = False,
+ input_data_format: ChannelDimension | str | None = None,
+):
+ """
+ Convert the target in COCO format into the format expected by RT-DETR.
+ """
+ image_height, image_width = image.size()[-2:]
+
+ image_id = target["image_id"]
+ image_id = torch.as_tensor([image_id], dtype=torch.int64, device=image.device)
+
+ # Get all COCO annotations for the given image.
+ annotations = target["annotations"]
+ classes = []
+ area = []
+ boxes = []
+ keypoints = []
+ for obj in annotations:
+ if "iscrowd" not in obj or obj["iscrowd"] == 0:
+ classes.append(obj["category_id"])
+ area.append(obj["area"])
+ boxes.append(obj["bbox"])
+ if "keypoints" in obj:
+ keypoints.append(obj["keypoints"])
+
+ classes = torch.as_tensor(classes, dtype=torch.int64, device=image.device)
+ area = torch.as_tensor(area, dtype=torch.float32, device=image.device)
+ iscrowd = torch.zeros_like(classes, dtype=torch.int64, device=image.device)
+ # guard against no boxes via resizing
+ boxes = torch.as_tensor(boxes, dtype=torch.float32, device=image.device).reshape(-1, 4)
+ boxes[:, 2:] += boxes[:, :2]
+ boxes[:, 0::2] = boxes[:, 0::2].clip(min=0, max=image_width)
+ boxes[:, 1::2] = boxes[:, 1::2].clip(min=0, max=image_height)
+
+ keep = (boxes[:, 3] > boxes[:, 1]) & (boxes[:, 2] > boxes[:, 0])
+
+ new_target = {
+ "image_id": image_id,
+ "class_labels": classes[keep],
+ "boxes": boxes[keep],
+ "area": area[keep],
+ "iscrowd": iscrowd[keep],
+ "orig_size": torch.as_tensor([int(image_height), int(image_width)], dtype=torch.int64, device=image.device),
+ }
+
+ if keypoints:
+ keypoints = torch.as_tensor(keypoints, dtype=torch.float32, device=image.device)
+ # Apply the keep mask here to filter the relevant annotations
+ keypoints = keypoints[keep]
+ num_keypoints = keypoints.shape[0]
+ keypoints = keypoints.reshape((-1, 3)) if num_keypoints else keypoints
+ new_target["keypoints"] = keypoints
+
+ return new_target
+
+
+@auto_docstring
+class RTDetrImageProcessor(TorchvisionBackend):
+ valid_kwargs = RTDetrImageProcessorKwargs
+ resample = PILImageResampling.BILINEAR
+ image_mean = IMAGENET_DEFAULT_MEAN
+ image_std = IMAGENET_DEFAULT_STD
+ format = AnnotationFormat.COCO_DETECTION
+ do_resize = True
+ do_rescale = True
+ do_normalize = False
+ do_pad = False
+ size = {"height": 640, "width": 640}
+ default_to_square = False
+ model_input_names = ["pixel_values", "pixel_mask"]
+ do_convert_annotations = True
+
+ def __init__(self, **kwargs: Unpack[RTDetrImageProcessorKwargs]) -> None:
+ # Backwards compatibility
+ do_convert_annotations = kwargs.get("do_convert_annotations")
+ do_normalize = kwargs.get("do_normalize")
+ if do_convert_annotations is None and getattr(self, "do_convert_annotations", None) is None:
+ self.do_convert_annotations = do_normalize if do_normalize is not None else self.do_normalize
+
+ super().__init__(**kwargs)
+
+ def prepare_annotation(
+ self,
+ image: torch.Tensor,
+ target: dict,
+ format: AnnotationFormat | None = None,
+ return_segmentation_masks: bool | None = None,
+ masks_path: str | pathlib.Path | None = None,
+ input_data_format: str | ChannelDimension | None = None,
+ ) -> dict:
+ """
+ Prepare an annotation for feeding into RT_DETR model.
+ """
+ format = format if format is not None else self.format
+
+ if format == AnnotationFormat.COCO_DETECTION:
+ return_segmentation_masks = False if return_segmentation_masks is None else return_segmentation_masks
+ target = prepare_coco_detection_annotation(
+ image, target, return_segmentation_masks, input_data_format=input_data_format
+ )
+ else:
+ raise ValueError(f"Format {format} is not supported.")
+ return target
+
+ def resize(
+ self,
+ image: torch.Tensor,
+ size: SizeDict,
+ resample: Optional["PILImageResampling | tvF.InterpolationMode | int"] = None,
+ **kwargs,
+ ) -> torch.Tensor:
+ """
+ Resize the image to the given size. Size can be `min_size` (scalar) or `(height, width)` tuple. If size is an
+ int, smaller edge of the image will be matched to this number.
+
+ Args:
+ image (`torch.Tensor`):
+ Image to resize.
+ size (`SizeDict`):
+ Size of the image's `(height, width)` dimensions after resizing. Available options are:
+ - `{"height": int, "width": int}`: The image will be resized to the exact size `(height, width)`.
+ Do NOT keep the aspect ratio.
+ - `{"shortest_edge": int, "longest_edge": int}`: The image will be resized to a maximum size respecting
+ the aspect ratio and keeping the shortest edge less or equal to `shortest_edge` and the longest edge
+ less or equal to `longest_edge`.
+ - `{"max_height": int, "max_width": int}`: The image will be resized to the maximum size respecting the
+ aspect ratio and keeping the height less or equal to `max_height` and the width less or equal to
+ `max_width`.
+ resample (`PILImageResampling | tvF.InterpolationMode | int`, *optional*, defaults to `PILImageResampling.BILINEAR`):
+ Resampling filter to use if resizing the image.
+ """
+ if size.shortest_edge and size.longest_edge:
+ # Resize the image so that the shortest edge or the longest edge is of the given size
+ # while maintaining the aspect ratio of the original image.
+ new_size = get_size_with_aspect_ratio(image.shape[-2:], size.shortest_edge, size.longest_edge)
+ elif size.max_height and size.max_width:
+ new_size = get_image_size_for_max_height_width(image.shape[-2:], size.max_height, size.max_width)
+ elif size.height and size.width:
+ new_size = (size.height, size.width)
+ else:
+ raise ValueError(
+ f"Size must contain 'height' and 'width' keys or 'shortest_edge' and 'longest_edge' keys. Got {size}."
+ )
+
+ image = super().resize(
+ image, size=SizeDict(height=new_size[0], width=new_size[1]), resample=resample, **kwargs
+ )
+ return image
+
+ def resize_annotation(
+ self,
+ annotation: dict[str, Any],
+ orig_size: tuple[int, int],
+ target_size: tuple[int, int],
+ threshold: float = 0.5,
+ resample: Optional["PILImageResampling | tvF.InterpolationMode | int"] = PILImageResampling.NEAREST,
+ ):
+ """
+ Resizes an annotation to a target size.
+
+ Args:
+ annotation (`dict[str, Any]`):
+ The annotation dictionary.
+ orig_size (`tuple[int, int]`):
+ The original size of the input image.
+ target_size (`tuple[int, int]`):
+ The target size of the image, as returned by the preprocessing `resize` step.
+ threshold (`float`, *optional*, defaults to 0.5):
+ The threshold used to binarize the segmentation masks.
+ resample (`PILImageResampling | tvF.InterpolationMode | int`, defaults to `tvF.InterpolationMode.NEAREST_EXACT`):
+ The resampling filter to use when resizing the masks.
+ """
+ ratio_height, ratio_width = [target / orig for target, orig in zip(target_size, orig_size)]
+
+ new_annotation = {}
+ new_annotation["size"] = target_size
+
+ for key, value in annotation.items():
+ if key == "boxes":
+ boxes = value
+ scaled_boxes = boxes * torch.as_tensor(
+ [ratio_width, ratio_height, ratio_width, ratio_height], dtype=torch.float32, device=boxes.device
+ )
+ new_annotation["boxes"] = scaled_boxes
+ elif key == "area":
+ area = value
+ scaled_area = area * (ratio_width * ratio_height)
+ new_annotation["area"] = scaled_area
+ elif key == "masks":
+ masks = value[:, None]
+ masks = [
+ super(RTDetrImageProcessor, self).resize(
+ mask, size=SizeDict(height=target_size[0], width=target_size[1]), resample=resample
+ )
+ for mask in masks
+ ]
+ masks = torch.stack(masks).to(torch.float32)
+ masks = masks[:, 0] > threshold
+ new_annotation["masks"] = masks
+ elif key == "size":
+ new_annotation["size"] = target_size
+ else:
+ new_annotation[key] = value
+
+ return new_annotation
+
+ def normalize_annotation(self, annotation: dict, image_size: tuple[int, int]) -> dict:
+ image_height, image_width = image_size
+ norm_annotation = {}
+ for key, value in annotation.items():
+ if key == "boxes":
+ boxes = value
+ boxes = corners_to_center_format(boxes)
+ boxes /= torch.as_tensor(
+ [image_width, image_height, image_width, image_height], dtype=torch.float32, device=boxes.device
+ )
+ norm_annotation[key] = boxes
+ else:
+ norm_annotation[key] = value
+ return norm_annotation
+
+ def _update_annotation_for_padded_image(
+ self,
+ annotation: dict,
+ input_image_size: tuple[int, int],
+ output_image_size: tuple[int, int],
+ padding,
+ update_bboxes,
+ ) -> dict:
+ """
+ Update the annotation for a padded image.
+ """
+ new_annotation = {}
+ new_annotation["size"] = output_image_size
+ ratio_height, ratio_width = (input / output for output, input in zip(output_image_size, input_image_size))
+
+ for key, value in annotation.items():
+ if key == "masks":
+ masks = value
+ masks = tvF.pad(
+ masks,
+ padding,
+ fill=0,
+ )
+ masks = safe_squeeze(masks, 1)
+ new_annotation["masks"] = masks
+ elif key == "boxes" and update_bboxes:
+ boxes = value
+ boxes *= torch.as_tensor([ratio_width, ratio_height, ratio_width, ratio_height], device=boxes.device)
+ new_annotation["boxes"] = boxes
+ elif key == "size":
+ new_annotation["size"] = output_image_size
+ else:
+ new_annotation[key] = value
+ return new_annotation
+
+ def pad(
+ self,
+ image: torch.Tensor,
+ padded_size: tuple[int, int],
+ annotation: dict[str, Any] | None = None,
+ update_bboxes: bool = True,
+ fill: int = 0,
+ ):
+ original_size = image.size()[-2:]
+ padding_bottom = padded_size[0] - original_size[0]
+ padding_right = padded_size[1] - original_size[1]
+ if padding_bottom < 0 or padding_right < 0:
+ raise ValueError(
+ f"Padding dimensions are negative. Please make sure that the padded size is larger than the "
+ f"original size. Got padded size: {padded_size}, original size: {original_size}."
+ )
+ if original_size != padded_size:
+ padding = [0, 0, padding_right, padding_bottom]
+ image = tvF.pad(image, padding, fill=fill)
+ if annotation is not None:
+ annotation = self._update_annotation_for_padded_image(
+ annotation, original_size, padded_size, padding, update_bboxes
+ )
+
+ # Make a pixel mask for the image, where 1 indicates a valid pixel and 0 indicates padding.
+ pixel_mask = torch.zeros(padded_size, dtype=torch.int64, device=image.device)
+ pixel_mask[: original_size[0], : original_size[1]] = 1
+
+ return image, pixel_mask, annotation
+
+ @auto_docstring
+ def preprocess(
+ self,
+ images: ImageInput,
+ annotations: AnnotationType | list[AnnotationType] | None = None,
+ return_segmentation_masks: bool | None = None,
+ masks_path: str | pathlib.Path | None = None,
+ **kwargs: Unpack[RTDetrImageProcessorKwargs],
+ ) -> BatchFeature:
+ r"""
+ annotations (`AnnotationType` or `list[AnnotationType]`, *optional*):
+ Annotations to transform according to the padding that is applied to the images.
+ return_segmentation_masks (`bool`, *optional*, defaults to `self.return_segmentation_masks`):
+ Whether to return segmentation masks.
+ masks_path (`str` or `pathlib.Path`, *optional*):
+ Path to the directory containing the segmentation masks.
+ """
+ return super().preprocess(images, annotations, return_segmentation_masks, masks_path, **kwargs)
+
+ def _preprocess(
+ self,
+ images: list["torch.Tensor"],
+ annotations: AnnotationType | list[AnnotationType] | None,
+ return_segmentation_masks: bool,
+ masks_path: str | pathlib.Path | None,
+ do_resize: bool,
+ size: SizeDict,
+ resample: "PILImageResampling | None",
+ do_rescale: bool,
+ rescale_factor: float,
+ do_normalize: bool,
+ do_convert_annotations: bool,
+ image_mean: float | list[float] | None,
+ image_std: float | list[float] | None,
+ do_pad: bool,
+ pad_size: SizeDict | None,
+ format: str | AnnotationFormat | None,
+ return_tensors: str | TensorType | None,
+ **kwargs,
+ ) -> BatchFeature:
+ """
+ Preprocess an image or a batch of images so that it can be used by the model.
+ """
+
+ if annotations is not None and isinstance(annotations, dict):
+ annotations = [annotations]
+
+ if annotations is not None and len(images) != len(annotations):
+ raise ValueError(
+ f"The number of images ({len(images)}) and annotations ({len(annotations)}) do not match."
+ )
+
+ format = AnnotationFormat(format)
+ if annotations is not None:
+ validate_annotations(format, SUPPORTED_ANNOTATION_FORMATS, annotations)
+
+ data = {}
+ processed_images = []
+ processed_annotations = []
+ pixel_masks = [] # Initialize pixel_masks here
+ for image, annotation in zip(images, annotations if annotations is not None else [None] * len(images)):
+ # prepare (COCO annotations as a list of Dict -> DETR target as a single Dict per image)
+ if annotations is not None:
+ annotation = self.prepare_annotation(
+ image,
+ annotation,
+ format,
+ return_segmentation_masks=return_segmentation_masks,
+ masks_path=masks_path,
+ input_data_format=ChannelDimension.FIRST,
+ )
+
+ if do_resize:
+ resized_image = self.resize(image, size=size, resample=resample)
+ if annotations is not None:
+ annotation = self.resize_annotation(
+ annotation,
+ orig_size=image.size()[-2:],
+ target_size=resized_image.size()[-2:],
+ )
+ image = resized_image
+ # Fused rescale and normalize
+ image = self.rescale_and_normalize(image, do_rescale, rescale_factor, do_normalize, image_mean, image_std)
+ if do_convert_annotations and annotations is not None:
+ annotation = self.normalize_annotation(annotation, get_image_size(image, ChannelDimension.FIRST))
+
+ processed_images.append(image)
+ processed_annotations.append(annotation)
+ images = processed_images
+ annotations = processed_annotations if annotations is not None else None
+
+ if do_pad:
+ # depends on all resized image shapes so we need another loop
+ if pad_size is not None:
+ padded_size = (pad_size.height, pad_size.width)
+ else:
+ padded_size = get_max_height_width(images)
+
+ padded_images = []
+ padded_annotations = []
+ for image, annotation in zip(images, annotations if annotations is not None else [None] * len(images)):
+ # Pads images and returns their mask: {'pixel_values': ..., 'pixel_mask': ...}
+ if padded_size == image.size()[-2:]:
+ padded_images.append(image)
+ pixel_masks.append(torch.ones(padded_size, dtype=torch.int64, device=image.device))
+ padded_annotations.append(annotation)
+ continue
+ image, pixel_mask, annotation = self.pad(
+ image, padded_size, annotation=annotation, update_bboxes=do_convert_annotations
+ )
+ padded_images.append(image)
+ padded_annotations.append(annotation)
+ pixel_masks.append(pixel_mask)
+ images = padded_images
+ annotations = padded_annotations if annotations is not None else None
+ data.update({"pixel_mask": torch.stack(pixel_masks, dim=0)})
+
+ data.update({"pixel_values": torch.stack(images, dim=0)})
+ encoded_inputs = BatchFeature(data, tensor_type=return_tensors)
+ if annotations is not None:
+ encoded_inputs["labels"] = [
+ BatchFeature(annotation, tensor_type=return_tensors) for annotation in annotations
+ ]
+ return encoded_inputs
+
+ def post_process_object_detection(
+ self,
+ outputs,
+ threshold: float = 0.5,
+ target_sizes: TensorType | list[tuple] = None,
+ use_focal_loss: bool = True,
+ ):
+ """
+ Converts the raw output of [`DetrForObjectDetection`] into final bounding boxes in (top_left_x, top_left_y,
+ bottom_right_x, bottom_right_y) format. Only supports PyTorch.
+
+ Args:
+ outputs ([`DetrObjectDetectionOutput`]):
+ Raw outputs of the model.
+ threshold (`float`, *optional*, defaults to 0.5):
+ Score threshold to keep object detection predictions.
+ target_sizes (`torch.Tensor` or `list[tuple[int, int]]`, *optional*):
+ Tensor of shape `(batch_size, 2)` or list of tuples (`tuple[int, int]`) containing the target size
+ `(height, width)` of each image in the batch. If unset, predictions will not be resized.
+ use_focal_loss (`bool` defaults to `True`):
+ Variable informing if the focal loss was used to predict the outputs. If `True`, a sigmoid is applied
+ to compute the scores of each detection, otherwise, a softmax function is used.
+
+ Returns:
+ `list[Dict]`: A list of dictionaries, each dictionary containing the scores, labels and boxes for an image
+ in the batch as predicted by the model.
+ """
+ requires_backends(self, ["torch"])
+ out_logits, out_bbox = outputs.logits, outputs.pred_boxes
+ # convert from relative cxcywh to absolute xyxy
+ boxes = center_to_corners_format(out_bbox)
+ if target_sizes is not None:
+ if len(out_logits) != len(target_sizes):
+ raise ValueError(
+ "Make sure that you pass in as many target sizes as the batch dimension of the logits"
+ )
+ if isinstance(target_sizes, list):
+ img_h, img_w = torch.as_tensor(target_sizes).unbind(1)
+ else:
+ img_h, img_w = target_sizes.unbind(1)
+ scale_fct = torch.stack([img_w, img_h, img_w, img_h], dim=1).to(boxes.device)
+ boxes = boxes * scale_fct[:, None, :]
+
+ num_top_queries = out_logits.shape[1]
+ num_classes = out_logits.shape[2]
+
+ if use_focal_loss:
+ scores = torch.nn.functional.sigmoid(out_logits)
+ scores, index = torch.topk(scores.flatten(1), num_top_queries, axis=-1)
+ labels = index % num_classes
+ index = index // num_classes
+ boxes = boxes.gather(dim=1, index=index.unsqueeze(-1).repeat(1, 1, boxes.shape[-1]))
+ else:
+ scores = torch.nn.functional.softmax(out_logits)[:, :, :-1]
+ scores, labels = scores.max(dim=-1)
+ if scores.shape[1] > num_top_queries:
+ scores, index = torch.topk(scores, num_top_queries, dim=-1)
+ labels = torch.gather(labels, dim=1, index=index)
+ boxes = torch.gather(boxes, dim=1, index=index.unsqueeze(-1).tile(1, 1, boxes.shape[-1]))
+
+ results = []
+ for score, label, box in zip(scores, labels, boxes):
+ results.append(
+ {
+ "scores": score[score > threshold],
+ "labels": label[score > threshold],
+ "boxes": box[score > threshold],
+ }
+ )
+
+ return results
+
+
+__all__ = ["RTDetrImageProcessor"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/rt_detr/modeling_rt_detr.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/rt_detr/modeling_rt_detr.py
new file mode 100644
index 0000000000000000000000000000000000000000..ce58da5269d02f61a824bc68a5cf369075e1531b
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/rt_detr/modeling_rt_detr.py
@@ -0,0 +1,1907 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/rt_detr/modular_rt_detr.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_rt_detr.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2024 Baidu Inc and The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import math
+import warnings
+from collections.abc import Callable
+from dataclasses import dataclass
+
+import torch
+import torch.nn.functional as F
+from torch import Tensor, nn
+
+from ... import initialization as init
+from ...activations import ACT2CLS, ACT2FN
+from ...backbone_utils import load_backbone
+from ...image_transforms import center_to_corners_format, corners_to_center_format
+from ...integrations import use_kernel_forward_from_hub
+from ...modeling_outputs import BaseModelOutput
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
+from ...processing_utils import Unpack
+from ...pytorch_utils import compile_compatible_method_lru_cache
+from ...utils import (
+ ModelOutput,
+ TransformersKwargs,
+ auto_docstring,
+ torch_compilable_check,
+ torch_int,
+)
+from ...utils.generic import can_return_tuple, merge_with_config_defaults
+from ...utils.output_capturing import capture_outputs
+from .configuration_rt_detr import RTDetrConfig
+
+
+@auto_docstring(
+ custom_intro="""
+ Base class for outputs of the RTDetrDecoder. This class adds two attributes to
+ BaseModelOutputWithCrossAttentions, namely:
+ - a stacked tensor of intermediate decoder hidden states (i.e. the output of each decoder layer)
+ - a stacked tensor of intermediate reference points.
+ """
+)
+@dataclass
+class RTDetrDecoderOutput(ModelOutput):
+ r"""
+ intermediate_hidden_states (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, hidden_size)`):
+ Stacked intermediate hidden states (output of each layer of the decoder).
+ intermediate_logits (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, sequence_length, config.num_labels)`):
+ Stacked intermediate logits (logits of each layer of the decoder).
+ intermediate_reference_points (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, sequence_length, hidden_size)`):
+ Stacked intermediate reference points (reference points of each layer of the decoder).
+ intermediate_predicted_corners (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, 4)`):
+ Stacked intermediate predicted corners (predicted corners of each layer of the decoder).
+ initial_reference_points (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, 4)`):
+ Stacked initial reference points (initial reference points of each layer of the decoder).
+ cross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` and `config.add_cross_attention=True` is passed or when `config.output_attentions=True`):
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
+ sequence_length)`. Attentions weights of the decoder's cross-attention layer, after the attention softmax,
+ used to compute the weighted average in the cross-attention heads.
+ """
+
+ last_hidden_state: torch.FloatTensor | None = None
+ intermediate_hidden_states: torch.FloatTensor | None = None
+ intermediate_logits: torch.FloatTensor | None = None
+ intermediate_reference_points: torch.FloatTensor | None = None
+ intermediate_predicted_corners: torch.FloatTensor | None = None
+ initial_reference_points: torch.FloatTensor | None = None
+ hidden_states: tuple[torch.FloatTensor] | None = None
+ attentions: tuple[torch.FloatTensor] | None = None
+ cross_attentions: tuple[torch.FloatTensor] | None = None
+
+
+@auto_docstring(
+ custom_intro="""
+ Base class for outputs of the RT-DETR encoder-decoder model.
+ """
+)
+@dataclass
+class RTDetrModelOutput(ModelOutput):
+ r"""
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_size)`):
+ Sequence of hidden-states at the output of the last layer of the decoder of the model.
+ intermediate_hidden_states (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, hidden_size)`):
+ Stacked intermediate hidden states (output of each layer of the decoder).
+ intermediate_logits (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, sequence_length, config.num_labels)`):
+ Stacked intermediate logits (logits of each layer of the decoder).
+ intermediate_reference_points (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, 4)`):
+ Stacked intermediate reference points (reference points of each layer of the decoder).
+ intermediate_predicted_corners (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, 4)`):
+ Stacked intermediate predicted corners (predicted corners of each layer of the decoder).
+ initial_reference_points (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)`):
+ Initial reference points used for the first decoder layer.
+ init_reference_points (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)`):
+ Initial reference points sent through the Transformer decoder.
+ enc_topk_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.num_labels)`):
+ Predicted bounding boxes scores where the top `config.two_stage_num_proposals` scoring bounding boxes are
+ picked as region proposals in the encoder stage. Output of bounding box binary classification (i.e.
+ foreground and background).
+ enc_topk_bboxes (`torch.FloatTensor` of shape `(batch_size, sequence_length, 4)`):
+ Logits of predicted bounding boxes coordinates in the encoder stage.
+ enc_outputs_class (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.num_labels)`, *optional*, returned when `config.with_box_refine=True` and `config.two_stage=True`):
+ Predicted bounding boxes scores where the top `config.two_stage_num_proposals` scoring bounding boxes are
+ picked as region proposals in the first stage. Output of bounding box binary classification (i.e.
+ foreground and background).
+ enc_outputs_coord_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, 4)`, *optional*, returned when `config.with_box_refine=True` and `config.two_stage=True`):
+ Logits of predicted bounding boxes coordinates in the first stage.
+ denoising_meta_values (`dict`):
+ Extra dictionary for the denoising related values.
+ """
+
+ last_hidden_state: torch.FloatTensor | None = None
+ intermediate_hidden_states: torch.FloatTensor | None = None
+ intermediate_logits: torch.FloatTensor | None = None
+ intermediate_reference_points: torch.FloatTensor | None = None
+ intermediate_predicted_corners: torch.FloatTensor | None = None
+ initial_reference_points: torch.FloatTensor | None = None
+ decoder_hidden_states: tuple[torch.FloatTensor] | None = None
+ decoder_attentions: tuple[torch.FloatTensor] | None = None
+ cross_attentions: tuple[torch.FloatTensor] | None = None
+ encoder_last_hidden_state: torch.FloatTensor | None = None
+ encoder_hidden_states: tuple[torch.FloatTensor] | None = None
+ encoder_attentions: tuple[torch.FloatTensor] | None = None
+ init_reference_points: torch.FloatTensor | None = None
+ enc_topk_logits: torch.FloatTensor | None = None
+ enc_topk_bboxes: torch.FloatTensor | None = None
+ enc_outputs_class: torch.FloatTensor | None = None
+ enc_outputs_coord_logits: torch.FloatTensor | None = None
+ denoising_meta_values: dict | None = None
+
+
+@auto_docstring(
+ custom_intro="""
+ Output type of [`RTDetrForObjectDetection`].
+ """
+)
+@dataclass
+class RTDetrObjectDetectionOutput(ModelOutput):
+ r"""
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` are provided)):
+ Total loss as a linear combination of a negative log-likehood (cross-entropy) for class prediction and a
+ bounding box loss. The latter is defined as a linear combination of the L1 loss and the generalized
+ scale-invariant IoU loss.
+ loss_dict (`Dict`, *optional*):
+ A dictionary containing the individual losses. Useful for logging.
+ logits (`torch.FloatTensor` of shape `(batch_size, num_queries, num_classes + 1)`):
+ Classification logits (including no-object) for all queries.
+ pred_boxes (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)`):
+ Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height). These
+ values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding
+ possible padding). You can use [`~RTDetrImageProcessor.post_process_object_detection`] to retrieve the
+ unnormalized (absolute) bounding boxes.
+ auxiliary_outputs (`list[Dict]`, *optional*):
+ Optional, only returned when auxiliary losses are activated (i.e. `config.auxiliary_loss` is set to `True`)
+ and labels are provided. It is a list of dictionaries containing the two above keys (`logits` and
+ `pred_boxes`) for each decoder layer.
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_size)`):
+ Sequence of hidden-states at the output of the last layer of the decoder of the model.
+ intermediate_hidden_states (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, hidden_size)`):
+ Stacked intermediate hidden states (output of each layer of the decoder).
+ intermediate_logits (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, config.num_labels)`):
+ Stacked intermediate logits (logits of each layer of the decoder).
+ intermediate_reference_points (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, 4)`):
+ Stacked intermediate reference points (reference points of each layer of the decoder).
+ intermediate_predicted_corners (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, 4)`):
+ Stacked intermediate predicted corners (predicted corners of each layer of the decoder).
+ initial_reference_points (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, 4)`):
+ Stacked initial reference points (initial reference points of each layer of the decoder).
+ init_reference_points (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)`):
+ Initial reference points sent through the Transformer decoder.
+ enc_topk_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.num_labels)`, *optional*, returned when `config.with_box_refine=True` and `config.two_stage=True`):
+ Logits of predicted bounding boxes coordinates in the encoder.
+ enc_topk_bboxes (`torch.FloatTensor` of shape `(batch_size, sequence_length, 4)`, *optional*, returned when `config.with_box_refine=True` and `config.two_stage=True`):
+ Logits of predicted bounding boxes coordinates in the encoder.
+ enc_outputs_class (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.num_labels)`, *optional*, returned when `config.with_box_refine=True` and `config.two_stage=True`):
+ Predicted bounding boxes scores where the top `config.two_stage_num_proposals` scoring bounding boxes are
+ picked as region proposals in the first stage. Output of bounding box binary classification (i.e.
+ foreground and background).
+ enc_outputs_coord_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, 4)`, *optional*, returned when `config.with_box_refine=True` and `config.two_stage=True`):
+ Logits of predicted bounding boxes coordinates in the first stage.
+ denoising_meta_values (`dict`):
+ Extra dictionary for the denoising related values
+ """
+
+ loss: torch.FloatTensor | None = None
+ loss_dict: dict | None = None
+ logits: torch.FloatTensor | None = None
+ pred_boxes: torch.FloatTensor | None = None
+ auxiliary_outputs: list[dict] | None = None
+ last_hidden_state: torch.FloatTensor | None = None
+ intermediate_hidden_states: torch.FloatTensor | None = None
+ intermediate_logits: torch.FloatTensor | None = None
+ intermediate_reference_points: torch.FloatTensor | None = None
+ intermediate_predicted_corners: torch.FloatTensor | None = None
+ initial_reference_points: torch.FloatTensor | None = None
+ decoder_hidden_states: tuple[torch.FloatTensor] | None = None
+ decoder_attentions: tuple[torch.FloatTensor] | None = None
+ cross_attentions: tuple[torch.FloatTensor] | None = None
+ encoder_last_hidden_state: torch.FloatTensor | None = None
+ encoder_hidden_states: tuple[torch.FloatTensor] | None = None
+ encoder_attentions: tuple[torch.FloatTensor] | None = None
+ init_reference_points: tuple[torch.FloatTensor] | None = None
+ enc_topk_logits: torch.FloatTensor | None = None
+ enc_topk_bboxes: torch.FloatTensor | None = None
+ enc_outputs_class: torch.FloatTensor | None = None
+ enc_outputs_coord_logits: torch.FloatTensor | None = None
+ denoising_meta_values: dict | None = None
+
+
+class RTDetrMLP(nn.Module):
+ def __init__(self, config: RTDetrConfig, hidden_size: int, intermediate_size: int, activation_function: str):
+ super().__init__()
+ self.fc1 = nn.Linear(hidden_size, intermediate_size)
+ self.fc2 = nn.Linear(intermediate_size, hidden_size)
+ self.activation_fn = ACT2FN[activation_function]
+ self.activation_dropout = config.activation_dropout
+ self.dropout = config.dropout
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
+ hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
+ hidden_states = self.fc2(hidden_states)
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
+ return hidden_states
+
+
+class RTDetrFrozenBatchNorm2d(nn.Module):
+ """
+ BatchNorm2d where the batch statistics and the affine parameters are fixed.
+
+ Copy-paste from torchvision.misc.ops with added eps before rqsrt, without which any other models than
+ torchvision.models.resnet[18,34,50,101] produce nans.
+ """
+
+ def __init__(self, n):
+ super().__init__()
+ self.register_buffer("weight", torch.ones(n))
+ self.register_buffer("bias", torch.zeros(n))
+ self.register_buffer("running_mean", torch.zeros(n))
+ self.register_buffer("running_var", torch.ones(n))
+
+ def _load_from_state_dict(
+ self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs
+ ):
+ num_batches_tracked_key = prefix + "num_batches_tracked"
+ if num_batches_tracked_key in state_dict:
+ del state_dict[num_batches_tracked_key]
+
+ super()._load_from_state_dict(
+ state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs
+ )
+
+ def forward(self, x):
+ # move reshapes to the beginning
+ # to make it user-friendly
+ weight = self.weight.reshape(1, -1, 1, 1)
+ bias = self.bias.reshape(1, -1, 1, 1)
+ running_var = self.running_var.reshape(1, -1, 1, 1)
+ running_mean = self.running_mean.reshape(1, -1, 1, 1)
+ epsilon = 1e-5
+ scale = weight * (running_var + epsilon).rsqrt()
+ bias = bias - running_mean * scale
+ return x * scale + bias
+
+
+def eager_attention_forward(
+ module: nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: torch.Tensor | None,
+ scaling: float | None = None,
+ dropout: float = 0.0,
+ **kwargs: Unpack[TransformersKwargs],
+):
+ if scaling is None:
+ scaling = query.size(-1) ** -0.5
+
+ # Take the dot product between "query" and "key" to get the raw attention scores.
+ attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
+
+ if attention_mask is not None:
+ attn_weights = attn_weights + attention_mask
+
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
+
+ attn_output = torch.matmul(attn_weights, value)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+
+ return attn_output, attn_weights
+
+
+class RTDetrSelfAttention(nn.Module):
+ """
+ Multi-headed self-attention from 'Attention Is All You Need' paper.
+
+ In RT_DETR, position embeddings are added to both queries and keys (but not values) in self-attention.
+ """
+
+ def __init__(
+ self,
+ config: RTDetrConfig,
+ hidden_size: int,
+ num_attention_heads: int,
+ dropout: float = 0.0,
+ bias: bool = True,
+ ):
+ super().__init__()
+ self.config = config
+ self.head_dim = hidden_size // num_attention_heads
+ self.scaling = self.head_dim**-0.5
+ self.attention_dropout = dropout
+ self.is_causal = False
+
+ self.k_proj = nn.Linear(hidden_size, hidden_size, bias=bias)
+ self.v_proj = nn.Linear(hidden_size, hidden_size, bias=bias)
+ self.q_proj = nn.Linear(hidden_size, hidden_size, bias=bias)
+ self.o_proj = nn.Linear(hidden_size, hidden_size, bias=bias)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor | None = None,
+ position_embeddings: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor, torch.Tensor]:
+ """
+ Position embeddings are added to both queries and keys (but not values).
+ """
+ input_shape = hidden_states.shape[:-1]
+ hidden_shape = (*input_shape, -1, self.head_dim)
+
+ query_key_input = hidden_states + position_embeddings if position_embeddings is not None else hidden_states
+
+ query_states = self.q_proj(query_key_input).view(hidden_shape).transpose(1, 2)
+ key_states = self.k_proj(query_key_input).view(hidden_shape).transpose(1, 2)
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_states,
+ key_states,
+ value_states,
+ attention_mask,
+ dropout=0.0 if not self.training else self.attention_dropout,
+ scaling=self.scaling,
+ **kwargs,
+ )
+
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ attn_output = self.o_proj(attn_output)
+ return attn_output, attn_weights
+
+
+def replace_batch_norm(model):
+ r"""
+ Recursively replace all `torch.nn.BatchNorm2d` with `RTDetrFrozenBatchNorm2d`.
+
+ Args:
+ model (torch.nn.Module):
+ input model
+ """
+ for name, module in model.named_children():
+ if isinstance(module, nn.BatchNorm2d):
+ new_module = RTDetrFrozenBatchNorm2d(module.num_features)
+
+ if module.weight.device != torch.device("meta"):
+ new_module.weight.copy_(module.weight)
+ new_module.bias.copy_(module.bias)
+ new_module.running_mean.copy_(module.running_mean)
+ new_module.running_var.copy_(module.running_var)
+
+ model._modules[name] = new_module
+
+ if len(list(module.children())) > 0:
+ replace_batch_norm(module)
+
+
+class RTDetrConvEncoder(nn.Module):
+ """
+ Convolutional backbone using the modeling_rt_detr_resnet.py.
+
+ nn.BatchNorm2d layers are replaced by RTDetrFrozenBatchNorm2d as defined above.
+ https://github.com/lyuwenyu/RT-DETR/blob/main/rtdetr_pytorch/src/nn/backbone/presnet.py#L142
+ """
+
+ def __init__(self, config):
+ super().__init__()
+
+ backbone = load_backbone(config)
+
+ if config.freeze_backbone_batch_norms:
+ # replace batch norm by frozen batch norm
+ with torch.no_grad():
+ replace_batch_norm(backbone)
+ self.model = backbone
+ self.intermediate_channel_sizes = self.model.channels
+
+ def forward(self, pixel_values: torch.Tensor, pixel_mask: torch.Tensor):
+ # send pixel_values through the model to get list of feature maps
+ features = self.model(pixel_values).feature_maps
+
+ out = []
+ for feature_map in features:
+ # downsample pixel_mask to match shape of corresponding feature_map
+ mask = nn.functional.interpolate(pixel_mask[None].float(), size=feature_map.shape[-2:]).to(torch.bool)[0]
+ out.append((feature_map, mask))
+ return out
+
+
+class RTDetrConvNormLayer(nn.Module):
+ def __init__(self, config, in_channels, out_channels, kernel_size, stride, padding=None, activation=None):
+ super().__init__()
+ self.conv = nn.Conv2d(
+ in_channels,
+ out_channels,
+ kernel_size,
+ stride,
+ padding=(kernel_size - 1) // 2 if padding is None else padding,
+ bias=False,
+ )
+ self.norm = nn.BatchNorm2d(out_channels, config.batch_norm_eps)
+ self.activation = nn.Identity() if activation is None else ACT2CLS[activation]()
+
+ def forward(self, hidden_state):
+ hidden_state = self.conv(hidden_state)
+ hidden_state = self.norm(hidden_state)
+ hidden_state = self.activation(hidden_state)
+ return hidden_state
+
+
+class RTDetrEncoderLayer(nn.Module):
+ def __init__(self, config: RTDetrConfig):
+ super().__init__()
+ self.normalize_before = config.normalize_before
+ self.hidden_size = config.encoder_hidden_dim
+
+ # self-attention
+ self.self_attn = RTDetrSelfAttention(
+ config=config,
+ hidden_size=self.hidden_size,
+ num_attention_heads=config.num_attention_heads,
+ dropout=config.dropout,
+ )
+ self.self_attn_layer_norm = nn.LayerNorm(self.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = config.dropout
+ self.mlp = RTDetrMLP(config, self.hidden_size, config.encoder_ffn_dim, config.encoder_activation_function)
+ self.final_layer_norm = nn.LayerNorm(self.hidden_size, eps=config.layer_norm_eps)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor,
+ spatial_position_embeddings: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.Tensor:
+ """
+ Args:
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, hidden_size)`
+ attention_mask (`torch.FloatTensor`): attention mask of size
+ `(batch, 1, target_len, source_len)` where padding elements are indicated by very large negative
+ values.
+ spatial_position_embeddings (`torch.FloatTensor`, *optional*):
+ Spatial position embeddings (2D positional encodings of image locations), to be added to both
+ the queries and keys in self-attention (but not to values).
+ """
+ residual = hidden_states
+ if self.normalize_before:
+ hidden_states = self.self_attn_layer_norm(hidden_states)
+
+ hidden_states, _ = self.self_attn(
+ hidden_states=hidden_states,
+ attention_mask=attention_mask,
+ position_embeddings=spatial_position_embeddings,
+ **kwargs,
+ )
+
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
+ hidden_states = residual + hidden_states
+ if not self.normalize_before:
+ hidden_states = self.self_attn_layer_norm(hidden_states)
+
+ if self.normalize_before:
+ hidden_states = self.final_layer_norm(hidden_states)
+ residual = hidden_states
+
+ hidden_states = self.mlp(hidden_states)
+
+ hidden_states = residual + hidden_states
+ if not self.normalize_before:
+ hidden_states = self.final_layer_norm(hidden_states)
+
+ if self.training:
+ if not torch.isfinite(hidden_states).all():
+ clamp_value = torch.finfo(hidden_states.dtype).max - 1000
+ hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
+
+ return hidden_states
+
+
+class RTDetrRepVggBlock(nn.Module):
+ """
+ RepVGG architecture block introduced by the work "RepVGG: Making VGG-style ConvNets Great Again".
+ """
+
+ def __init__(self, config: RTDetrConfig):
+ super().__init__()
+
+ activation = config.activation_function
+ hidden_channels = int(config.encoder_hidden_dim * config.hidden_expansion)
+ self.conv1 = RTDetrConvNormLayer(config, hidden_channels, hidden_channels, 3, 1, padding=1)
+ self.conv2 = RTDetrConvNormLayer(config, hidden_channels, hidden_channels, 1, 1, padding=0)
+ self.activation = nn.Identity() if activation is None else ACT2CLS[activation]()
+
+ def forward(self, x):
+ y = self.conv1(x) + self.conv2(x)
+ return self.activation(y)
+
+
+class RTDetrCSPRepLayer(nn.Module):
+ """
+ Cross Stage Partial (CSP) network layer with RepVGG blocks.
+ """
+
+ def __init__(self, config: RTDetrConfig):
+ super().__init__()
+
+ in_channels = config.encoder_hidden_dim * 2
+ out_channels = config.encoder_hidden_dim
+ num_blocks = 3
+ activation = config.activation_function
+
+ hidden_channels = int(out_channels * config.hidden_expansion)
+ self.conv1 = RTDetrConvNormLayer(config, in_channels, hidden_channels, 1, 1, activation=activation)
+ self.conv2 = RTDetrConvNormLayer(config, in_channels, hidden_channels, 1, 1, activation=activation)
+ self.bottlenecks = nn.Sequential(*[RTDetrRepVggBlock(config) for _ in range(num_blocks)])
+ if hidden_channels != out_channels:
+ self.conv3 = RTDetrConvNormLayer(config, hidden_channels, out_channels, 1, 1, activation=activation)
+ else:
+ self.conv3 = nn.Identity()
+
+ def forward(self, hidden_state):
+ hidden_state_1 = self.conv1(hidden_state)
+ hidden_state_1 = self.bottlenecks(hidden_state_1)
+ hidden_state_2 = self.conv2(hidden_state)
+ return self.conv3(hidden_state_1 + hidden_state_2)
+
+
+@use_kernel_forward_from_hub("MultiScaleDeformableAttention")
+class MultiScaleDeformableAttention(nn.Module):
+ def forward(
+ self,
+ value: Tensor,
+ value_spatial_shapes: Tensor,
+ value_spatial_shapes_list: list[tuple],
+ level_start_index: Tensor,
+ sampling_locations: Tensor,
+ attention_weights: Tensor,
+ im2col_step: int,
+ ):
+ batch_size, _, num_heads, hidden_dim = value.shape
+ _, num_queries, num_heads, num_levels, num_points, _ = sampling_locations.shape
+ value_list = value.split([height * width for height, width in value_spatial_shapes_list], dim=1)
+ sampling_grids = 2 * sampling_locations - 1
+ sampling_value_list = []
+ for level_id, (height, width) in enumerate(value_spatial_shapes_list):
+ # batch_size, height*width, num_heads, hidden_dim
+ # -> batch_size, height*width, num_heads*hidden_dim
+ # -> batch_size, num_heads*hidden_dim, height*width
+ # -> batch_size*num_heads, hidden_dim, height, width
+ value_l_ = (
+ value_list[level_id]
+ .flatten(2)
+ .transpose(1, 2)
+ .reshape(batch_size * num_heads, hidden_dim, height, width)
+ )
+ # batch_size, num_queries, num_heads, num_points, 2
+ # -> batch_size, num_heads, num_queries, num_points, 2
+ # -> batch_size*num_heads, num_queries, num_points, 2
+ sampling_grid_l_ = sampling_grids[:, :, :, level_id].transpose(1, 2).flatten(0, 1)
+ # batch_size*num_heads, hidden_dim, num_queries, num_points
+ sampling_value_l_ = nn.functional.grid_sample(
+ value_l_,
+ sampling_grid_l_,
+ mode="bilinear",
+ padding_mode="zeros",
+ align_corners=False,
+ )
+ sampling_value_list.append(sampling_value_l_)
+ # (batch_size, num_queries, num_heads, num_levels, num_points)
+ # -> (batch_size, num_heads, num_queries, num_levels, num_points)
+ # -> (batch_size, num_heads, 1, num_queries, num_levels*num_points)
+ attention_weights = attention_weights.transpose(1, 2).reshape(
+ batch_size * num_heads, 1, num_queries, num_levels * num_points
+ )
+ output = (
+ (torch.stack(sampling_value_list, dim=-2).flatten(-2) * attention_weights)
+ .sum(-1)
+ .view(batch_size, num_heads * hidden_dim, num_queries)
+ )
+ return output.transpose(1, 2).contiguous()
+
+
+class RTDetrMultiscaleDeformableAttention(nn.Module):
+ """
+ Multiscale deformable attention as proposed in Deformable DETR.
+ """
+
+ def __init__(self, config: RTDetrConfig, num_heads: int, n_points: int):
+ super().__init__()
+
+ self.attn = MultiScaleDeformableAttention()
+
+ if config.d_model % num_heads != 0:
+ raise ValueError(
+ f"embed_dim (d_model) must be divisible by num_heads, but got {config.d_model} and {num_heads}"
+ )
+ dim_per_head = config.d_model // num_heads
+ # check if dim_per_head is power of 2
+ if not ((dim_per_head & (dim_per_head - 1) == 0) and dim_per_head != 0):
+ warnings.warn(
+ "You'd better set embed_dim (d_model) in RTDetrMultiscaleDeformableAttention to make the"
+ " dimension of each attention head a power of 2 which is more efficient in the authors' CUDA"
+ " implementation."
+ )
+
+ self.im2col_step = 64
+
+ self.d_model = config.d_model
+ self.n_levels = config.num_feature_levels
+ self.n_heads = num_heads
+ self.n_points = n_points
+
+ self.sampling_offsets = nn.Linear(config.d_model, num_heads * self.n_levels * n_points * 2)
+ self.attention_weights = nn.Linear(config.d_model, num_heads * self.n_levels * n_points)
+ self.value_proj = nn.Linear(config.d_model, config.d_model)
+ self.output_proj = nn.Linear(config.d_model, config.d_model)
+
+ self.disable_custom_kernels = config.disable_custom_kernels
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor | None = None,
+ encoder_hidden_states=None,
+ encoder_attention_mask=None,
+ position_embeddings: torch.Tensor | None = None,
+ reference_points=None,
+ spatial_shapes=None,
+ spatial_shapes_list=None,
+ level_start_index=None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor, torch.Tensor]:
+ # add position embeddings to the hidden states before projecting to queries and keys
+ if position_embeddings is not None:
+ hidden_states = hidden_states + position_embeddings
+
+ batch_size, num_queries, _ = hidden_states.shape
+ batch_size, sequence_length, _ = encoder_hidden_states.shape
+ total_elements = sum(height * width for height, width in spatial_shapes_list)
+ torch_compilable_check(
+ total_elements == sequence_length,
+ "Make sure to align the spatial shapes with the sequence length of the encoder hidden states",
+ )
+
+ value = self.value_proj(encoder_hidden_states)
+ if attention_mask is not None:
+ # we invert the attention_mask
+ value = value.masked_fill(~attention_mask[..., None], float(0))
+ value = value.view(batch_size, sequence_length, self.n_heads, self.d_model // self.n_heads)
+ sampling_offsets = self.sampling_offsets(hidden_states).view(
+ batch_size, num_queries, self.n_heads, self.n_levels, self.n_points, 2
+ )
+ attention_weights = self.attention_weights(hidden_states).view(
+ batch_size, num_queries, self.n_heads, self.n_levels * self.n_points
+ )
+ attention_weights = F.softmax(attention_weights, -1).view(
+ batch_size, num_queries, self.n_heads, self.n_levels, self.n_points
+ )
+ # batch_size, num_queries, n_heads, n_levels, n_points, 2
+ num_coordinates = reference_points.shape[-1]
+ if num_coordinates == 2:
+ offset_normalizer = torch.stack([spatial_shapes[..., 1], spatial_shapes[..., 0]], -1)
+ sampling_locations = (
+ reference_points[:, :, None, :, None, :]
+ + sampling_offsets / offset_normalizer[None, None, None, :, None, :]
+ )
+ elif num_coordinates == 4:
+ sampling_locations = (
+ reference_points[:, :, None, :, None, :2]
+ + sampling_offsets / self.n_points * reference_points[:, :, None, :, None, 2:] * 0.5
+ )
+ else:
+ raise ValueError(f"Last dim of reference_points must be 2 or 4, but got {reference_points.shape[-1]}")
+
+ output = self.attn(
+ value,
+ spatial_shapes,
+ spatial_shapes_list,
+ level_start_index,
+ sampling_locations,
+ attention_weights,
+ self.im2col_step,
+ )
+
+ output = self.output_proj(output)
+
+ return output, attention_weights
+
+
+class RTDetrDecoderLayer(nn.Module):
+ def __init__(self, config: RTDetrConfig):
+ super().__init__()
+ self.hidden_size = config.d_model
+
+ # self-attention
+ self.self_attn = RTDetrSelfAttention(
+ config=config,
+ hidden_size=self.hidden_size,
+ num_attention_heads=config.decoder_attention_heads,
+ dropout=config.attention_dropout,
+ )
+ self.dropout = config.dropout
+
+ self.self_attn_layer_norm = nn.LayerNorm(self.hidden_size, eps=config.layer_norm_eps)
+ # cross-attention
+ self.encoder_attn = RTDetrMultiscaleDeformableAttention(
+ config,
+ num_heads=config.decoder_attention_heads,
+ n_points=config.decoder_n_points,
+ )
+ self.encoder_attn_layer_norm = nn.LayerNorm(self.hidden_size, eps=config.layer_norm_eps)
+ # feedforward neural networks
+ self.mlp = RTDetrMLP(config, self.hidden_size, config.decoder_ffn_dim, config.decoder_activation_function)
+ self.final_layer_norm = nn.LayerNorm(self.hidden_size, eps=config.layer_norm_eps)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ object_queries_position_embeddings: torch.Tensor | None = None,
+ reference_points=None,
+ spatial_shapes=None,
+ spatial_shapes_list=None,
+ level_start_index=None,
+ encoder_hidden_states: torch.Tensor | None = None,
+ encoder_attention_mask: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.Tensor:
+ """
+ Args:
+ hidden_states (`torch.FloatTensor`):
+ Input to the layer of shape `(batch, seq_len, hidden_size)`.
+ object_queries_position_embeddings (`torch.FloatTensor`, *optional*):
+ Position embeddings for the object query slots. These are added to both queries and keys
+ in the self-attention layer (not values).
+ reference_points (`torch.FloatTensor`, *optional*):
+ Reference points.
+ spatial_shapes (`torch.LongTensor`, *optional*):
+ Spatial shapes.
+ level_start_index (`torch.LongTensor`, *optional*):
+ Level start index.
+ encoder_hidden_states (`torch.FloatTensor`):
+ cross attention input to the layer of shape `(batch, seq_len, hidden_size)`
+ encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size
+ `(batch, 1, target_len, source_len)` where padding elements are indicated by very large negative
+ values.
+ """
+ residual = hidden_states
+
+ # Self Attention
+ hidden_states, _ = self.self_attn(
+ hidden_states=hidden_states,
+ attention_mask=encoder_attention_mask,
+ position_embeddings=object_queries_position_embeddings,
+ **kwargs,
+ )
+
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
+ hidden_states = residual + hidden_states
+ hidden_states = self.self_attn_layer_norm(hidden_states)
+
+ residual = hidden_states
+
+ # Cross-Attention
+ hidden_states, _ = self.encoder_attn(
+ hidden_states=hidden_states,
+ encoder_hidden_states=encoder_hidden_states,
+ position_embeddings=object_queries_position_embeddings,
+ reference_points=reference_points,
+ spatial_shapes=spatial_shapes,
+ spatial_shapes_list=spatial_shapes_list,
+ level_start_index=level_start_index,
+ **kwargs,
+ )
+
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
+ hidden_states = residual + hidden_states
+
+ hidden_states = self.encoder_attn_layer_norm(hidden_states)
+
+ # Fully Connected
+ residual = hidden_states
+ hidden_states = self.mlp(hidden_states)
+ hidden_states = residual + hidden_states
+ hidden_states = self.final_layer_norm(hidden_states)
+
+ return hidden_states
+
+
+def build_2d_sinusoidal_position_embedding(
+ height: int,
+ width: int,
+ embed_dim: int = 256,
+ temperature: float = 10000.0,
+ cls_token: bool = False,
+ device: torch.device | None = None,
+ dtype: torch.dtype = torch.float32,
+) -> torch.Tensor:
+ """2D sinusoidal position embeddings for an image patch grid.
+
+ Each (h, w) position gets an ``embed_dim``-dimensional vector laid out as
+ ``[sin_h | cos_h | sin_w | cos_w]``, with row-major (H-outer) patch ordering.
+
+ Args:
+ height: Grid height in patches.
+ width: Grid width in patches.
+ embed_dim: Total embedding dimension; must be divisible by 4.
+ temperature: Base for the frequency decay.
+ cls_token: If `True`, prepend a zero row for a CLS token.
+ device: Target device; defaults to CPU.
+ dtype: Output dtype; frequency arithmetic uses float64 internally.
+
+ Returns:
+ Tensor of shape ``(height * width [+1], embed_dim)``.
+ """
+ if embed_dim % 4 != 0:
+ raise ValueError(f"`embed_dim` must be divisible by 4, got {embed_dim}")
+
+ pos_dim = embed_dim // 4
+ omega = torch.arange(pos_dim, dtype=torch.float64, device=device) / pos_dim
+ omega = 1.0 / temperature**omega # (D/4,)
+
+ grid_h = torch.arange(height, dtype=torch.float64, device=device)
+ grid_w = torch.arange(width, dtype=torch.float64, device=device)
+ grid_h, grid_w = torch.meshgrid(grid_h, grid_w, indexing="ij") # (H, W) each
+
+ emb_h = grid_h.flatten().outer(omega) # (H*W, D/4)
+ emb_w = grid_w.flatten().outer(omega) # (H*W, D/4)
+
+ pos_embed = torch.cat([emb_h.sin(), emb_h.cos(), emb_w.sin(), emb_w.cos()], dim=1)
+
+ if cls_token:
+ pos_embed = torch.cat([torch.zeros(1, embed_dim, dtype=torch.float64, device=device), pos_embed], dim=0)
+
+ return pos_embed.to(dtype)
+
+
+class RTDetrSinePositionEmbedding(nn.Module):
+ """
+ 2D sinusoidal position embedding used in RT-DETR hybrid encoder.
+ """
+
+ def __init__(self, embed_dim: int = 256, temperature: int = 10000):
+ super().__init__()
+ self.embed_dim = embed_dim
+ self.temperature = temperature
+
+ @staticmethod
+ @compile_compatible_method_lru_cache(maxsize=32)
+ def _cached_build_2d_sinusoidal_position_embedding(*args, **kwargs) -> torch.Tensor:
+ return build_2d_sinusoidal_position_embedding(*args, **kwargs)
+
+ def forward(
+ self,
+ width: int,
+ height: int,
+ device: torch.device | str,
+ dtype: torch.dtype,
+ ) -> torch.Tensor:
+ """
+ Generate 2D sinusoidal position embeddings.
+
+ Returns:
+ Position embeddings of shape (1, height*width, embed_dim)
+ """
+ return self._cached_build_2d_sinusoidal_position_embedding(
+ height=torch_int(height),
+ width=torch_int(width),
+ embed_dim=self.embed_dim,
+ temperature=self.temperature,
+ device=device,
+ dtype=dtype,
+ ).unsqueeze(0)
+
+
+class RTDetrAIFILayer(nn.Module):
+ """
+ AIFI (Attention-based Intra-scale Feature Interaction) layer used in RT-DETR hybrid encoder.
+ """
+
+ def __init__(self, config: RTDetrConfig):
+ super().__init__()
+ self.config = config
+ self.encoder_hidden_dim = config.encoder_hidden_dim
+ self.eval_size = config.eval_size
+
+ self.position_embedding = RTDetrSinePositionEmbedding(
+ embed_dim=self.encoder_hidden_dim,
+ temperature=config.positional_encoding_temperature,
+ )
+ self.layers = nn.ModuleList([RTDetrEncoderLayer(config) for _ in range(config.encoder_layers)])
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.Tensor:
+ """
+ Args:
+ hidden_states (`torch.FloatTensor` of shape `(batch_size, channels, height, width)`):
+ Feature map to process.
+ """
+ batch_size = hidden_states.shape[0]
+ height, width = hidden_states.shape[2:]
+
+ hidden_states = hidden_states.flatten(2).transpose(1, 2)
+
+ if self.training or self.eval_size is None:
+ pos_embed = self.position_embedding(
+ width=width,
+ height=height,
+ device=hidden_states.device,
+ dtype=hidden_states.dtype,
+ )
+ else:
+ pos_embed = None
+
+ for layer in self.layers:
+ hidden_states = layer(
+ hidden_states,
+ attention_mask=None,
+ spatial_position_embeddings=pos_embed,
+ **kwargs,
+ )
+
+ hidden_states = (
+ hidden_states.transpose(1, 2).reshape(batch_size, self.encoder_hidden_dim, height, width).contiguous()
+ )
+
+ return hidden_states
+
+
+class RTDetrMLPPredictionHead(nn.Module):
+ """
+ Very simple multi-layer perceptron (MLP, also called FFN), used to predict the normalized center coordinates,
+ height and width of a bounding box w.r.t. an image.
+
+ """
+
+ def __init__(self, input_dim, hidden_dim, output_dim, num_layers):
+ super().__init__()
+ self.num_layers = num_layers
+ h = [hidden_dim] * (num_layers - 1)
+ self.layers = nn.ModuleList(nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim]))
+
+ def forward(self, x):
+ for i, layer in enumerate(self.layers):
+ x = nn.functional.relu(layer(x)) if i < self.num_layers - 1 else layer(x)
+ return x
+
+
+@auto_docstring
+class RTDetrPreTrainedModel(PreTrainedModel):
+ config: RTDetrConfig
+ base_model_prefix = "rt_detr"
+ main_input_name = "pixel_values"
+ input_modalities = ("image",)
+ _no_split_modules = [r"RTDetrHybridEncoder", r"RTDetrDecoderLayer"]
+ _supports_sdpa = True
+ _supports_flash_attn = True
+ _supports_attention_backend = True
+ _supports_flex_attn = True
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ """Initialize the weights"""
+ if isinstance(module, RTDetrForObjectDetection):
+ if module.model.decoder.class_embed is not None:
+ for layer in module.model.decoder.class_embed:
+ prior_prob = self.config.initializer_bias_prior_prob or 1 / (self.config.num_labels + 1)
+ bias = float(-math.log((1 - prior_prob) / prior_prob))
+ init.xavier_uniform_(layer.weight)
+ init.constant_(layer.bias, bias)
+
+ if module.model.decoder.bbox_embed is not None:
+ for layer in module.model.decoder.bbox_embed:
+ init.constant_(layer.layers[-1].weight, 0)
+ init.constant_(layer.layers[-1].bias, 0)
+
+ elif isinstance(module, RTDetrMultiscaleDeformableAttention):
+ init.constant_(module.sampling_offsets.weight, 0.0)
+ default_dtype = torch.get_default_dtype()
+ thetas = torch.arange(module.n_heads, dtype=torch.int64).to(default_dtype) * (
+ 2.0 * math.pi / module.n_heads
+ )
+ grid_init = torch.stack([thetas.cos(), thetas.sin()], -1)
+ grid_init = (
+ (grid_init / grid_init.abs().max(-1, keepdim=True)[0])
+ .view(module.n_heads, 1, 1, 2)
+ .repeat(1, module.n_levels, module.n_points, 1)
+ )
+ for i in range(module.n_points):
+ grid_init[:, :, i, :] *= i + 1
+
+ init.copy_(module.sampling_offsets.bias, grid_init.view(-1))
+ init.constant_(module.attention_weights.weight, 0.0)
+ init.constant_(module.attention_weights.bias, 0.0)
+ init.xavier_uniform_(module.value_proj.weight)
+ init.constant_(module.value_proj.bias, 0.0)
+ init.xavier_uniform_(module.output_proj.weight)
+ init.constant_(module.output_proj.bias, 0.0)
+
+ elif isinstance(module, RTDetrModel):
+ prior_prob = self.config.initializer_bias_prior_prob or 1 / (self.config.num_labels + 1)
+ bias = float(-math.log((1 - prior_prob) / prior_prob))
+ init.xavier_uniform_(module.enc_score_head.weight)
+ init.constant_(module.enc_score_head.bias, bias)
+
+ elif isinstance(module, (nn.Linear, nn.Conv2d, nn.BatchNorm2d)):
+ init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
+ if module.bias is not None:
+ init.zeros_(module.bias)
+ if getattr(module, "running_mean", None) is not None:
+ init.zeros_(module.running_mean)
+ init.ones_(module.running_var)
+ init.zeros_(module.num_batches_tracked)
+
+ elif isinstance(module, nn.LayerNorm):
+ init.ones_(module.weight)
+ init.zeros_(module.bias)
+
+ if hasattr(module, "weight_embedding") and self.config.learn_initial_query:
+ init.xavier_uniform_(module.weight_embedding.weight)
+ if hasattr(module, "denoising_class_embed") and self.config.num_denoising > 0:
+ init.xavier_uniform_(module.denoising_class_embed.weight)
+
+
+class RTDetrHybridEncoder(RTDetrPreTrainedModel):
+ """
+ Hybrid encoder consisting of AIFI (Attention-based Intra-scale Feature Interaction) layers,
+ a top-down Feature Pyramid Network (FPN) and a bottom-up Path Aggregation Network (PAN).
+ More details on the paper: https://huggingface.co/papers/2304.08069
+
+ Args:
+ config: RTDetrConfig
+ """
+
+ _can_record_outputs = {
+ "hidden_states": RTDetrAIFILayer,
+ "attentions": RTDetrSelfAttention,
+ }
+
+ def __init__(self, config: RTDetrConfig):
+ super().__init__(config)
+ self.config = config
+ self.in_channels = config.encoder_in_channels
+ self.feat_strides = config.feat_strides
+ self.encoder_hidden_dim = config.encoder_hidden_dim
+ self.encode_proj_layers = config.encode_proj_layers
+ self.positional_encoding_temperature = config.positional_encoding_temperature
+ self.eval_size = config.eval_size
+ self.out_channels = [self.encoder_hidden_dim for _ in self.in_channels]
+ self.out_strides = self.feat_strides
+ self.num_fpn_stages = len(self.in_channels) - 1
+ self.num_pan_stages = len(self.in_channels) - 1
+
+ # AIFI (Attention-based Intra-scale Feature Interaction) layers
+ self.aifi = nn.ModuleList([RTDetrAIFILayer(config) for _ in range(len(self.encode_proj_layers))])
+
+ # top-down FPN
+ self.lateral_convs = nn.ModuleList()
+ self.fpn_blocks = nn.ModuleList()
+ for _ in range(self.num_fpn_stages):
+ lateral_conv = RTDetrConvNormLayer(
+ config,
+ in_channels=self.encoder_hidden_dim,
+ out_channels=self.encoder_hidden_dim,
+ kernel_size=1,
+ stride=1,
+ activation=config.activation_function,
+ )
+ fpn_block = RTDetrCSPRepLayer(config)
+ self.lateral_convs.append(lateral_conv)
+ self.fpn_blocks.append(fpn_block)
+
+ # bottom-up PAN
+ self.downsample_convs = nn.ModuleList()
+ self.pan_blocks = nn.ModuleList()
+ for _ in range(self.num_pan_stages):
+ downsample_conv = RTDetrConvNormLayer(
+ config,
+ in_channels=self.encoder_hidden_dim,
+ out_channels=self.encoder_hidden_dim,
+ kernel_size=3,
+ stride=2,
+ activation=config.activation_function,
+ )
+ pan_block = RTDetrCSPRepLayer(config)
+ self.downsample_convs.append(downsample_conv)
+ self.pan_blocks.append(pan_block)
+
+ self.post_init()
+
+ @merge_with_config_defaults
+ @capture_outputs(tie_last_hidden_states=False)
+ def forward(
+ self,
+ inputs_embeds=None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> BaseModelOutput:
+ r"""
+ Args:
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
+ Flattened feature map (output of the backbone + projection layer) that is passed to the encoder.
+ """
+ feature_maps = inputs_embeds
+
+ # AIFI: Apply transformer encoder to specified feature levels
+ if self.config.encoder_layers > 0:
+ for i, enc_ind in enumerate(self.encode_proj_layers):
+ feature_maps[enc_ind] = self.aifi[i](feature_maps[enc_ind], **kwargs)
+
+ # top-down FPN
+ fpn_feature_maps = [feature_maps[-1]]
+ for idx, (lateral_conv, fpn_block) in enumerate(zip(self.lateral_convs, self.fpn_blocks)):
+ backbone_feature_map = feature_maps[self.num_fpn_stages - idx - 1]
+ top_fpn_feature_map = fpn_feature_maps[-1]
+ # apply lateral block
+ top_fpn_feature_map = lateral_conv(top_fpn_feature_map)
+ fpn_feature_maps[-1] = top_fpn_feature_map
+ # apply fpn block
+ top_fpn_feature_map = F.interpolate(top_fpn_feature_map, scale_factor=2.0, mode="nearest")
+ fused_feature_map = torch.concat([top_fpn_feature_map, backbone_feature_map], dim=1)
+ new_fpn_feature_map = fpn_block(fused_feature_map)
+ fpn_feature_maps.append(new_fpn_feature_map)
+
+ fpn_feature_maps.reverse()
+
+ # bottom-up PAN
+ pan_feature_maps = [fpn_feature_maps[0]]
+ for idx, (downsample_conv, pan_block) in enumerate(zip(self.downsample_convs, self.pan_blocks)):
+ top_pan_feature_map = pan_feature_maps[-1]
+ fpn_feature_map = fpn_feature_maps[idx + 1]
+ downsampled_feature_map = downsample_conv(top_pan_feature_map)
+ fused_feature_map = torch.concat([downsampled_feature_map, fpn_feature_map], dim=1)
+ new_pan_feature_map = pan_block(fused_feature_map)
+ pan_feature_maps.append(new_pan_feature_map)
+
+ return BaseModelOutput(last_hidden_state=pan_feature_maps)
+
+
+def inverse_sigmoid(x, eps=1e-5):
+ x = x.clamp(min=0, max=1)
+ x1 = x.clamp(min=eps)
+ x2 = (1 - x).clamp(min=eps)
+ return torch.log(x1 / x2)
+
+
+class RTDetrDecoder(RTDetrPreTrainedModel):
+ _can_record_outputs = {
+ "hidden_states": RTDetrDecoderLayer,
+ "attentions": RTDetrSelfAttention,
+ "cross_attentions": RTDetrMultiscaleDeformableAttention,
+ }
+
+ def __init__(self, config: RTDetrConfig):
+ super().__init__(config)
+
+ self.dropout = config.dropout
+ self.layers = nn.ModuleList([RTDetrDecoderLayer(config) for _ in range(config.decoder_layers)])
+ self.query_pos_head = RTDetrMLPPredictionHead(4, 2 * config.d_model, config.d_model, num_layers=2)
+
+ # hack implementation for iterative bounding box refinement and two-stage Deformable DETR
+ self.bbox_embed = None
+ self.class_embed = None
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @merge_with_config_defaults
+ @capture_outputs
+ def forward(
+ self,
+ inputs_embeds=None,
+ encoder_hidden_states=None,
+ encoder_attention_mask=None,
+ reference_points=None,
+ spatial_shapes=None,
+ spatial_shapes_list=None,
+ level_start_index=None,
+ **kwargs: Unpack[TransformersKwargs],
+ ):
+ r"""
+ Args:
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_size)`):
+ The query embeddings that are passed into the decoder.
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
+ of the decoder.
+ encoder_attention_mask (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Mask to avoid performing cross-attention on padding pixel_values of the encoder. Mask values selected
+ in `[0, 1]`:
+ - 1 for pixels that are real (i.e. **not masked**),
+ - 0 for pixels that are padding (i.e. **masked**).
+ reference_points (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)` is `as_two_stage` else `(batch_size, num_queries, 2)` or , *optional*):
+ Reference point in range `[0, 1]`, top-left (0,0), bottom-right (1, 1), including padding area.
+ spatial_shapes (`torch.FloatTensor` of shape `(num_feature_levels, 2)`):
+ Spatial shapes of the feature maps.
+ level_start_index (`torch.LongTensor` of shape `(num_feature_levels)`, *optional*):
+ Indexes for the start of each feature level. In range `[0, sequence_length]`.
+ """
+ if inputs_embeds is not None:
+ hidden_states = inputs_embeds
+
+ # decoder layers
+ intermediate = ()
+ intermediate_reference_points = ()
+ intermediate_logits = ()
+
+ reference_points = F.sigmoid(reference_points)
+
+ # https://github.com/lyuwenyu/RT-DETR/blob/94f5e16708329d2f2716426868ec89aa774af016/rtdetr_pytorch/src/zoo/rtdetr/rtdetr_decoder.py#L252
+ for idx, decoder_layer in enumerate(self.layers):
+ reference_points_input = reference_points.unsqueeze(2)
+ object_queries_position_embeddings = self.query_pos_head(reference_points)
+
+ hidden_states = decoder_layer(
+ hidden_states,
+ object_queries_position_embeddings=object_queries_position_embeddings,
+ encoder_hidden_states=encoder_hidden_states,
+ reference_points=reference_points_input,
+ spatial_shapes=spatial_shapes,
+ spatial_shapes_list=spatial_shapes_list,
+ level_start_index=level_start_index,
+ encoder_attention_mask=encoder_attention_mask,
+ **kwargs,
+ )
+
+ # hack implementation for iterative bounding box refinement
+ if self.bbox_embed is not None:
+ predicted_corners = self.bbox_embed[idx](hidden_states)
+ new_reference_points = F.sigmoid(predicted_corners + inverse_sigmoid(reference_points))
+ reference_points = new_reference_points.detach()
+
+ intermediate += (hidden_states,)
+ intermediate_reference_points += (
+ (new_reference_points,) if self.bbox_embed is not None else (reference_points,)
+ )
+
+ if self.class_embed is not None:
+ logits = self.class_embed[idx](hidden_states)
+ intermediate_logits += (logits,)
+
+ # Keep batch_size as first dimension
+ intermediate = torch.stack(intermediate, dim=1)
+ intermediate_reference_points = torch.stack(intermediate_reference_points, dim=1)
+ if self.class_embed is not None:
+ intermediate_logits = torch.stack(intermediate_logits, dim=1)
+
+ return RTDetrDecoderOutput(
+ last_hidden_state=hidden_states,
+ intermediate_hidden_states=intermediate,
+ intermediate_logits=intermediate_logits,
+ intermediate_reference_points=intermediate_reference_points,
+ )
+
+
+def get_contrastive_denoising_training_group(
+ targets,
+ num_classes,
+ num_queries,
+ class_embed,
+ num_denoising_queries=100,
+ label_noise_ratio=0.5,
+ box_noise_scale=1.0,
+):
+ """
+ Creates a contrastive denoising training group using ground-truth samples. It adds noise to labels and boxes.
+
+ Args:
+ targets (`list[dict]`):
+ The target objects, each containing 'class_labels' and 'boxes' for objects in an image.
+ num_classes (`int`):
+ Total number of classes in the dataset.
+ num_queries (`int`):
+ Number of query slots in the transformer.
+ class_embed (`callable`):
+ A function or a model layer to embed class labels.
+ num_denoising_queries (`int`, *optional*, defaults to 100):
+ Number of denoising queries.
+ label_noise_ratio (`float`, *optional*, defaults to 0.5):
+ Ratio of noise applied to labels.
+ box_noise_scale (`float`, *optional*, defaults to 1.0):
+ Scale of noise applied to bounding boxes.
+ Returns:
+ `tuple` comprising various elements:
+ - **input_query_class** (`torch.FloatTensor`) --
+ Class queries with applied label noise.
+ - **input_query_bbox** (`torch.FloatTensor`) --
+ Bounding box queries with applied box noise.
+ - **attn_mask** (`torch.FloatTensor`) --
+ Attention mask for separating denoising and reconstruction queries.
+ - **denoising_meta_values** (`dict`) --
+ Metadata including denoising positive indices, number of groups, and split sizes.
+ """
+
+ if num_denoising_queries <= 0:
+ return None, None, None, None
+
+ num_ground_truths = [len(t["class_labels"]) for t in targets]
+ device = targets[0]["class_labels"].device
+
+ max_gt_num = max(num_ground_truths)
+ if max_gt_num == 0:
+ return None, None, None, None
+
+ num_groups_denoising_queries = num_denoising_queries // max_gt_num
+ num_groups_denoising_queries = 1 if num_groups_denoising_queries == 0 else num_groups_denoising_queries
+ # pad gt to max_num of a batch
+ batch_size = len(num_ground_truths)
+
+ input_query_class = torch.full([batch_size, max_gt_num], num_classes, dtype=torch.int32, device=device)
+ input_query_bbox = torch.zeros([batch_size, max_gt_num, 4], device=device)
+ pad_gt_mask = torch.zeros([batch_size, max_gt_num], dtype=torch.bool, device=device)
+
+ for i in range(batch_size):
+ num_gt = num_ground_truths[i]
+ if num_gt > 0:
+ input_query_class[i, :num_gt] = targets[i]["class_labels"]
+ input_query_bbox[i, :num_gt] = targets[i]["boxes"]
+ pad_gt_mask[i, :num_gt] = 1
+ # each group has positive and negative queries.
+ input_query_class = input_query_class.tile([1, 2 * num_groups_denoising_queries])
+ input_query_bbox = input_query_bbox.tile([1, 2 * num_groups_denoising_queries, 1])
+ pad_gt_mask = pad_gt_mask.tile([1, 2 * num_groups_denoising_queries])
+ # positive and negative mask
+ negative_gt_mask = torch.zeros([batch_size, max_gt_num * 2, 1], device=device)
+ negative_gt_mask[:, max_gt_num:] = 1
+ negative_gt_mask = negative_gt_mask.tile([1, num_groups_denoising_queries, 1])
+ positive_gt_mask = 1 - negative_gt_mask
+ # contrastive denoising training positive index
+ positive_gt_mask = positive_gt_mask.squeeze(-1) * pad_gt_mask
+ denoise_positive_idx = torch.nonzero(positive_gt_mask)[:, 1]
+ denoise_positive_idx = torch.split(
+ denoise_positive_idx, [n * num_groups_denoising_queries for n in num_ground_truths]
+ )
+ # total denoising queries
+ num_denoising_queries = torch_int(max_gt_num * 2 * num_groups_denoising_queries)
+
+ if label_noise_ratio > 0:
+ mask = torch.rand_like(input_query_class, dtype=torch.float) < (label_noise_ratio * 0.5)
+ # randomly put a new one here
+ new_label = torch.randint_like(mask, 0, num_classes, dtype=input_query_class.dtype)
+ input_query_class = torch.where(mask & pad_gt_mask, new_label, input_query_class)
+
+ if box_noise_scale > 0:
+ known_bbox = center_to_corners_format(input_query_bbox)
+ diff = torch.tile(input_query_bbox[..., 2:] * 0.5, [1, 1, 2]) * box_noise_scale
+ rand_sign = torch.randint_like(input_query_bbox, 0, 2) * 2.0 - 1.0
+ rand_part = torch.rand_like(input_query_bbox)
+ rand_part = (rand_part + 1.0) * negative_gt_mask + rand_part * (1 - negative_gt_mask)
+ rand_part *= rand_sign
+ known_bbox += rand_part * diff
+ known_bbox.clip_(min=0.0, max=1.0)
+ input_query_bbox = corners_to_center_format(known_bbox)
+ input_query_bbox = inverse_sigmoid(input_query_bbox)
+
+ input_query_class = class_embed(input_query_class)
+
+ target_size = num_denoising_queries + num_queries
+ attn_mask = torch.full([target_size, target_size], 0, dtype=torch.float, device=device)
+ # match query cannot see the reconstruction
+ attn_mask[num_denoising_queries:, :num_denoising_queries] = -torch.inf
+
+ # reconstructions cannot see each other
+ for i in range(num_groups_denoising_queries):
+ idx_block_start = max_gt_num * 2 * i
+ idx_block_end = max_gt_num * 2 * (i + 1)
+ attn_mask[idx_block_start:idx_block_end, :idx_block_start] = -torch.inf
+ attn_mask[idx_block_start:idx_block_end, idx_block_end:num_denoising_queries] = -torch.inf
+
+ denoising_meta_values = {
+ "dn_positive_idx": denoise_positive_idx,
+ "dn_num_group": num_groups_denoising_queries,
+ "dn_num_split": [num_denoising_queries, num_queries],
+ }
+
+ return input_query_class, input_query_bbox, attn_mask, denoising_meta_values
+
+
+@auto_docstring(
+ custom_intro="""
+ RT-DETR Model (consisting of a backbone and encoder-decoder) outputting raw hidden states without any head on top.
+ """
+)
+class RTDetrModel(RTDetrPreTrainedModel):
+ def __init__(self, config: RTDetrConfig):
+ super().__init__(config)
+
+ # Create backbone
+ self.backbone = RTDetrConvEncoder(config)
+ intermediate_channel_sizes = self.backbone.intermediate_channel_sizes
+
+ # Create encoder input projection layers
+ # https://github.com/lyuwenyu/RT-DETR/blob/94f5e16708329d2f2716426868ec89aa774af016/rtdetr_pytorch/src/zoo/rtdetr/hybrid_encoder.py#L212
+ num_backbone_outs = len(intermediate_channel_sizes)
+ encoder_input_proj_list = []
+ for i in range(num_backbone_outs):
+ in_channels = intermediate_channel_sizes[i]
+ encoder_input_proj_list.append(
+ nn.Sequential(
+ nn.Conv2d(in_channels, config.encoder_hidden_dim, kernel_size=1, bias=False),
+ nn.BatchNorm2d(config.encoder_hidden_dim),
+ )
+ )
+ self.encoder_input_proj = nn.ModuleList(encoder_input_proj_list)
+
+ # Create encoder
+ self.encoder = RTDetrHybridEncoder(config)
+
+ # denoising part
+ if config.num_denoising > 0:
+ self.denoising_class_embed = nn.Embedding(
+ config.num_labels + 1, config.d_model, padding_idx=config.num_labels
+ )
+
+ # decoder embedding
+ if config.learn_initial_query:
+ self.weight_embedding = nn.Embedding(config.num_queries, config.d_model)
+
+ # encoder head
+ self.enc_output = nn.Sequential(
+ nn.Linear(config.d_model, config.d_model),
+ nn.LayerNorm(config.d_model, eps=config.layer_norm_eps),
+ )
+ self.enc_score_head = nn.Linear(config.d_model, config.num_labels)
+ self.enc_bbox_head = RTDetrMLPPredictionHead(config.d_model, config.d_model, 4, num_layers=3)
+
+ # init encoder output anchors and valid_mask
+ if config.anchor_image_size:
+ self.anchors, self.valid_mask = self.generate_anchors(dtype=self.dtype)
+
+ # Create decoder input projection layers
+ # https://github.com/lyuwenyu/RT-DETR/blob/94f5e16708329d2f2716426868ec89aa774af016/rtdetr_pytorch/src/zoo/rtdetr/rtdetr_decoder.py#L412
+ num_backbone_outs = len(config.decoder_in_channels)
+ decoder_input_proj_list = []
+ for i in range(num_backbone_outs):
+ in_channels = config.decoder_in_channels[i]
+ decoder_input_proj_list.append(
+ nn.Sequential(
+ nn.Conv2d(in_channels, config.d_model, kernel_size=1, bias=False),
+ nn.BatchNorm2d(config.d_model, config.batch_norm_eps),
+ )
+ )
+ for _ in range(config.num_feature_levels - num_backbone_outs):
+ decoder_input_proj_list.append(
+ nn.Sequential(
+ nn.Conv2d(in_channels, config.d_model, kernel_size=3, stride=2, padding=1, bias=False),
+ nn.BatchNorm2d(config.d_model, config.batch_norm_eps),
+ )
+ )
+ in_channels = config.d_model
+ self.decoder_input_proj = nn.ModuleList(decoder_input_proj_list)
+
+ # decoder
+ self.decoder = RTDetrDecoder(config)
+
+ self.post_init()
+
+ def freeze_backbone(self):
+ for param in self.backbone.parameters():
+ param.requires_grad_(False)
+
+ def unfreeze_backbone(self):
+ for param in self.backbone.parameters():
+ param.requires_grad_(True)
+
+ @staticmethod
+ @compile_compatible_method_lru_cache(maxsize=32)
+ def _cached_generate_anchors(
+ spatial_shapes: tuple[tuple[int, int], ...],
+ grid_size: float,
+ device: torch.device | str = "cpu",
+ dtype: torch.dtype = torch.float32,
+ ) -> tuple[torch.Tensor, torch.Tensor]:
+ anchors = []
+ for level, (height, width) in enumerate(spatial_shapes):
+ grid_y, grid_x = torch.meshgrid(
+ torch.arange(end=height, device=device).to(dtype),
+ torch.arange(end=width, device=device).to(dtype),
+ indexing="ij",
+ )
+ grid_xy = torch.stack([grid_x, grid_y], -1)
+ grid_xy = grid_xy.unsqueeze(0) + 0.5
+ grid_xy[..., 0] /= width
+ grid_xy[..., 1] /= height
+ wh = torch.ones_like(grid_xy) * grid_size * (2.0**level)
+ anchors.append(torch.concat([grid_xy, wh], -1).reshape(-1, height * width, 4))
+ # define the valid range for anchor coordinates
+ eps = 1e-2
+ anchors = torch.concat(anchors, 1)
+ valid_mask = ((anchors > eps) * (anchors < 1 - eps)).all(-1, keepdim=True)
+ anchors = torch.log(anchors / (1 - anchors))
+ anchors = torch.where(valid_mask, anchors, torch.tensor(torch.finfo(dtype).max, dtype=dtype, device=device))
+
+ return anchors, valid_mask
+
+ def generate_anchors(self, spatial_shapes=None, grid_size=0.05, device="cpu", dtype=torch.float32):
+ if spatial_shapes is None:
+ spatial_shapes = (
+ (int(self.config.anchor_image_size[0] / s), int(self.config.anchor_image_size[1] / s))
+ for s in self.config.feat_strides
+ )
+ return self._cached_generate_anchors(spatial_shapes, grid_size, device, dtype)
+
+ @auto_docstring
+ @can_return_tuple
+ def forward(
+ self,
+ pixel_values: torch.FloatTensor,
+ pixel_mask: torch.LongTensor | None = None,
+ encoder_outputs: torch.FloatTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: list[dict] | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.FloatTensor] | RTDetrModelOutput:
+ r"""
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
+ Optionally, instead of passing the flattened feature map (output of the backbone + projection layer), you
+ can choose to directly pass a flattened representation of an image.
+ labels (`list[Dict]` of len `(batch_size,)`, *optional*):
+ Labels for computing the bipartite matching loss. List of dicts, each dictionary containing at least the
+ following 2 keys: 'class_labels' and 'boxes' (the class labels and bounding boxes of an image in the batch
+ respectively). The class labels themselves should be a `torch.LongTensor` of len `(number of bounding boxes
+ in the image,)` and the boxes a `torch.FloatTensor` of shape `(number of bounding boxes in the image, 4)`.
+
+ Examples:
+
+ ```python
+ >>> from transformers import AutoImageProcessor, RTDetrModel
+ >>> from PIL import Image
+ >>> import httpx
+ >>> from io import BytesIO
+
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
+ >>> with httpx.stream("GET", url) as response:
+ ... image = Image.open(BytesIO(response.read()))
+
+ >>> image_processor = AutoImageProcessor.from_pretrained("PekingU/rtdetr_r50vd")
+ >>> model = RTDetrModel.from_pretrained("PekingU/rtdetr_r50vd")
+
+ >>> inputs = image_processor(images=image, return_tensors="pt")
+
+ >>> outputs = model(**inputs)
+
+ >>> last_hidden_states = outputs.last_hidden_state
+ >>> list(last_hidden_states.shape)
+ [1, 300, 256]
+ ```"""
+ if pixel_values is None and inputs_embeds is None:
+ raise ValueError("You have to specify either pixel_values or inputs_embeds")
+
+ if inputs_embeds is None:
+ batch_size, num_channels, height, width = pixel_values.shape
+ device = pixel_values.device
+ if pixel_mask is None:
+ pixel_mask = torch.ones(((batch_size, height, width)), device=device)
+ features = self.backbone(pixel_values, pixel_mask)
+ proj_feats = [self.encoder_input_proj[level](source) for level, (source, mask) in enumerate(features)]
+ else:
+ batch_size = inputs_embeds.shape[0]
+ device = inputs_embeds.device
+ proj_feats = inputs_embeds
+
+ if encoder_outputs is None:
+ encoder_outputs = self.encoder(
+ proj_feats,
+ **kwargs,
+ )
+ # If the user passed a tuple for encoder_outputs, we wrap it in a BaseModelOutput
+ elif not isinstance(encoder_outputs, BaseModelOutput):
+ encoder_outputs = BaseModelOutput(
+ last_hidden_state=encoder_outputs[0],
+ hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
+ attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
+ )
+
+ # Equivalent to def _get_encoder_input
+ # https://github.com/lyuwenyu/RT-DETR/blob/94f5e16708329d2f2716426868ec89aa774af016/rtdetr_pytorch/src/zoo/rtdetr/rtdetr_decoder.py#L412
+ sources = []
+ for level, source in enumerate(encoder_outputs.last_hidden_state):
+ sources.append(self.decoder_input_proj[level](source))
+
+ # Lowest resolution feature maps are obtained via 3x3 stride 2 convolutions on the final stage
+ if self.config.num_feature_levels > len(sources):
+ _len_sources = len(sources)
+ sources.append(self.decoder_input_proj[_len_sources](encoder_outputs.last_hidden_state)[-1])
+ for i in range(_len_sources + 1, self.config.num_feature_levels):
+ sources.append(self.decoder_input_proj[i](encoder_outputs.last_hidden_state[-1]))
+
+ # Prepare encoder inputs (by flattening)
+ source_flatten = []
+ spatial_shapes_list = []
+ spatial_shapes = torch.empty((len(sources), 2), device=device, dtype=torch.long)
+ for level, source in enumerate(sources):
+ height, width = source.shape[-2:]
+ spatial_shapes[level, 0] = height
+ spatial_shapes[level, 1] = width
+ spatial_shapes_list.append((height, width))
+ source = source.flatten(2).transpose(1, 2)
+ source_flatten.append(source)
+ source_flatten = torch.cat(source_flatten, 1)
+ level_start_index = torch.cat((spatial_shapes.new_zeros((1,)), spatial_shapes.prod(1).cumsum(0)[:-1]))
+
+ # prepare denoising training
+ if self.training and self.config.num_denoising > 0 and labels is not None:
+ (
+ denoising_class,
+ denoising_bbox_unact,
+ attention_mask,
+ denoising_meta_values,
+ ) = get_contrastive_denoising_training_group(
+ targets=labels,
+ num_classes=self.config.num_labels,
+ num_queries=self.config.num_queries,
+ class_embed=self.denoising_class_embed,
+ num_denoising_queries=self.config.num_denoising,
+ label_noise_ratio=self.config.label_noise_ratio,
+ box_noise_scale=self.config.box_noise_scale,
+ )
+ else:
+ denoising_class, denoising_bbox_unact, attention_mask, denoising_meta_values = None, None, None, None
+
+ batch_size = len(source_flatten)
+ device = source_flatten.device
+ dtype = source_flatten.dtype
+
+ # prepare input for decoder
+ if self.training or self.config.anchor_image_size is None:
+ # Pass spatial_shapes as tuple to make it hashable and make sure
+ # lru_cache is working for generate_anchors()
+ spatial_shapes_tuple = tuple(spatial_shapes_list)
+ anchors, valid_mask = self.generate_anchors(spatial_shapes_tuple, device=device, dtype=dtype)
+ else:
+ anchors, valid_mask = self.anchors, self.valid_mask
+ anchors, valid_mask = anchors.to(device, dtype), valid_mask.to(device, dtype)
+
+ # use the valid_mask to selectively retain values in the feature map where the mask is `True`
+ memory = valid_mask.to(source_flatten.dtype) * source_flatten
+
+ output_memory = self.enc_output(memory)
+
+ enc_outputs_class = self.enc_score_head(output_memory)
+ enc_outputs_coord_logits = self.enc_bbox_head(output_memory) + anchors
+
+ _, topk_ind = torch.topk(enc_outputs_class.max(-1).values, self.config.num_queries, dim=1)
+
+ reference_points_unact = enc_outputs_coord_logits.gather(
+ dim=1, index=topk_ind.unsqueeze(-1).repeat(1, 1, enc_outputs_coord_logits.shape[-1])
+ )
+
+ enc_topk_bboxes = F.sigmoid(reference_points_unact)
+ if denoising_bbox_unact is not None:
+ reference_points_unact = torch.concat([denoising_bbox_unact, reference_points_unact], 1)
+
+ enc_topk_logits = enc_outputs_class.gather(
+ dim=1, index=topk_ind.unsqueeze(-1).repeat(1, 1, enc_outputs_class.shape[-1])
+ )
+
+ # extract region features
+ if self.config.learn_initial_query:
+ target = self.weight_embedding.tile([batch_size, 1, 1])
+ else:
+ target = output_memory.gather(dim=1, index=topk_ind.unsqueeze(-1).repeat(1, 1, output_memory.shape[-1]))
+ target = target.detach()
+
+ if denoising_class is not None:
+ target = torch.concat([denoising_class, target], 1)
+
+ init_reference_points = reference_points_unact.detach()
+
+ # decoder
+ decoder_outputs = self.decoder(
+ inputs_embeds=target,
+ encoder_hidden_states=source_flatten,
+ encoder_attention_mask=attention_mask,
+ reference_points=init_reference_points,
+ spatial_shapes=spatial_shapes,
+ spatial_shapes_list=spatial_shapes_list,
+ level_start_index=level_start_index,
+ **kwargs,
+ )
+
+ return RTDetrModelOutput(
+ last_hidden_state=decoder_outputs.last_hidden_state,
+ intermediate_hidden_states=decoder_outputs.intermediate_hidden_states,
+ intermediate_logits=decoder_outputs.intermediate_logits,
+ intermediate_reference_points=decoder_outputs.intermediate_reference_points,
+ intermediate_predicted_corners=decoder_outputs.intermediate_predicted_corners,
+ initial_reference_points=decoder_outputs.initial_reference_points,
+ decoder_hidden_states=decoder_outputs.hidden_states,
+ decoder_attentions=decoder_outputs.attentions,
+ cross_attentions=decoder_outputs.cross_attentions,
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
+ encoder_hidden_states=encoder_outputs.hidden_states,
+ encoder_attentions=encoder_outputs.attentions,
+ init_reference_points=init_reference_points,
+ enc_topk_logits=enc_topk_logits,
+ enc_topk_bboxes=enc_topk_bboxes,
+ enc_outputs_class=enc_outputs_class,
+ enc_outputs_coord_logits=enc_outputs_coord_logits,
+ denoising_meta_values=denoising_meta_values,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ RT-DETR Model (consisting of a backbone and encoder-decoder) outputting bounding boxes and logits to be further
+ decoded into scores and classes.
+ """
+)
+class RTDetrForObjectDetection(RTDetrPreTrainedModel):
+ # When using clones, all layers > 0 will be clones, but layer 0 *is* required
+ # We can't initialize the model on meta device as some weights are modified during the initialization
+ _no_split_modules = None
+
+ def __init__(self, config: RTDetrConfig):
+ super().__init__(config)
+ self.model = RTDetrModel(config)
+ num_pred = config.decoder_layers
+ self.model.decoder.class_embed = nn.ModuleList(
+ [torch.nn.Linear(config.d_model, config.num_labels) for _ in range(num_pred)]
+ )
+ self.model.decoder.bbox_embed = nn.ModuleList(
+ [RTDetrMLPPredictionHead(config.d_model, config.d_model, 4, num_layers=3) for _ in range(num_pred)]
+ )
+ # if two-stage, the last class_embed and bbox_embed is for region proposal generation
+ self.post_init()
+
+ def _set_aux_loss(self, outputs_class, outputs_coord):
+ return [{"logits": a, "pred_boxes": b} for a, b in zip(outputs_class, outputs_coord)]
+
+ @auto_docstring
+ @can_return_tuple
+ def forward(
+ self,
+ pixel_values: torch.FloatTensor,
+ pixel_mask: torch.LongTensor | None = None,
+ encoder_outputs: torch.FloatTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: list[dict] | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.FloatTensor] | RTDetrObjectDetectionOutput:
+ r"""
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
+ Optionally, instead of passing the flattened feature map (output of the backbone + projection layer), you
+ can choose to directly pass a flattened representation of an image.
+ labels (`list[Dict]` of len `(batch_size,)`, *optional*):
+ Labels for computing the bipartite matching loss. List of dicts, each dictionary containing at least the
+ following 2 keys: 'class_labels' and 'boxes' (the class labels and bounding boxes of an image in the batch
+ respectively). The class labels themselves should be a `torch.LongTensor` of len `(number of bounding boxes
+ in the image,)` and the boxes a `torch.FloatTensor` of shape `(number of bounding boxes in the image, 4)`.
+
+ Examples:
+
+ ```python
+ >>> from transformers import RTDetrImageProcessor, RTDetrForObjectDetection
+ >>> from PIL import Image
+ >>> import httpx
+ >>> from io import BytesIO
+ >>> import torch
+
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
+ >>> with httpx.stream("GET", url) as response:
+ ... image = Image.open(BytesIO(response.read()))
+
+ >>> image_processor = RTDetrImageProcessor.from_pretrained("PekingU/rtdetr_r50vd")
+ >>> model = RTDetrForObjectDetection.from_pretrained("PekingU/rtdetr_r50vd")
+
+ >>> # prepare image for the model
+ >>> inputs = image_processor(images=image, return_tensors="pt")
+
+ >>> # forward pass
+ >>> outputs = model(**inputs)
+
+ >>> logits = outputs.logits
+ >>> list(logits.shape)
+ [1, 300, 80]
+
+ >>> boxes = outputs.pred_boxes
+ >>> list(boxes.shape)
+ [1, 300, 4]
+
+ >>> # convert outputs (bounding boxes and class logits) to Pascal VOC format (xmin, ymin, xmax, ymax)
+ >>> target_sizes = torch.tensor([image.size[::-1]])
+ >>> results = image_processor.post_process_object_detection(outputs, threshold=0.9, target_sizes=target_sizes)[
+ ... 0
+ ... ]
+
+ >>> for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
+ ... box = [round(i, 2) for i in box.tolist()]
+ ... print(
+ ... f"Detected {model.config.id2label[label.item()]} with confidence "
+ ... f"{round(score.item(), 3)} at location {box}"
+ ... )
+ Detected sofa with confidence 0.97 at location [0.14, 0.38, 640.13, 476.21]
+ Detected cat with confidence 0.96 at location [343.38, 24.28, 640.14, 371.5]
+ Detected cat with confidence 0.958 at location [13.23, 54.18, 318.98, 472.22]
+ Detected remote with confidence 0.951 at location [40.11, 73.44, 175.96, 118.48]
+ Detected remote with confidence 0.924 at location [333.73, 76.58, 369.97, 186.99]
+ ```"""
+ outputs = self.model(
+ pixel_values,
+ pixel_mask=pixel_mask,
+ encoder_outputs=encoder_outputs,
+ inputs_embeds=inputs_embeds,
+ labels=labels,
+ **kwargs,
+ )
+
+ denoising_meta_values = outputs.denoising_meta_values if self.training else None
+
+ outputs_class = outputs.intermediate_logits
+ outputs_coord = outputs.intermediate_reference_points
+ predicted_corners = outputs.intermediate_predicted_corners
+ initial_reference_points = outputs.initial_reference_points
+
+ logits = outputs_class[:, -1]
+ pred_boxes = outputs_coord[:, -1]
+
+ loss, loss_dict, auxiliary_outputs, enc_topk_logits, enc_topk_bboxes = None, None, None, None, None
+ if labels is not None:
+ enc_topk_logits = outputs.enc_topk_logits
+ enc_topk_bboxes = outputs.enc_topk_bboxes
+ loss, loss_dict, auxiliary_outputs = self.loss_function(
+ logits,
+ labels,
+ self.device,
+ pred_boxes,
+ self.config,
+ outputs_class,
+ outputs_coord,
+ enc_topk_logits=enc_topk_logits,
+ enc_topk_bboxes=enc_topk_bboxes,
+ denoising_meta_values=denoising_meta_values,
+ predicted_corners=predicted_corners,
+ initial_reference_points=initial_reference_points,
+ **kwargs,
+ )
+
+ return RTDetrObjectDetectionOutput(
+ loss=loss,
+ loss_dict=loss_dict,
+ logits=logits,
+ pred_boxes=pred_boxes,
+ auxiliary_outputs=auxiliary_outputs,
+ last_hidden_state=outputs.last_hidden_state,
+ intermediate_hidden_states=outputs.intermediate_hidden_states,
+ intermediate_logits=outputs.intermediate_logits,
+ intermediate_reference_points=outputs.intermediate_reference_points,
+ intermediate_predicted_corners=outputs.intermediate_predicted_corners,
+ initial_reference_points=outputs.initial_reference_points,
+ decoder_hidden_states=outputs.decoder_hidden_states,
+ decoder_attentions=outputs.decoder_attentions,
+ cross_attentions=outputs.cross_attentions,
+ encoder_last_hidden_state=outputs.encoder_last_hidden_state,
+ encoder_hidden_states=outputs.encoder_hidden_states,
+ encoder_attentions=outputs.encoder_attentions,
+ init_reference_points=outputs.init_reference_points,
+ enc_topk_logits=outputs.enc_topk_logits,
+ enc_topk_bboxes=outputs.enc_topk_bboxes,
+ enc_outputs_class=outputs.enc_outputs_class,
+ enc_outputs_coord_logits=outputs.enc_outputs_coord_logits,
+ denoising_meta_values=outputs.denoising_meta_values,
+ )
+
+
+__all__ = ["RTDetrForObjectDetection", "RTDetrModel", "RTDetrPreTrainedModel"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/rt_detr/modeling_rt_detr_resnet.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/rt_detr/modeling_rt_detr_resnet.py
new file mode 100644
index 0000000000000000000000000000000000000000..e557fa0e7cf7d5a50595d66e2cf1b215a1b4952a
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/rt_detr/modeling_rt_detr_resnet.py
@@ -0,0 +1,427 @@
+# Copyright 2024 Microsoft Research, Inc. and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""
+PyTorch RTDetr specific ResNet model. The main difference between hugginface ResNet model is that this RTDetrResNet model forces to use shortcut at the first layer in the resnet-18/34 models.
+See https://github.com/lyuwenyu/RT-DETR/blob/5b628eaa0a2fc25bdafec7e6148d5296b144af85/rtdetr_pytorch/src/nn/backbone/presnet.py#L126 for details.
+"""
+
+import math
+
+import torch
+from torch import Tensor, nn
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...backbone_utils import BackboneMixin, filter_output_hidden_states
+from ...modeling_outputs import BackboneOutput, BaseModelOutputWithNoAttention
+from ...modeling_utils import PreTrainedModel
+from ...utils import auto_docstring, logging
+from ...utils.generic import can_return_tuple
+from .configuration_rt_detr_resnet import RTDetrResNetConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+# Copied from transformers.models.resnet.modeling_resnet.ResNetConvLayer with ResNet->RTDetrResNet
+class RTDetrResNetConvLayer(nn.Module):
+ def __init__(
+ self,
+ in_channels: int,
+ out_channels: int,
+ kernel_size: int | tuple[int, int] = 3,
+ stride: int = 1,
+ bias: bool = False,
+ dilation: int | tuple[int, int] = 1,
+ groups: int = 1,
+ activation: str = "relu",
+ ):
+ super().__init__()
+ self.convolution = nn.Conv2d(
+ in_channels=in_channels,
+ out_channels=out_channels,
+ kernel_size=kernel_size,
+ stride=stride,
+ padding=kernel_size // 2,
+ dilation=dilation,
+ groups=groups,
+ bias=bias,
+ )
+ self.normalization = nn.BatchNorm2d(out_channels)
+ self.activation = ACT2FN[activation] if activation is not None else nn.Identity()
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.convolution(hidden_states)
+ hidden_states = self.normalization(hidden_states)
+ hidden_states = self.activation(hidden_states)
+ return hidden_states
+
+
+class RTDetrResNetEmbeddings(nn.Module):
+ """
+ ResNet Embeddings (stem) composed of a deep aggressive convolution.
+ """
+
+ def __init__(self, config: RTDetrResNetConfig):
+ super().__init__()
+ self.embedder = nn.Sequential(
+ *[
+ RTDetrResNetConvLayer(
+ config.num_channels,
+ config.embedding_size // 2,
+ kernel_size=3,
+ stride=2,
+ activation=config.hidden_act,
+ ),
+ RTDetrResNetConvLayer(
+ config.embedding_size // 2,
+ config.embedding_size // 2,
+ kernel_size=3,
+ stride=1,
+ activation=config.hidden_act,
+ ),
+ RTDetrResNetConvLayer(
+ config.embedding_size // 2,
+ config.embedding_size,
+ kernel_size=3,
+ stride=1,
+ activation=config.hidden_act,
+ ),
+ ]
+ )
+ self.pooler = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
+ self.num_channels = config.num_channels
+
+ def forward(self, pixel_values: Tensor) -> Tensor:
+ num_channels = pixel_values.shape[1]
+ if num_channels != self.num_channels:
+ raise ValueError(
+ "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
+ )
+ embedding = self.embedder(pixel_values)
+ embedding = self.pooler(embedding)
+ return embedding
+
+
+# Copied from transformers.models.resnet.modeling_resnet.ResNetShortCut -> RTDetrResNetChortCut
+class RTDetrResNetShortCut(nn.Module):
+ """
+ ResNet shortcut, used to project the residual features to the correct size. If needed, it is also used to
+ downsample the input using `stride=2`.
+ """
+
+ def __init__(self, in_channels: int, out_channels: int, stride: int = 2):
+ super().__init__()
+ self.convolution = nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=stride, bias=False)
+ self.normalization = nn.BatchNorm2d(out_channels)
+
+ def forward(self, input: Tensor) -> Tensor:
+ hidden_state = self.convolution(input)
+ hidden_state = self.normalization(hidden_state)
+ return hidden_state
+
+
+class RTDetrResNetBasicLayer(nn.Module):
+ """
+ A classic ResNet's residual layer composed by two `3x3` convolutions.
+ See https://github.com/lyuwenyu/RT-DETR/blob/5b628eaa0a2fc25bdafec7e6148d5296b144af85/rtdetr_pytorch/src/nn/backbone/presnet.py#L34.
+ """
+
+ def __init__(
+ self,
+ config: RTDetrResNetConfig,
+ in_channels: int,
+ out_channels: int,
+ stride: int = 1,
+ should_apply_shortcut: bool = False,
+ ):
+ super().__init__()
+ if in_channels != out_channels:
+ self.shortcut = (
+ nn.Sequential(
+ *[nn.AvgPool2d(2, 2, 0, ceil_mode=True), RTDetrResNetShortCut(in_channels, out_channels, stride=1)]
+ )
+ if should_apply_shortcut
+ else nn.Identity()
+ )
+ else:
+ self.shortcut = (
+ RTDetrResNetShortCut(in_channels, out_channels, stride=stride)
+ if should_apply_shortcut
+ else nn.Identity()
+ )
+ self.layer = nn.Sequential(
+ RTDetrResNetConvLayer(in_channels, out_channels, stride=stride),
+ RTDetrResNetConvLayer(out_channels, out_channels, activation=None),
+ )
+ self.activation = ACT2FN[config.hidden_act]
+
+ def forward(self, hidden_state):
+ residual = hidden_state
+ hidden_state = self.layer(hidden_state)
+ residual = self.shortcut(residual)
+ hidden_state += residual
+ hidden_state = self.activation(hidden_state)
+ return hidden_state
+
+
+class RTDetrResNetBottleNeckLayer(nn.Module):
+ """
+ A classic RTDetrResNet's bottleneck layer composed by three `3x3` convolutions.
+
+ The first `1x1` convolution reduces the input by a factor of `reduction` in order to make the second `3x3`
+ convolution faster. The last `1x1` convolution remaps the reduced features to `out_channels`. If
+ `downsample_in_bottleneck` is true, downsample will be in the first layer instead of the second layer.
+ """
+
+ def __init__(
+ self,
+ config: RTDetrResNetConfig,
+ in_channels: int,
+ out_channels: int,
+ stride: int = 1,
+ ):
+ super().__init__()
+ reduction = 4
+ should_apply_shortcut = in_channels != out_channels or stride != 1
+ reduces_channels = out_channels // reduction
+ if stride == 2:
+ self.shortcut = nn.Sequential(
+ *[
+ nn.AvgPool2d(2, 2, 0, ceil_mode=True),
+ RTDetrResNetShortCut(in_channels, out_channels, stride=1)
+ if should_apply_shortcut
+ else nn.Identity(),
+ ]
+ )
+ else:
+ self.shortcut = (
+ RTDetrResNetShortCut(in_channels, out_channels, stride=stride)
+ if should_apply_shortcut
+ else nn.Identity()
+ )
+ self.layer = nn.Sequential(
+ RTDetrResNetConvLayer(
+ in_channels, reduces_channels, kernel_size=1, stride=stride if config.downsample_in_bottleneck else 1
+ ),
+ RTDetrResNetConvLayer(
+ reduces_channels, reduces_channels, stride=stride if not config.downsample_in_bottleneck else 1
+ ),
+ RTDetrResNetConvLayer(reduces_channels, out_channels, kernel_size=1, activation=None),
+ )
+ self.activation = ACT2FN[config.hidden_act]
+
+ def forward(self, hidden_state):
+ residual = hidden_state
+ hidden_state = self.layer(hidden_state)
+ residual = self.shortcut(residual)
+ hidden_state += residual
+ hidden_state = self.activation(hidden_state)
+ return hidden_state
+
+
+class RTDetrResNetStage(nn.Module):
+ """
+ A RTDetrResNet stage composed by stacked layers.
+ """
+
+ def __init__(
+ self,
+ config: RTDetrResNetConfig,
+ in_channels: int,
+ out_channels: int,
+ stride: int = 2,
+ depth: int = 2,
+ ):
+ super().__init__()
+
+ layer = RTDetrResNetBottleNeckLayer if config.layer_type == "bottleneck" else RTDetrResNetBasicLayer
+
+ if config.layer_type == "bottleneck":
+ first_layer = layer(
+ config,
+ in_channels,
+ out_channels,
+ stride=stride,
+ )
+ else:
+ first_layer = layer(config, in_channels, out_channels, stride=stride, should_apply_shortcut=True)
+ self.layers = nn.Sequential(
+ first_layer, *[layer(config, out_channels, out_channels) for _ in range(depth - 1)]
+ )
+
+ def forward(self, input: Tensor) -> Tensor:
+ hidden_state = input
+ for layer in self.layers:
+ hidden_state = layer(hidden_state)
+ return hidden_state
+
+
+# Copied from transformers.models.resnet.modeling_resnet.ResNetEncoder with ResNet->RTDetrResNet
+class RTDetrResNetEncoder(nn.Module):
+ def __init__(self, config: RTDetrResNetConfig):
+ super().__init__()
+ self.stages = nn.ModuleList([])
+ # based on `downsample_in_first_stage` the first layer of the first stage may or may not downsample the input
+ self.stages.append(
+ RTDetrResNetStage(
+ config,
+ config.embedding_size,
+ config.hidden_sizes[0],
+ stride=2 if config.downsample_in_first_stage else 1,
+ depth=config.depths[0],
+ )
+ )
+ in_out_channels = zip(config.hidden_sizes, config.hidden_sizes[1:])
+ for (in_channels, out_channels), depth in zip(in_out_channels, config.depths[1:]):
+ self.stages.append(RTDetrResNetStage(config, in_channels, out_channels, depth=depth))
+
+ def forward(
+ self, hidden_state: Tensor, output_hidden_states: bool = False, return_dict: bool = True
+ ) -> BaseModelOutputWithNoAttention:
+ hidden_states = () if output_hidden_states else None
+
+ for stage_module in self.stages:
+ if output_hidden_states:
+ hidden_states = hidden_states + (hidden_state,)
+
+ hidden_state = stage_module(hidden_state)
+
+ if output_hidden_states:
+ hidden_states = hidden_states + (hidden_state,)
+
+ if not return_dict:
+ return tuple(v for v in [hidden_state, hidden_states] if v is not None)
+
+ return BaseModelOutputWithNoAttention(
+ last_hidden_state=hidden_state,
+ hidden_states=hidden_states,
+ )
+
+
+@auto_docstring
+# Copied from transformers.models.resnet.modeling_resnet.ResNetPreTrainedModel with ResNet->RTDetrResNet
+class RTDetrResNetPreTrainedModel(PreTrainedModel):
+ config: RTDetrResNetConfig
+ base_model_prefix = "resnet"
+ main_input_name = "pixel_values"
+ input_modalities = ("image",)
+ _no_split_modules = ["RTDetrResNetConvLayer", "RTDetrResNetShortCut"]
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ if isinstance(module, nn.Conv2d):
+ init.kaiming_normal_(module.weight, mode="fan_out", nonlinearity="relu")
+ # copied from the `reset_parameters` method of `class Linear(Module)` in `torch`.
+ elif isinstance(module, nn.Linear):
+ init.kaiming_uniform_(module.weight, a=math.sqrt(5))
+ if module.bias is not None:
+ fan_in, _ = torch.nn.init._calculate_fan_in_and_fan_out(module.weight)
+ bound = 1 / math.sqrt(fan_in) if fan_in > 0 else 0
+ init.uniform_(module.bias, -bound, bound)
+ # We need to check it like that as some Detr models replace the BatchNorm2d by their own
+ elif "BatchNorm" in module.__class__.__name__:
+ init.ones_(module.weight)
+ init.zeros_(module.bias)
+ init.zeros_(module.running_mean)
+ init.ones_(module.running_var)
+ if getattr(module, "num_batches_tracked", None) is not None:
+ init.zeros_(module.num_batches_tracked)
+
+
+@auto_docstring(
+ custom_intro="""
+ ResNet backbone, to be used with frameworks like RTDETR.
+ """
+)
+class RTDetrResNetBackbone(BackboneMixin, RTDetrResNetPreTrainedModel):
+ has_attentions = False
+
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.num_features = [config.embedding_size] + config.hidden_sizes
+ self.embedder = RTDetrResNetEmbeddings(config)
+ self.encoder = RTDetrResNetEncoder(config)
+
+ # initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @filter_output_hidden_states
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: Tensor,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> BackboneOutput:
+ r"""
+ Examples:
+
+ ```python
+ >>> from transformers import RTDetrResNetConfig, RTDetrResNetBackbone
+ >>> import torch
+ from ...utils.deprecation import deprecate_kwarg
+ from ...utils.deprecation import deprecate_kwarg
+ from ...utils.deprecation import deprecate_kwarg
+ from ...utils.deprecation import deprecate_kwarg
+ from ...utils.deprecation import deprecate_kwarg
+
+ >>> config = RTDetrResNetConfig()
+ >>> model = RTDetrResNetBackbone(config)
+
+ >>> pixel_values = torch.randn(1, 3, 224, 224)
+
+ >>> with torch.no_grad():
+ ... outputs = model(pixel_values)
+
+ >>> feature_maps = outputs.feature_maps
+ >>> list(feature_maps[-1].shape)
+ [1, 2048, 7, 7]
+ ```"""
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+
+ embedding_output = self.embedder(pixel_values)
+
+ outputs = self.encoder(embedding_output, output_hidden_states=True, return_dict=True)
+
+ hidden_states = outputs.hidden_states
+
+ feature_maps = ()
+ for idx, stage in enumerate(self.stage_names):
+ if stage in self.out_features:
+ feature_maps += (hidden_states[idx],)
+
+ if not return_dict:
+ output = (feature_maps,)
+ if output_hidden_states:
+ output += (outputs.hidden_states,)
+ return output
+
+ return BackboneOutput(
+ feature_maps=feature_maps,
+ hidden_states=outputs.hidden_states if output_hidden_states else None,
+ attentions=None,
+ )
+
+
+__all__ = [
+ "RTDetrResNetBackbone",
+ "RTDetrResNetPreTrainedModel",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/rt_detr/modular_rt_detr.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/rt_detr/modular_rt_detr.py
new file mode 100644
index 0000000000000000000000000000000000000000..11d5191001f9f79a77f9ce1004383a606ba20c06
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/rt_detr/modular_rt_detr.py
@@ -0,0 +1,2152 @@
+# Copyright 2024 Baidu Inc and The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import math
+import pathlib
+from dataclasses import dataclass
+
+import numpy as np
+import torch
+import torch.nn.functional as F
+from torch import nn
+
+from ... import initialization as init
+from ...activations import ACT2CLS, ACT2FN
+from ...backbone_utils import load_backbone
+from ...image_processing_backends import PilBackend, TorchvisionBackend
+from ...image_processing_utils import BatchFeature, SizeDict
+from ...image_transforms import center_to_corners_format, corners_to_center_format
+from ...image_utils import (
+ IMAGENET_DEFAULT_MEAN,
+ IMAGENET_DEFAULT_STD,
+ AnnotationFormat,
+ AnnotationType,
+ ChannelDimension,
+ PILImageResampling,
+ get_image_size,
+ get_max_height_width,
+ validate_annotations,
+)
+from ...modeling_outputs import BaseModelOutput
+from ...modeling_utils import PreTrainedModel
+from ...processing_utils import ImagesKwargs, Unpack
+from ...pytorch_utils import compile_compatible_method_lru_cache
+from ...utils import (
+ ModelOutput,
+ TensorType,
+ TransformersKwargs,
+ auto_docstring,
+ logging,
+ requires_backends,
+ torch_int,
+)
+from ...utils.generic import can_return_tuple, merge_with_config_defaults
+from ...utils.import_utils import requires
+from ...utils.output_capturing import capture_outputs
+from ..conditional_detr.modeling_conditional_detr import inverse_sigmoid
+from ..deformable_detr.modeling_deformable_detr import DeformableDetrMultiscaleDeformableAttention
+from ..detr.image_processing_detr import DetrImageProcessor
+from ..detr.image_processing_pil_detr import DetrImageProcessorPil
+from ..detr.modeling_detr import DetrFrozenBatchNorm2d, DetrMLPPredictionHead, DetrSelfAttention, replace_batch_norm
+from ..vit_mae.modeling_vit_mae import build_2d_sinusoidal_position_embedding
+from .configuration_rt_detr import RTDetrConfig
+
+
+logger = logging.get_logger(__name__)
+
+SUPPORTED_ANNOTATION_FORMATS = (AnnotationFormat.COCO_DETECTION,)
+
+
+def prepare_coco_detection_annotation(
+ image,
+ target,
+ return_segmentation_masks: bool = False,
+ input_data_format: ChannelDimension | str | None = None,
+):
+ """
+ Convert the target in COCO format into the format expected by RT-DETR.
+ """
+ image_height, image_width = image.size()[-2:]
+
+ image_id = target["image_id"]
+ image_id = torch.as_tensor([image_id], dtype=torch.int64, device=image.device)
+
+ # Get all COCO annotations for the given image.
+ annotations = target["annotations"]
+ classes = []
+ area = []
+ boxes = []
+ keypoints = []
+ for obj in annotations:
+ if "iscrowd" not in obj or obj["iscrowd"] == 0:
+ classes.append(obj["category_id"])
+ area.append(obj["area"])
+ boxes.append(obj["bbox"])
+ if "keypoints" in obj:
+ keypoints.append(obj["keypoints"])
+
+ classes = torch.as_tensor(classes, dtype=torch.int64, device=image.device)
+ area = torch.as_tensor(area, dtype=torch.float32, device=image.device)
+ iscrowd = torch.zeros_like(classes, dtype=torch.int64, device=image.device)
+ # guard against no boxes via resizing
+ boxes = torch.as_tensor(boxes, dtype=torch.float32, device=image.device).reshape(-1, 4)
+ boxes[:, 2:] += boxes[:, :2]
+ boxes[:, 0::2] = boxes[:, 0::2].clip(min=0, max=image_width)
+ boxes[:, 1::2] = boxes[:, 1::2].clip(min=0, max=image_height)
+
+ keep = (boxes[:, 3] > boxes[:, 1]) & (boxes[:, 2] > boxes[:, 0])
+
+ new_target = {
+ "image_id": image_id,
+ "class_labels": classes[keep],
+ "boxes": boxes[keep],
+ "area": area[keep],
+ "iscrowd": iscrowd[keep],
+ "orig_size": torch.as_tensor([int(image_height), int(image_width)], dtype=torch.int64, device=image.device),
+ }
+
+ if keypoints:
+ keypoints = torch.as_tensor(keypoints, dtype=torch.float32, device=image.device)
+ # Apply the keep mask here to filter the relevant annotations
+ keypoints = keypoints[keep]
+ num_keypoints = keypoints.shape[0]
+ keypoints = keypoints.reshape((-1, 3)) if num_keypoints else keypoints
+ new_target["keypoints"] = keypoints
+
+ return new_target
+
+
+def prepare_coco_detection_annotation_pil(
+ image,
+ target,
+ return_segmentation_masks: bool = False,
+ input_data_format: ChannelDimension | str | None = None,
+):
+ """
+ Convert the target in COCO format into the format expected by RTDETR.
+ """
+ image_height, image_width = get_image_size(image, channel_dim=input_data_format)
+
+ image_id = target["image_id"]
+ image_id = np.asarray([image_id], dtype=np.int64)
+
+ # Get all COCO annotations for the given image.
+ annotations = target["annotations"]
+ annotations = [obj for obj in annotations if "iscrowd" not in obj or obj["iscrowd"] == 0]
+
+ classes = [obj["category_id"] for obj in annotations]
+ classes = np.asarray(classes, dtype=np.int64)
+
+ # for conversion to coco api
+ area = np.asarray([obj["area"] for obj in annotations], dtype=np.float32)
+ iscrowd = np.asarray([obj.get("iscrowd", 0) for obj in annotations], dtype=np.int64)
+
+ boxes = [obj["bbox"] for obj in annotations]
+ # guard against no boxes via resizing
+ boxes = np.asarray(boxes, dtype=np.float32).reshape(-1, 4)
+ boxes[:, 2:] += boxes[:, :2]
+ boxes[:, 0::2] = boxes[:, 0::2].clip(min=0, max=image_width)
+ boxes[:, 1::2] = boxes[:, 1::2].clip(min=0, max=image_height)
+
+ keep = (boxes[:, 3] > boxes[:, 1]) & (boxes[:, 2] > boxes[:, 0])
+
+ new_target = {}
+ new_target["image_id"] = image_id
+ new_target["class_labels"] = classes[keep]
+ new_target["boxes"] = boxes[keep]
+ new_target["area"] = area[keep]
+ new_target["iscrowd"] = iscrowd[keep]
+ new_target["orig_size"] = np.asarray([int(image_height), int(image_width)], dtype=np.int64)
+
+ if annotations and "keypoints" in annotations[0]:
+ keypoints = [obj["keypoints"] for obj in annotations]
+ # Converting the filtered keypoints list to a numpy array
+ keypoints = np.asarray(keypoints, dtype=np.float32)
+ # Apply the keep mask here to filter the relevant annotations
+ keypoints = keypoints[keep]
+ num_keypoints = keypoints.shape[0]
+ keypoints = keypoints.reshape((-1, 3)) if num_keypoints else keypoints
+ new_target["keypoints"] = keypoints
+
+ return new_target
+
+
+class RTDetrImageProcessorKwargs(ImagesKwargs, total=False):
+ r"""
+ format (`str`, *optional*, defaults to `AnnotationFormat.COCO_DETECTION`):
+ Data format of the annotations. One of "coco_detection" or "coco_panoptic".
+ do_convert_annotations (`bool`, *optional*, defaults to `True`):
+ Controls whether to convert the annotations to the format expected by the RT_DETR model. Converts the
+ bounding boxes to the format `(center_x, center_y, width, height)` and in the range `[0, 1]`.
+ Can be overridden by the `do_convert_annotations` parameter in the `preprocess` method.
+ """
+
+ format: str | AnnotationFormat
+ do_convert_annotations: bool
+
+
+class RTDetrImageProcessor(DetrImageProcessor):
+ resample = PILImageResampling.BILINEAR
+ image_mean = IMAGENET_DEFAULT_MEAN
+ image_std = IMAGENET_DEFAULT_STD
+ format = AnnotationFormat.COCO_DETECTION
+ do_convert_annotations = True
+ do_resize = True
+ do_rescale = True
+ do_normalize = False
+ do_pad = False
+ size = {"height": 640, "width": 640}
+ default_to_square = False
+ model_input_names = ["pixel_values", "pixel_mask"]
+ valid_kwargs = RTDetrImageProcessorKwargs
+
+ def __init__(self, **kwargs: Unpack[RTDetrImageProcessorKwargs]) -> None:
+ # Backwards compatibility
+ do_convert_annotations = kwargs.get("do_convert_annotations")
+ do_normalize = kwargs.get("do_normalize")
+ if do_convert_annotations is None and getattr(self, "do_convert_annotations", None) is None:
+ self.do_convert_annotations = do_normalize if do_normalize is not None else self.do_normalize
+
+ TorchvisionBackend.__init__(self, **kwargs)
+
+ def prepare_annotation(
+ self,
+ image: torch.Tensor,
+ target: dict,
+ format: AnnotationFormat | None = None,
+ return_segmentation_masks: bool | None = None,
+ masks_path: str | pathlib.Path | None = None,
+ input_data_format: str | ChannelDimension | None = None,
+ ) -> dict:
+ format = format if format is not None else self.format
+
+ if format == AnnotationFormat.COCO_DETECTION:
+ return_segmentation_masks = False if return_segmentation_masks is None else return_segmentation_masks
+ target = prepare_coco_detection_annotation(
+ image, target, return_segmentation_masks, input_data_format=input_data_format
+ )
+ else:
+ raise ValueError(f"Format {format} is not supported.")
+ return target
+
+ def _preprocess(
+ self,
+ images: list["torch.Tensor"],
+ annotations: AnnotationType | list[AnnotationType] | None,
+ return_segmentation_masks: bool,
+ masks_path: str | pathlib.Path | None,
+ do_resize: bool,
+ size: SizeDict,
+ resample: "PILImageResampling | None",
+ do_rescale: bool,
+ rescale_factor: float,
+ do_normalize: bool,
+ do_convert_annotations: bool,
+ image_mean: float | list[float] | None,
+ image_std: float | list[float] | None,
+ do_pad: bool,
+ pad_size: SizeDict | None,
+ format: str | AnnotationFormat | None,
+ return_tensors: str | TensorType | None,
+ **kwargs,
+ ) -> BatchFeature:
+ """
+ Preprocess an image or a batch of images so that it can be used by the model.
+ """
+
+ if annotations is not None and isinstance(annotations, dict):
+ annotations = [annotations]
+
+ if annotations is not None and len(images) != len(annotations):
+ raise ValueError(
+ f"The number of images ({len(images)}) and annotations ({len(annotations)}) do not match."
+ )
+
+ format = AnnotationFormat(format)
+ if annotations is not None:
+ validate_annotations(format, SUPPORTED_ANNOTATION_FORMATS, annotations)
+
+ data = {}
+ processed_images = []
+ processed_annotations = []
+ pixel_masks = [] # Initialize pixel_masks here
+ for image, annotation in zip(images, annotations if annotations is not None else [None] * len(images)):
+ # prepare (COCO annotations as a list of Dict -> DETR target as a single Dict per image)
+ if annotations is not None:
+ annotation = self.prepare_annotation(
+ image,
+ annotation,
+ format,
+ return_segmentation_masks=return_segmentation_masks,
+ masks_path=masks_path,
+ input_data_format=ChannelDimension.FIRST,
+ )
+
+ if do_resize:
+ resized_image = self.resize(image, size=size, resample=resample)
+ if annotations is not None:
+ annotation = self.resize_annotation(
+ annotation,
+ orig_size=image.size()[-2:],
+ target_size=resized_image.size()[-2:],
+ )
+ image = resized_image
+ # Fused rescale and normalize
+ image = self.rescale_and_normalize(image, do_rescale, rescale_factor, do_normalize, image_mean, image_std)
+ if do_convert_annotations and annotations is not None:
+ annotation = self.normalize_annotation(annotation, get_image_size(image, ChannelDimension.FIRST))
+
+ processed_images.append(image)
+ processed_annotations.append(annotation)
+ images = processed_images
+ annotations = processed_annotations if annotations is not None else None
+
+ if do_pad:
+ # depends on all resized image shapes so we need another loop
+ if pad_size is not None:
+ padded_size = (pad_size.height, pad_size.width)
+ else:
+ padded_size = get_max_height_width(images)
+
+ padded_images = []
+ padded_annotations = []
+ for image, annotation in zip(images, annotations if annotations is not None else [None] * len(images)):
+ # Pads images and returns their mask: {'pixel_values': ..., 'pixel_mask': ...}
+ if padded_size == image.size()[-2:]:
+ padded_images.append(image)
+ pixel_masks.append(torch.ones(padded_size, dtype=torch.int64, device=image.device))
+ padded_annotations.append(annotation)
+ continue
+ image, pixel_mask, annotation = self.pad(
+ image, padded_size, annotation=annotation, update_bboxes=do_convert_annotations
+ )
+ padded_images.append(image)
+ padded_annotations.append(annotation)
+ pixel_masks.append(pixel_mask)
+ images = padded_images
+ annotations = padded_annotations if annotations is not None else None
+ data.update({"pixel_mask": torch.stack(pixel_masks, dim=0)})
+
+ data.update({"pixel_values": torch.stack(images, dim=0)})
+ encoded_inputs = BatchFeature(data, tensor_type=return_tensors)
+ if annotations is not None:
+ encoded_inputs["labels"] = [
+ BatchFeature(annotation, tensor_type=return_tensors) for annotation in annotations
+ ]
+ return encoded_inputs
+
+ def post_process_object_detection(
+ self,
+ outputs,
+ threshold: float = 0.5,
+ target_sizes: TensorType | list[tuple] = None,
+ use_focal_loss: bool = True,
+ ):
+ """
+ Converts the raw output of [`DetrForObjectDetection`] into final bounding boxes in (top_left_x, top_left_y,
+ bottom_right_x, bottom_right_y) format. Only supports PyTorch.
+
+ Args:
+ outputs ([`DetrObjectDetectionOutput`]):
+ Raw outputs of the model.
+ threshold (`float`, *optional*, defaults to 0.5):
+ Score threshold to keep object detection predictions.
+ target_sizes (`torch.Tensor` or `list[tuple[int, int]]`, *optional*):
+ Tensor of shape `(batch_size, 2)` or list of tuples (`tuple[int, int]`) containing the target size
+ `(height, width)` of each image in the batch. If unset, predictions will not be resized.
+ use_focal_loss (`bool` defaults to `True`):
+ Variable informing if the focal loss was used to predict the outputs. If `True`, a sigmoid is applied
+ to compute the scores of each detection, otherwise, a softmax function is used.
+
+ Returns:
+ `list[Dict]`: A list of dictionaries, each dictionary containing the scores, labels and boxes for an image
+ in the batch as predicted by the model.
+ """
+ requires_backends(self, ["torch"])
+ out_logits, out_bbox = outputs.logits, outputs.pred_boxes
+ # convert from relative cxcywh to absolute xyxy
+ boxes = center_to_corners_format(out_bbox)
+ if target_sizes is not None:
+ if len(out_logits) != len(target_sizes):
+ raise ValueError(
+ "Make sure that you pass in as many target sizes as the batch dimension of the logits"
+ )
+ if isinstance(target_sizes, list):
+ img_h, img_w = torch.as_tensor(target_sizes).unbind(1)
+ else:
+ img_h, img_w = target_sizes.unbind(1)
+ scale_fct = torch.stack([img_w, img_h, img_w, img_h], dim=1).to(boxes.device)
+ boxes = boxes * scale_fct[:, None, :]
+
+ num_top_queries = out_logits.shape[1]
+ num_classes = out_logits.shape[2]
+
+ if use_focal_loss:
+ scores = torch.nn.functional.sigmoid(out_logits)
+ scores, index = torch.topk(scores.flatten(1), num_top_queries, axis=-1)
+ labels = index % num_classes
+ index = index // num_classes
+ boxes = boxes.gather(dim=1, index=index.unsqueeze(-1).repeat(1, 1, boxes.shape[-1]))
+ else:
+ scores = torch.nn.functional.softmax(out_logits)[:, :, :-1]
+ scores, labels = scores.max(dim=-1)
+ if scores.shape[1] > num_top_queries:
+ scores, index = torch.topk(scores, num_top_queries, dim=-1)
+ labels = torch.gather(labels, dim=1, index=index)
+ boxes = torch.gather(boxes, dim=1, index=index.unsqueeze(-1).tile(1, 1, boxes.shape[-1]))
+
+ results = []
+ for score, label, box in zip(scores, labels, boxes):
+ results.append(
+ {
+ "scores": score[score > threshold],
+ "labels": label[score > threshold],
+ "boxes": box[score > threshold],
+ }
+ )
+
+ return results
+
+ def post_process_instance_segmentation(self):
+ raise NotImplementedError("Segmentation post-processing is not implemented for RT-DETR yet.")
+
+ def post_process_semantic_segmentation(self):
+ raise NotImplementedError("Semantic segmentation post-processing is not implemented for RT-DETR yet.")
+
+ def post_process_panoptic_segmentation(self):
+ raise NotImplementedError("Panoptic segmentation post-processing is not implemented for RT-DETR yet.")
+
+
+@requires(backends=("torch",))
+class RTDetrImageProcessorPil(DetrImageProcessorPil):
+ resample = PILImageResampling.BILINEAR
+ image_mean = IMAGENET_DEFAULT_MEAN
+ image_std = IMAGENET_DEFAULT_STD
+ format = AnnotationFormat.COCO_DETECTION
+ do_convert_annotations = True
+ do_resize = True
+ do_rescale = True
+ do_normalize = False
+ do_pad = False
+ size = {"height": 640, "width": 640}
+ default_to_square = False
+ model_input_names = ["pixel_values", "pixel_mask"]
+ valid_kwargs = RTDetrImageProcessorKwargs
+
+ def __init__(self, **kwargs: Unpack[RTDetrImageProcessorKwargs]) -> None:
+ # Backwards compatibility
+ do_convert_annotations = kwargs.get("do_convert_annotations")
+ do_normalize = kwargs.get("do_normalize")
+ if do_convert_annotations is None and getattr(self, "do_convert_annotations", None) is None:
+ self.do_convert_annotations = do_normalize if do_normalize is not None else self.do_normalize
+
+ PilBackend.__init__(self, **kwargs)
+
+ def prepare_annotation(
+ self,
+ image: np.ndarray,
+ target: dict,
+ format: AnnotationFormat | None = None,
+ return_segmentation_masks: bool | None = None,
+ masks_path: str | pathlib.Path | None = None,
+ input_data_format: str | ChannelDimension | None = None,
+ ) -> dict:
+ format = format if format is not None else self.format
+
+ if format == AnnotationFormat.COCO_DETECTION:
+ return_segmentation_masks = False if return_segmentation_masks is None else return_segmentation_masks
+ target = prepare_coco_detection_annotation_pil(
+ image, target, return_segmentation_masks, input_data_format=input_data_format
+ )
+ else:
+ raise ValueError(f"Format {format} is not supported.")
+ return target
+
+ def _preprocess(
+ self,
+ images: list[np.ndarray],
+ annotations: AnnotationType | list[AnnotationType] | None,
+ return_segmentation_masks: bool,
+ masks_path: str | pathlib.Path | None,
+ do_resize: bool,
+ size: SizeDict,
+ resample: "PILImageResampling | None",
+ do_rescale: bool,
+ rescale_factor: float,
+ do_normalize: bool,
+ do_convert_annotations: bool,
+ image_mean: float | list[float] | None,
+ image_std: float | list[float] | None,
+ do_pad: bool,
+ pad_size: SizeDict | None,
+ format: str | AnnotationFormat | None,
+ return_tensors: str | TensorType | None,
+ **kwargs,
+ ) -> BatchFeature:
+ """
+ Preprocess an image or a batch of images so that it can be used by the model.
+ """
+
+ if annotations is not None and isinstance(annotations, dict):
+ annotations = [annotations]
+
+ if annotations is not None and len(images) != len(annotations):
+ raise ValueError(
+ f"The number of images ({len(images)}) and annotations ({len(annotations)}) do not match."
+ )
+
+ format = AnnotationFormat(format)
+ if annotations is not None:
+ validate_annotations(format, SUPPORTED_ANNOTATION_FORMATS, annotations)
+
+ data = {}
+ processed_images = []
+ processed_annotations = []
+ pixel_masks = [] # Initialize pixel_masks here
+ for image, annotation in zip(images, annotations if annotations is not None else [None] * len(images)):
+ # prepare (COCO annotations as a list of Dict -> DETR target as a single Dict per image)
+ if annotations is not None:
+ annotation = self.prepare_annotation(
+ image,
+ annotation,
+ format,
+ return_segmentation_masks=return_segmentation_masks,
+ masks_path=masks_path,
+ input_data_format=ChannelDimension.FIRST,
+ )
+
+ if do_resize:
+ resized_image = self.resize(image, size=size, resample=resample)
+ if annotations is not None:
+ annotation = self.resize_annotation(
+ annotation,
+ orig_size=image.shape[-2:],
+ target_size=resized_image.shape[-2:],
+ )
+ image = resized_image
+
+ if do_rescale:
+ image = self.rescale(image, rescale_factor)
+ if do_normalize:
+ image = self.normalize(image, image_mean, image_std)
+ if do_convert_annotations and annotations is not None:
+ annotation = self.normalize_annotation(annotation, get_image_size(image, ChannelDimension.FIRST))
+
+ processed_images.append(image)
+ processed_annotations.append(annotation)
+ images = processed_images
+ annotations = processed_annotations if annotations is not None else None
+
+ if do_pad:
+ # depends on all resized image shapes so we need another loop
+ if pad_size is not None:
+ padded_size = (pad_size.height, pad_size.width)
+ else:
+ padded_size = get_max_height_width(images)
+
+ padded_images = []
+ padded_annotations = []
+ for image, annotation in zip(images, annotations if annotations is not None else [None] * len(images)):
+ # Pads images and returns their mask: {'pixel_values': ..., 'pixel_mask': ...}
+ if padded_size == image.shape[-2:]:
+ padded_images.append(image)
+ pixel_masks.append(np.ones(padded_size, dtype=np.int64))
+ padded_annotations.append(annotation)
+ continue
+ image, pixel_mask, annotation = self.pad(
+ image, padded_size, annotation=annotation, update_bboxes=do_convert_annotations
+ )
+ padded_images.append(image)
+ padded_annotations.append(annotation)
+ pixel_masks.append(pixel_mask)
+ images = padded_images
+ annotations = padded_annotations if annotations is not None else None
+ data.update({"pixel_mask": pixel_masks})
+
+ data.update({"pixel_values": images})
+ encoded_inputs = BatchFeature(data, tensor_type=return_tensors)
+ if annotations is not None:
+ encoded_inputs["labels"] = [
+ BatchFeature(annotation, tensor_type=return_tensors) for annotation in annotations
+ ]
+ return encoded_inputs
+
+ def post_process_object_detection(
+ self,
+ outputs,
+ threshold: float = 0.5,
+ target_sizes: TensorType | list[tuple] = None,
+ use_focal_loss: bool = True,
+ ):
+ """
+ Converts the raw output of [`DetrForObjectDetection`] into final bounding boxes in (top_left_x, top_left_y,
+ bottom_right_x, bottom_right_y) format. Only supports PyTorch.
+
+ Args:
+ outputs ([`DetrObjectDetectionOutput`]):
+ Raw outputs of the model.
+ threshold (`float`, *optional*, defaults to 0.5):
+ Score threshold to keep object detection predictions.
+ target_sizes (`torch.Tensor` or `list[tuple[int, int]]`, *optional*):
+ Tensor of shape `(batch_size, 2)` or list of tuples (`tuple[int, int]`) containing the target size
+ `(height, width)` of each image in the batch. If unset, predictions will not be resized.
+ use_focal_loss (`bool` defaults to `True`):
+ Variable informing if the focal loss was used to predict the outputs. If `True`, a sigmoid is applied
+ to compute the scores of each detection, otherwise, a softmax function is used.
+
+ Returns:
+ `list[Dict]`: A list of dictionaries, each dictionary containing the scores, labels and boxes for an image
+ in the batch as predicted by the model.
+ """
+ requires_backends(self, ["torch"])
+ out_logits, out_bbox = outputs.logits, outputs.pred_boxes
+ # convert from relative cxcywh to absolute xyxy
+ boxes = center_to_corners_format(out_bbox)
+ if target_sizes is not None:
+ if len(out_logits) != len(target_sizes):
+ raise ValueError(
+ "Make sure that you pass in as many target sizes as the batch dimension of the logits"
+ )
+ if isinstance(target_sizes, list):
+ img_h, img_w = torch.as_tensor(target_sizes).unbind(1)
+ else:
+ img_h, img_w = target_sizes.unbind(1)
+ scale_fct = torch.stack([img_w, img_h, img_w, img_h], dim=1).to(boxes.device)
+ boxes = boxes * scale_fct[:, None, :]
+
+ num_top_queries = out_logits.shape[1]
+ num_classes = out_logits.shape[2]
+
+ if use_focal_loss:
+ scores = torch.nn.functional.sigmoid(out_logits)
+ scores, index = torch.topk(scores.flatten(1), num_top_queries, axis=-1)
+ labels = index % num_classes
+ index = index // num_classes
+ boxes = boxes.gather(dim=1, index=index.unsqueeze(-1).repeat(1, 1, boxes.shape[-1]))
+ else:
+ scores = torch.nn.functional.softmax(out_logits)[:, :, :-1]
+ scores, labels = scores.max(dim=-1)
+ if scores.shape[1] > num_top_queries:
+ scores, index = torch.topk(scores, num_top_queries, dim=-1)
+ labels = torch.gather(labels, dim=1, index=index)
+ boxes = torch.gather(boxes, dim=1, index=index.unsqueeze(-1).tile(1, 1, boxes.shape[-1]))
+
+ results = []
+ for score, label, box in zip(scores, labels, boxes):
+ results.append(
+ {
+ "scores": score[score > threshold],
+ "labels": label[score > threshold],
+ "boxes": box[score > threshold],
+ }
+ )
+
+ return results
+
+ def post_process_instance_segmentation(self):
+ raise NotImplementedError("Segmentation post-processing is not implemented for RT-DETR yet.")
+
+ def post_process_semantic_segmentation(self):
+ raise NotImplementedError("Semantic segmentation post-processing is not implemented for RT-DETR yet.")
+
+ def post_process_panoptic_segmentation(self):
+ raise NotImplementedError("Panoptic segmentation post-processing is not implemented for RT-DETR yet.")
+
+
+@auto_docstring(
+ custom_intro="""
+ Base class for outputs of the RTDetrDecoder. This class adds two attributes to
+ BaseModelOutputWithCrossAttentions, namely:
+ - a stacked tensor of intermediate decoder hidden states (i.e. the output of each decoder layer)
+ - a stacked tensor of intermediate reference points.
+ """
+)
+@dataclass
+class RTDetrDecoderOutput(ModelOutput):
+ r"""
+ intermediate_hidden_states (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, hidden_size)`):
+ Stacked intermediate hidden states (output of each layer of the decoder).
+ intermediate_logits (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, sequence_length, config.num_labels)`):
+ Stacked intermediate logits (logits of each layer of the decoder).
+ intermediate_reference_points (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, sequence_length, hidden_size)`):
+ Stacked intermediate reference points (reference points of each layer of the decoder).
+ intermediate_predicted_corners (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, 4)`):
+ Stacked intermediate predicted corners (predicted corners of each layer of the decoder).
+ initial_reference_points (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, 4)`):
+ Stacked initial reference points (initial reference points of each layer of the decoder).
+ cross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` and `config.add_cross_attention=True` is passed or when `config.output_attentions=True`):
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
+ sequence_length)`. Attentions weights of the decoder's cross-attention layer, after the attention softmax,
+ used to compute the weighted average in the cross-attention heads.
+ """
+
+ last_hidden_state: torch.FloatTensor | None = None
+ intermediate_hidden_states: torch.FloatTensor | None = None
+ intermediate_logits: torch.FloatTensor | None = None
+ intermediate_reference_points: torch.FloatTensor | None = None
+ intermediate_predicted_corners: torch.FloatTensor | None = None
+ initial_reference_points: torch.FloatTensor | None = None
+ hidden_states: tuple[torch.FloatTensor] | None = None
+ attentions: tuple[torch.FloatTensor] | None = None
+ cross_attentions: tuple[torch.FloatTensor] | None = None
+
+
+@auto_docstring(
+ custom_intro="""
+ Base class for outputs of the RT-DETR encoder-decoder model.
+ """
+)
+@dataclass
+class RTDetrModelOutput(ModelOutput):
+ r"""
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_size)`):
+ Sequence of hidden-states at the output of the last layer of the decoder of the model.
+ intermediate_hidden_states (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, hidden_size)`):
+ Stacked intermediate hidden states (output of each layer of the decoder).
+ intermediate_logits (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, sequence_length, config.num_labels)`):
+ Stacked intermediate logits (logits of each layer of the decoder).
+ intermediate_reference_points (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, 4)`):
+ Stacked intermediate reference points (reference points of each layer of the decoder).
+ intermediate_predicted_corners (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, 4)`):
+ Stacked intermediate predicted corners (predicted corners of each layer of the decoder).
+ initial_reference_points (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)`):
+ Initial reference points used for the first decoder layer.
+ init_reference_points (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)`):
+ Initial reference points sent through the Transformer decoder.
+ enc_topk_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.num_labels)`):
+ Predicted bounding boxes scores where the top `config.two_stage_num_proposals` scoring bounding boxes are
+ picked as region proposals in the encoder stage. Output of bounding box binary classification (i.e.
+ foreground and background).
+ enc_topk_bboxes (`torch.FloatTensor` of shape `(batch_size, sequence_length, 4)`):
+ Logits of predicted bounding boxes coordinates in the encoder stage.
+ enc_outputs_class (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.num_labels)`, *optional*, returned when `config.with_box_refine=True` and `config.two_stage=True`):
+ Predicted bounding boxes scores where the top `config.two_stage_num_proposals` scoring bounding boxes are
+ picked as region proposals in the first stage. Output of bounding box binary classification (i.e.
+ foreground and background).
+ enc_outputs_coord_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, 4)`, *optional*, returned when `config.with_box_refine=True` and `config.two_stage=True`):
+ Logits of predicted bounding boxes coordinates in the first stage.
+ denoising_meta_values (`dict`):
+ Extra dictionary for the denoising related values.
+ """
+
+ last_hidden_state: torch.FloatTensor | None = None
+ intermediate_hidden_states: torch.FloatTensor | None = None
+ intermediate_logits: torch.FloatTensor | None = None
+ intermediate_reference_points: torch.FloatTensor | None = None
+ intermediate_predicted_corners: torch.FloatTensor | None = None
+ initial_reference_points: torch.FloatTensor | None = None
+ decoder_hidden_states: tuple[torch.FloatTensor] | None = None
+ decoder_attentions: tuple[torch.FloatTensor] | None = None
+ cross_attentions: tuple[torch.FloatTensor] | None = None
+ encoder_last_hidden_state: torch.FloatTensor | None = None
+ encoder_hidden_states: tuple[torch.FloatTensor] | None = None
+ encoder_attentions: tuple[torch.FloatTensor] | None = None
+ init_reference_points: torch.FloatTensor | None = None
+ enc_topk_logits: torch.FloatTensor | None = None
+ enc_topk_bboxes: torch.FloatTensor | None = None
+ enc_outputs_class: torch.FloatTensor | None = None
+ enc_outputs_coord_logits: torch.FloatTensor | None = None
+ denoising_meta_values: dict | None = None
+
+
+@auto_docstring(
+ custom_intro="""
+ Output type of [`RTDetrForObjectDetection`].
+ """
+)
+@dataclass
+class RTDetrObjectDetectionOutput(ModelOutput):
+ r"""
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` are provided)):
+ Total loss as a linear combination of a negative log-likehood (cross-entropy) for class prediction and a
+ bounding box loss. The latter is defined as a linear combination of the L1 loss and the generalized
+ scale-invariant IoU loss.
+ loss_dict (`Dict`, *optional*):
+ A dictionary containing the individual losses. Useful for logging.
+ logits (`torch.FloatTensor` of shape `(batch_size, num_queries, num_classes + 1)`):
+ Classification logits (including no-object) for all queries.
+ pred_boxes (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)`):
+ Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height). These
+ values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding
+ possible padding). You can use [`~RTDetrImageProcessor.post_process_object_detection`] to retrieve the
+ unnormalized (absolute) bounding boxes.
+ auxiliary_outputs (`list[Dict]`, *optional*):
+ Optional, only returned when auxiliary losses are activated (i.e. `config.auxiliary_loss` is set to `True`)
+ and labels are provided. It is a list of dictionaries containing the two above keys (`logits` and
+ `pred_boxes`) for each decoder layer.
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_size)`):
+ Sequence of hidden-states at the output of the last layer of the decoder of the model.
+ intermediate_hidden_states (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, hidden_size)`):
+ Stacked intermediate hidden states (output of each layer of the decoder).
+ intermediate_logits (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, config.num_labels)`):
+ Stacked intermediate logits (logits of each layer of the decoder).
+ intermediate_reference_points (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, 4)`):
+ Stacked intermediate reference points (reference points of each layer of the decoder).
+ intermediate_predicted_corners (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, 4)`):
+ Stacked intermediate predicted corners (predicted corners of each layer of the decoder).
+ initial_reference_points (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, 4)`):
+ Stacked initial reference points (initial reference points of each layer of the decoder).
+ init_reference_points (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)`):
+ Initial reference points sent through the Transformer decoder.
+ enc_topk_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.num_labels)`, *optional*, returned when `config.with_box_refine=True` and `config.two_stage=True`):
+ Logits of predicted bounding boxes coordinates in the encoder.
+ enc_topk_bboxes (`torch.FloatTensor` of shape `(batch_size, sequence_length, 4)`, *optional*, returned when `config.with_box_refine=True` and `config.two_stage=True`):
+ Logits of predicted bounding boxes coordinates in the encoder.
+ enc_outputs_class (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.num_labels)`, *optional*, returned when `config.with_box_refine=True` and `config.two_stage=True`):
+ Predicted bounding boxes scores where the top `config.two_stage_num_proposals` scoring bounding boxes are
+ picked as region proposals in the first stage. Output of bounding box binary classification (i.e.
+ foreground and background).
+ enc_outputs_coord_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, 4)`, *optional*, returned when `config.with_box_refine=True` and `config.two_stage=True`):
+ Logits of predicted bounding boxes coordinates in the first stage.
+ denoising_meta_values (`dict`):
+ Extra dictionary for the denoising related values
+ """
+
+ loss: torch.FloatTensor | None = None
+ loss_dict: dict | None = None
+ logits: torch.FloatTensor | None = None
+ pred_boxes: torch.FloatTensor | None = None
+ auxiliary_outputs: list[dict] | None = None
+ last_hidden_state: torch.FloatTensor | None = None
+ intermediate_hidden_states: torch.FloatTensor | None = None
+ intermediate_logits: torch.FloatTensor | None = None
+ intermediate_reference_points: torch.FloatTensor | None = None
+ intermediate_predicted_corners: torch.FloatTensor | None = None
+ initial_reference_points: torch.FloatTensor | None = None
+ decoder_hidden_states: tuple[torch.FloatTensor] | None = None
+ decoder_attentions: tuple[torch.FloatTensor] | None = None
+ cross_attentions: tuple[torch.FloatTensor] | None = None
+ encoder_last_hidden_state: torch.FloatTensor | None = None
+ encoder_hidden_states: tuple[torch.FloatTensor] | None = None
+ encoder_attentions: tuple[torch.FloatTensor] | None = None
+ init_reference_points: tuple[torch.FloatTensor] | None = None
+ enc_topk_logits: torch.FloatTensor | None = None
+ enc_topk_bboxes: torch.FloatTensor | None = None
+ enc_outputs_class: torch.FloatTensor | None = None
+ enc_outputs_coord_logits: torch.FloatTensor | None = None
+ denoising_meta_values: dict | None = None
+
+
+class RTDetrMLP(nn.Module):
+ def __init__(self, config: RTDetrConfig, hidden_size: int, intermediate_size: int, activation_function: str):
+ super().__init__()
+ self.fc1 = nn.Linear(hidden_size, intermediate_size)
+ self.fc2 = nn.Linear(intermediate_size, hidden_size)
+ self.activation_fn = ACT2FN[activation_function]
+ self.activation_dropout = config.activation_dropout
+ self.dropout = config.dropout
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
+ hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
+ hidden_states = self.fc2(hidden_states)
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
+ return hidden_states
+
+
+class RTDetrFrozenBatchNorm2d(DetrFrozenBatchNorm2d):
+ pass
+
+
+class RTDetrSelfAttention(DetrSelfAttention):
+ pass
+
+
+def get_contrastive_denoising_training_group(
+ targets,
+ num_classes,
+ num_queries,
+ class_embed,
+ num_denoising_queries=100,
+ label_noise_ratio=0.5,
+ box_noise_scale=1.0,
+):
+ """
+ Creates a contrastive denoising training group using ground-truth samples. It adds noise to labels and boxes.
+
+ Args:
+ targets (`list[dict]`):
+ The target objects, each containing 'class_labels' and 'boxes' for objects in an image.
+ num_classes (`int`):
+ Total number of classes in the dataset.
+ num_queries (`int`):
+ Number of query slots in the transformer.
+ class_embed (`callable`):
+ A function or a model layer to embed class labels.
+ num_denoising_queries (`int`, *optional*, defaults to 100):
+ Number of denoising queries.
+ label_noise_ratio (`float`, *optional*, defaults to 0.5):
+ Ratio of noise applied to labels.
+ box_noise_scale (`float`, *optional*, defaults to 1.0):
+ Scale of noise applied to bounding boxes.
+ Returns:
+ `tuple` comprising various elements:
+ - **input_query_class** (`torch.FloatTensor`) --
+ Class queries with applied label noise.
+ - **input_query_bbox** (`torch.FloatTensor`) --
+ Bounding box queries with applied box noise.
+ - **attn_mask** (`torch.FloatTensor`) --
+ Attention mask for separating denoising and reconstruction queries.
+ - **denoising_meta_values** (`dict`) --
+ Metadata including denoising positive indices, number of groups, and split sizes.
+ """
+
+ if num_denoising_queries <= 0:
+ return None, None, None, None
+
+ num_ground_truths = [len(t["class_labels"]) for t in targets]
+ device = targets[0]["class_labels"].device
+
+ max_gt_num = max(num_ground_truths)
+ if max_gt_num == 0:
+ return None, None, None, None
+
+ num_groups_denoising_queries = num_denoising_queries // max_gt_num
+ num_groups_denoising_queries = 1 if num_groups_denoising_queries == 0 else num_groups_denoising_queries
+ # pad gt to max_num of a batch
+ batch_size = len(num_ground_truths)
+
+ input_query_class = torch.full([batch_size, max_gt_num], num_classes, dtype=torch.int32, device=device)
+ input_query_bbox = torch.zeros([batch_size, max_gt_num, 4], device=device)
+ pad_gt_mask = torch.zeros([batch_size, max_gt_num], dtype=torch.bool, device=device)
+
+ for i in range(batch_size):
+ num_gt = num_ground_truths[i]
+ if num_gt > 0:
+ input_query_class[i, :num_gt] = targets[i]["class_labels"]
+ input_query_bbox[i, :num_gt] = targets[i]["boxes"]
+ pad_gt_mask[i, :num_gt] = 1
+ # each group has positive and negative queries.
+ input_query_class = input_query_class.tile([1, 2 * num_groups_denoising_queries])
+ input_query_bbox = input_query_bbox.tile([1, 2 * num_groups_denoising_queries, 1])
+ pad_gt_mask = pad_gt_mask.tile([1, 2 * num_groups_denoising_queries])
+ # positive and negative mask
+ negative_gt_mask = torch.zeros([batch_size, max_gt_num * 2, 1], device=device)
+ negative_gt_mask[:, max_gt_num:] = 1
+ negative_gt_mask = negative_gt_mask.tile([1, num_groups_denoising_queries, 1])
+ positive_gt_mask = 1 - negative_gt_mask
+ # contrastive denoising training positive index
+ positive_gt_mask = positive_gt_mask.squeeze(-1) * pad_gt_mask
+ denoise_positive_idx = torch.nonzero(positive_gt_mask)[:, 1]
+ denoise_positive_idx = torch.split(
+ denoise_positive_idx, [n * num_groups_denoising_queries for n in num_ground_truths]
+ )
+ # total denoising queries
+ num_denoising_queries = torch_int(max_gt_num * 2 * num_groups_denoising_queries)
+
+ if label_noise_ratio > 0:
+ mask = torch.rand_like(input_query_class, dtype=torch.float) < (label_noise_ratio * 0.5)
+ # randomly put a new one here
+ new_label = torch.randint_like(mask, 0, num_classes, dtype=input_query_class.dtype)
+ input_query_class = torch.where(mask & pad_gt_mask, new_label, input_query_class)
+
+ if box_noise_scale > 0:
+ known_bbox = center_to_corners_format(input_query_bbox)
+ diff = torch.tile(input_query_bbox[..., 2:] * 0.5, [1, 1, 2]) * box_noise_scale
+ rand_sign = torch.randint_like(input_query_bbox, 0, 2) * 2.0 - 1.0
+ rand_part = torch.rand_like(input_query_bbox)
+ rand_part = (rand_part + 1.0) * negative_gt_mask + rand_part * (1 - negative_gt_mask)
+ rand_part *= rand_sign
+ known_bbox += rand_part * diff
+ known_bbox.clip_(min=0.0, max=1.0)
+ input_query_bbox = corners_to_center_format(known_bbox)
+ input_query_bbox = inverse_sigmoid(input_query_bbox)
+
+ input_query_class = class_embed(input_query_class)
+
+ target_size = num_denoising_queries + num_queries
+ attn_mask = torch.full([target_size, target_size], 0, dtype=torch.float, device=device)
+ # match query cannot see the reconstruction
+ attn_mask[num_denoising_queries:, :num_denoising_queries] = -torch.inf
+
+ # reconstructions cannot see each other
+ for i in range(num_groups_denoising_queries):
+ idx_block_start = max_gt_num * 2 * i
+ idx_block_end = max_gt_num * 2 * (i + 1)
+ attn_mask[idx_block_start:idx_block_end, :idx_block_start] = -torch.inf
+ attn_mask[idx_block_start:idx_block_end, idx_block_end:num_denoising_queries] = -torch.inf
+
+ denoising_meta_values = {
+ "dn_positive_idx": denoise_positive_idx,
+ "dn_num_group": num_groups_denoising_queries,
+ "dn_num_split": [num_denoising_queries, num_queries],
+ }
+
+ return input_query_class, input_query_bbox, attn_mask, denoising_meta_values
+
+
+class RTDetrConvEncoder(nn.Module):
+ """
+ Convolutional backbone using the modeling_rt_detr_resnet.py.
+
+ nn.BatchNorm2d layers are replaced by RTDetrFrozenBatchNorm2d as defined above.
+ https://github.com/lyuwenyu/RT-DETR/blob/main/rtdetr_pytorch/src/nn/backbone/presnet.py#L142
+ """
+
+ def __init__(self, config):
+ super().__init__()
+
+ backbone = load_backbone(config)
+
+ if config.freeze_backbone_batch_norms:
+ # replace batch norm by frozen batch norm
+ with torch.no_grad():
+ replace_batch_norm(backbone)
+ self.model = backbone
+ self.intermediate_channel_sizes = self.model.channels
+
+ def forward(self, pixel_values: torch.Tensor, pixel_mask: torch.Tensor):
+ # send pixel_values through the model to get list of feature maps
+ features = self.model(pixel_values).feature_maps
+
+ out = []
+ for feature_map in features:
+ # downsample pixel_mask to match shape of corresponding feature_map
+ mask = nn.functional.interpolate(pixel_mask[None].float(), size=feature_map.shape[-2:]).to(torch.bool)[0]
+ out.append((feature_map, mask))
+ return out
+
+
+class RTDetrConvNormLayer(nn.Module):
+ def __init__(self, config, in_channels, out_channels, kernel_size, stride, padding=None, activation=None):
+ super().__init__()
+ self.conv = nn.Conv2d(
+ in_channels,
+ out_channels,
+ kernel_size,
+ stride,
+ padding=(kernel_size - 1) // 2 if padding is None else padding,
+ bias=False,
+ )
+ self.norm = nn.BatchNorm2d(out_channels, config.batch_norm_eps)
+ self.activation = nn.Identity() if activation is None else ACT2CLS[activation]()
+
+ def forward(self, hidden_state):
+ hidden_state = self.conv(hidden_state)
+ hidden_state = self.norm(hidden_state)
+ hidden_state = self.activation(hidden_state)
+ return hidden_state
+
+
+class RTDetrEncoderLayer(nn.Module):
+ def __init__(self, config: RTDetrConfig):
+ super().__init__()
+ self.normalize_before = config.normalize_before
+ self.hidden_size = config.encoder_hidden_dim
+
+ # self-attention
+ self.self_attn = RTDetrSelfAttention(
+ config=config,
+ hidden_size=self.hidden_size,
+ num_attention_heads=config.num_attention_heads,
+ dropout=config.dropout,
+ )
+ self.self_attn_layer_norm = nn.LayerNorm(self.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = config.dropout
+ self.mlp = RTDetrMLP(config, self.hidden_size, config.encoder_ffn_dim, config.encoder_activation_function)
+ self.final_layer_norm = nn.LayerNorm(self.hidden_size, eps=config.layer_norm_eps)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor,
+ spatial_position_embeddings: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.Tensor:
+ """
+ Args:
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, hidden_size)`
+ attention_mask (`torch.FloatTensor`): attention mask of size
+ `(batch, 1, target_len, source_len)` where padding elements are indicated by very large negative
+ values.
+ spatial_position_embeddings (`torch.FloatTensor`, *optional*):
+ Spatial position embeddings (2D positional encodings of image locations), to be added to both
+ the queries and keys in self-attention (but not to values).
+ """
+ residual = hidden_states
+ if self.normalize_before:
+ hidden_states = self.self_attn_layer_norm(hidden_states)
+
+ hidden_states, _ = self.self_attn(
+ hidden_states=hidden_states,
+ attention_mask=attention_mask,
+ position_embeddings=spatial_position_embeddings,
+ **kwargs,
+ )
+
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
+ hidden_states = residual + hidden_states
+ if not self.normalize_before:
+ hidden_states = self.self_attn_layer_norm(hidden_states)
+
+ if self.normalize_before:
+ hidden_states = self.final_layer_norm(hidden_states)
+ residual = hidden_states
+
+ hidden_states = self.mlp(hidden_states)
+
+ hidden_states = residual + hidden_states
+ if not self.normalize_before:
+ hidden_states = self.final_layer_norm(hidden_states)
+
+ if self.training:
+ if not torch.isfinite(hidden_states).all():
+ clamp_value = torch.finfo(hidden_states.dtype).max - 1000
+ hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
+
+ return hidden_states
+
+
+class RTDetrRepVggBlock(nn.Module):
+ """
+ RepVGG architecture block introduced by the work "RepVGG: Making VGG-style ConvNets Great Again".
+ """
+
+ def __init__(self, config: RTDetrConfig):
+ super().__init__()
+
+ activation = config.activation_function
+ hidden_channels = int(config.encoder_hidden_dim * config.hidden_expansion)
+ self.conv1 = RTDetrConvNormLayer(config, hidden_channels, hidden_channels, 3, 1, padding=1)
+ self.conv2 = RTDetrConvNormLayer(config, hidden_channels, hidden_channels, 1, 1, padding=0)
+ self.activation = nn.Identity() if activation is None else ACT2CLS[activation]()
+
+ def forward(self, x):
+ y = self.conv1(x) + self.conv2(x)
+ return self.activation(y)
+
+
+class RTDetrCSPRepLayer(nn.Module):
+ """
+ Cross Stage Partial (CSP) network layer with RepVGG blocks.
+ """
+
+ def __init__(self, config: RTDetrConfig):
+ super().__init__()
+
+ in_channels = config.encoder_hidden_dim * 2
+ out_channels = config.encoder_hidden_dim
+ num_blocks = 3
+ activation = config.activation_function
+
+ hidden_channels = int(out_channels * config.hidden_expansion)
+ self.conv1 = RTDetrConvNormLayer(config, in_channels, hidden_channels, 1, 1, activation=activation)
+ self.conv2 = RTDetrConvNormLayer(config, in_channels, hidden_channels, 1, 1, activation=activation)
+ self.bottlenecks = nn.Sequential(*[RTDetrRepVggBlock(config) for _ in range(num_blocks)])
+ if hidden_channels != out_channels:
+ self.conv3 = RTDetrConvNormLayer(config, hidden_channels, out_channels, 1, 1, activation=activation)
+ else:
+ self.conv3 = nn.Identity()
+
+ def forward(self, hidden_state):
+ hidden_state_1 = self.conv1(hidden_state)
+ hidden_state_1 = self.bottlenecks(hidden_state_1)
+ hidden_state_2 = self.conv2(hidden_state)
+ return self.conv3(hidden_state_1 + hidden_state_2)
+
+
+class RTDetrMultiscaleDeformableAttention(DeformableDetrMultiscaleDeformableAttention):
+ pass
+
+
+class RTDetrDecoderLayer(nn.Module):
+ def __init__(self, config: RTDetrConfig):
+ super().__init__()
+ self.hidden_size = config.d_model
+
+ # self-attention
+ self.self_attn = RTDetrSelfAttention(
+ config=config,
+ hidden_size=self.hidden_size,
+ num_attention_heads=config.decoder_attention_heads,
+ dropout=config.attention_dropout,
+ )
+ self.dropout = config.dropout
+
+ self.self_attn_layer_norm = nn.LayerNorm(self.hidden_size, eps=config.layer_norm_eps)
+ # cross-attention
+ self.encoder_attn = RTDetrMultiscaleDeformableAttention(
+ config,
+ num_heads=config.decoder_attention_heads,
+ n_points=config.decoder_n_points,
+ )
+ self.encoder_attn_layer_norm = nn.LayerNorm(self.hidden_size, eps=config.layer_norm_eps)
+ # feedforward neural networks
+ self.mlp = RTDetrMLP(config, self.hidden_size, config.decoder_ffn_dim, config.decoder_activation_function)
+ self.final_layer_norm = nn.LayerNorm(self.hidden_size, eps=config.layer_norm_eps)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ object_queries_position_embeddings: torch.Tensor | None = None,
+ reference_points=None,
+ spatial_shapes=None,
+ spatial_shapes_list=None,
+ level_start_index=None,
+ encoder_hidden_states: torch.Tensor | None = None,
+ encoder_attention_mask: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.Tensor:
+ """
+ Args:
+ hidden_states (`torch.FloatTensor`):
+ Input to the layer of shape `(batch, seq_len, hidden_size)`.
+ object_queries_position_embeddings (`torch.FloatTensor`, *optional*):
+ Position embeddings for the object query slots. These are added to both queries and keys
+ in the self-attention layer (not values).
+ reference_points (`torch.FloatTensor`, *optional*):
+ Reference points.
+ spatial_shapes (`torch.LongTensor`, *optional*):
+ Spatial shapes.
+ level_start_index (`torch.LongTensor`, *optional*):
+ Level start index.
+ encoder_hidden_states (`torch.FloatTensor`):
+ cross attention input to the layer of shape `(batch, seq_len, hidden_size)`
+ encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size
+ `(batch, 1, target_len, source_len)` where padding elements are indicated by very large negative
+ values.
+ """
+ residual = hidden_states
+
+ # Self Attention
+ hidden_states, _ = self.self_attn(
+ hidden_states=hidden_states,
+ attention_mask=encoder_attention_mask,
+ position_embeddings=object_queries_position_embeddings,
+ **kwargs,
+ )
+
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
+ hidden_states = residual + hidden_states
+ hidden_states = self.self_attn_layer_norm(hidden_states)
+
+ residual = hidden_states
+
+ # Cross-Attention
+ hidden_states, _ = self.encoder_attn(
+ hidden_states=hidden_states,
+ encoder_hidden_states=encoder_hidden_states,
+ position_embeddings=object_queries_position_embeddings,
+ reference_points=reference_points,
+ spatial_shapes=spatial_shapes,
+ spatial_shapes_list=spatial_shapes_list,
+ level_start_index=level_start_index,
+ **kwargs,
+ )
+
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
+ hidden_states = residual + hidden_states
+
+ hidden_states = self.encoder_attn_layer_norm(hidden_states)
+
+ # Fully Connected
+ residual = hidden_states
+ hidden_states = self.mlp(hidden_states)
+ hidden_states = residual + hidden_states
+ hidden_states = self.final_layer_norm(hidden_states)
+
+ return hidden_states
+
+
+class RTDetrSinePositionEmbedding(nn.Module):
+ """
+ 2D sinusoidal position embedding used in RT-DETR hybrid encoder.
+ """
+
+ def __init__(self, embed_dim: int = 256, temperature: int = 10000):
+ super().__init__()
+ self.embed_dim = embed_dim
+ self.temperature = temperature
+
+ @staticmethod
+ @compile_compatible_method_lru_cache(maxsize=32)
+ def _cached_build_2d_sinusoidal_position_embedding(*args, **kwargs) -> torch.Tensor:
+ return build_2d_sinusoidal_position_embedding(*args, **kwargs)
+
+ def forward(
+ self,
+ width: int,
+ height: int,
+ device: torch.device | str,
+ dtype: torch.dtype,
+ ) -> torch.Tensor:
+ """
+ Generate 2D sinusoidal position embeddings.
+
+ Returns:
+ Position embeddings of shape (1, height*width, embed_dim)
+ """
+ return self._cached_build_2d_sinusoidal_position_embedding(
+ height=torch_int(height),
+ width=torch_int(width),
+ embed_dim=self.embed_dim,
+ temperature=self.temperature,
+ device=device,
+ dtype=dtype,
+ ).unsqueeze(0)
+
+
+class RTDetrAIFILayer(nn.Module):
+ """
+ AIFI (Attention-based Intra-scale Feature Interaction) layer used in RT-DETR hybrid encoder.
+ """
+
+ def __init__(self, config: RTDetrConfig):
+ super().__init__()
+ self.config = config
+ self.encoder_hidden_dim = config.encoder_hidden_dim
+ self.eval_size = config.eval_size
+
+ self.position_embedding = RTDetrSinePositionEmbedding(
+ embed_dim=self.encoder_hidden_dim,
+ temperature=config.positional_encoding_temperature,
+ )
+ self.layers = nn.ModuleList([RTDetrEncoderLayer(config) for _ in range(config.encoder_layers)])
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.Tensor:
+ """
+ Args:
+ hidden_states (`torch.FloatTensor` of shape `(batch_size, channels, height, width)`):
+ Feature map to process.
+ """
+ batch_size = hidden_states.shape[0]
+ height, width = hidden_states.shape[2:]
+
+ hidden_states = hidden_states.flatten(2).transpose(1, 2)
+
+ if self.training or self.eval_size is None:
+ pos_embed = self.position_embedding(
+ width=width,
+ height=height,
+ device=hidden_states.device,
+ dtype=hidden_states.dtype,
+ )
+ else:
+ pos_embed = None
+
+ for layer in self.layers:
+ hidden_states = layer(
+ hidden_states,
+ attention_mask=None,
+ spatial_position_embeddings=pos_embed,
+ **kwargs,
+ )
+
+ hidden_states = (
+ hidden_states.transpose(1, 2).reshape(batch_size, self.encoder_hidden_dim, height, width).contiguous()
+ )
+
+ return hidden_states
+
+
+class RTDetrMLPPredictionHead(DetrMLPPredictionHead):
+ pass
+
+
+@auto_docstring
+class RTDetrPreTrainedModel(PreTrainedModel):
+ config: RTDetrConfig
+ base_model_prefix = "rt_detr"
+ main_input_name = "pixel_values"
+ input_modalities = ("image",)
+ _no_split_modules = [r"RTDetrHybridEncoder", r"RTDetrDecoderLayer"]
+ _supports_sdpa = True
+ _supports_flash_attn = True
+ _supports_attention_backend = True
+ _supports_flex_attn = True
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ """Initialize the weights"""
+ if isinstance(module, RTDetrForObjectDetection):
+ if module.model.decoder.class_embed is not None:
+ for layer in module.model.decoder.class_embed:
+ prior_prob = self.config.initializer_bias_prior_prob or 1 / (self.config.num_labels + 1)
+ bias = float(-math.log((1 - prior_prob) / prior_prob))
+ init.xavier_uniform_(layer.weight)
+ init.constant_(layer.bias, bias)
+
+ if module.model.decoder.bbox_embed is not None:
+ for layer in module.model.decoder.bbox_embed:
+ init.constant_(layer.layers[-1].weight, 0)
+ init.constant_(layer.layers[-1].bias, 0)
+
+ elif isinstance(module, RTDetrMultiscaleDeformableAttention):
+ init.constant_(module.sampling_offsets.weight, 0.0)
+ default_dtype = torch.get_default_dtype()
+ thetas = torch.arange(module.n_heads, dtype=torch.int64).to(default_dtype) * (
+ 2.0 * math.pi / module.n_heads
+ )
+ grid_init = torch.stack([thetas.cos(), thetas.sin()], -1)
+ grid_init = (
+ (grid_init / grid_init.abs().max(-1, keepdim=True)[0])
+ .view(module.n_heads, 1, 1, 2)
+ .repeat(1, module.n_levels, module.n_points, 1)
+ )
+ for i in range(module.n_points):
+ grid_init[:, :, i, :] *= i + 1
+
+ init.copy_(module.sampling_offsets.bias, grid_init.view(-1))
+ init.constant_(module.attention_weights.weight, 0.0)
+ init.constant_(module.attention_weights.bias, 0.0)
+ init.xavier_uniform_(module.value_proj.weight)
+ init.constant_(module.value_proj.bias, 0.0)
+ init.xavier_uniform_(module.output_proj.weight)
+ init.constant_(module.output_proj.bias, 0.0)
+
+ elif isinstance(module, RTDetrModel):
+ prior_prob = self.config.initializer_bias_prior_prob or 1 / (self.config.num_labels + 1)
+ bias = float(-math.log((1 - prior_prob) / prior_prob))
+ init.xavier_uniform_(module.enc_score_head.weight)
+ init.constant_(module.enc_score_head.bias, bias)
+
+ elif isinstance(module, (nn.Linear, nn.Conv2d, nn.BatchNorm2d)):
+ init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
+ if module.bias is not None:
+ init.zeros_(module.bias)
+ if getattr(module, "running_mean", None) is not None:
+ init.zeros_(module.running_mean)
+ init.ones_(module.running_var)
+ init.zeros_(module.num_batches_tracked)
+
+ elif isinstance(module, nn.LayerNorm):
+ init.ones_(module.weight)
+ init.zeros_(module.bias)
+
+ if hasattr(module, "weight_embedding") and self.config.learn_initial_query:
+ init.xavier_uniform_(module.weight_embedding.weight)
+ if hasattr(module, "denoising_class_embed") and self.config.num_denoising > 0:
+ init.xavier_uniform_(module.denoising_class_embed.weight)
+
+
+class RTDetrHybridEncoder(RTDetrPreTrainedModel):
+ """
+ Hybrid encoder consisting of AIFI (Attention-based Intra-scale Feature Interaction) layers,
+ a top-down Feature Pyramid Network (FPN) and a bottom-up Path Aggregation Network (PAN).
+ More details on the paper: https://huggingface.co/papers/2304.08069
+
+ Args:
+ config: RTDetrConfig
+ """
+
+ _can_record_outputs = {
+ "hidden_states": RTDetrAIFILayer,
+ "attentions": RTDetrSelfAttention,
+ }
+
+ def __init__(self, config: RTDetrConfig):
+ super().__init__(config)
+ self.config = config
+ self.in_channels = config.encoder_in_channels
+ self.feat_strides = config.feat_strides
+ self.encoder_hidden_dim = config.encoder_hidden_dim
+ self.encode_proj_layers = config.encode_proj_layers
+ self.positional_encoding_temperature = config.positional_encoding_temperature
+ self.eval_size = config.eval_size
+ self.out_channels = [self.encoder_hidden_dim for _ in self.in_channels]
+ self.out_strides = self.feat_strides
+ self.num_fpn_stages = len(self.in_channels) - 1
+ self.num_pan_stages = len(self.in_channels) - 1
+
+ # AIFI (Attention-based Intra-scale Feature Interaction) layers
+ self.aifi = nn.ModuleList([RTDetrAIFILayer(config) for _ in range(len(self.encode_proj_layers))])
+
+ # top-down FPN
+ self.lateral_convs = nn.ModuleList()
+ self.fpn_blocks = nn.ModuleList()
+ for _ in range(self.num_fpn_stages):
+ lateral_conv = RTDetrConvNormLayer(
+ config,
+ in_channels=self.encoder_hidden_dim,
+ out_channels=self.encoder_hidden_dim,
+ kernel_size=1,
+ stride=1,
+ activation=config.activation_function,
+ )
+ fpn_block = RTDetrCSPRepLayer(config)
+ self.lateral_convs.append(lateral_conv)
+ self.fpn_blocks.append(fpn_block)
+
+ # bottom-up PAN
+ self.downsample_convs = nn.ModuleList()
+ self.pan_blocks = nn.ModuleList()
+ for _ in range(self.num_pan_stages):
+ downsample_conv = RTDetrConvNormLayer(
+ config,
+ in_channels=self.encoder_hidden_dim,
+ out_channels=self.encoder_hidden_dim,
+ kernel_size=3,
+ stride=2,
+ activation=config.activation_function,
+ )
+ pan_block = RTDetrCSPRepLayer(config)
+ self.downsample_convs.append(downsample_conv)
+ self.pan_blocks.append(pan_block)
+
+ self.post_init()
+
+ @merge_with_config_defaults
+ @capture_outputs(tie_last_hidden_states=False)
+ def forward(
+ self,
+ inputs_embeds=None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> BaseModelOutput:
+ r"""
+ Args:
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
+ Flattened feature map (output of the backbone + projection layer) that is passed to the encoder.
+ """
+ feature_maps = inputs_embeds
+
+ # AIFI: Apply transformer encoder to specified feature levels
+ if self.config.encoder_layers > 0:
+ for i, enc_ind in enumerate(self.encode_proj_layers):
+ feature_maps[enc_ind] = self.aifi[i](feature_maps[enc_ind], **kwargs)
+
+ # top-down FPN
+ fpn_feature_maps = [feature_maps[-1]]
+ for idx, (lateral_conv, fpn_block) in enumerate(zip(self.lateral_convs, self.fpn_blocks)):
+ backbone_feature_map = feature_maps[self.num_fpn_stages - idx - 1]
+ top_fpn_feature_map = fpn_feature_maps[-1]
+ # apply lateral block
+ top_fpn_feature_map = lateral_conv(top_fpn_feature_map)
+ fpn_feature_maps[-1] = top_fpn_feature_map
+ # apply fpn block
+ top_fpn_feature_map = F.interpolate(top_fpn_feature_map, scale_factor=2.0, mode="nearest")
+ fused_feature_map = torch.concat([top_fpn_feature_map, backbone_feature_map], dim=1)
+ new_fpn_feature_map = fpn_block(fused_feature_map)
+ fpn_feature_maps.append(new_fpn_feature_map)
+
+ fpn_feature_maps.reverse()
+
+ # bottom-up PAN
+ pan_feature_maps = [fpn_feature_maps[0]]
+ for idx, (downsample_conv, pan_block) in enumerate(zip(self.downsample_convs, self.pan_blocks)):
+ top_pan_feature_map = pan_feature_maps[-1]
+ fpn_feature_map = fpn_feature_maps[idx + 1]
+ downsampled_feature_map = downsample_conv(top_pan_feature_map)
+ fused_feature_map = torch.concat([downsampled_feature_map, fpn_feature_map], dim=1)
+ new_pan_feature_map = pan_block(fused_feature_map)
+ pan_feature_maps.append(new_pan_feature_map)
+
+ return BaseModelOutput(last_hidden_state=pan_feature_maps)
+
+
+class RTDetrDecoder(RTDetrPreTrainedModel):
+ _can_record_outputs = {
+ "hidden_states": RTDetrDecoderLayer,
+ "attentions": RTDetrSelfAttention,
+ "cross_attentions": RTDetrMultiscaleDeformableAttention,
+ }
+
+ def __init__(self, config: RTDetrConfig):
+ super().__init__(config)
+
+ self.dropout = config.dropout
+ self.layers = nn.ModuleList([RTDetrDecoderLayer(config) for _ in range(config.decoder_layers)])
+ self.query_pos_head = RTDetrMLPPredictionHead(4, 2 * config.d_model, config.d_model, num_layers=2)
+
+ # hack implementation for iterative bounding box refinement and two-stage Deformable DETR
+ self.bbox_embed = None
+ self.class_embed = None
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @merge_with_config_defaults
+ @capture_outputs
+ def forward(
+ self,
+ inputs_embeds=None,
+ encoder_hidden_states=None,
+ encoder_attention_mask=None,
+ reference_points=None,
+ spatial_shapes=None,
+ spatial_shapes_list=None,
+ level_start_index=None,
+ **kwargs: Unpack[TransformersKwargs],
+ ):
+ r"""
+ Args:
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_size)`):
+ The query embeddings that are passed into the decoder.
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
+ of the decoder.
+ encoder_attention_mask (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Mask to avoid performing cross-attention on padding pixel_values of the encoder. Mask values selected
+ in `[0, 1]`:
+ - 1 for pixels that are real (i.e. **not masked**),
+ - 0 for pixels that are padding (i.e. **masked**).
+ reference_points (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)` is `as_two_stage` else `(batch_size, num_queries, 2)` or , *optional*):
+ Reference point in range `[0, 1]`, top-left (0,0), bottom-right (1, 1), including padding area.
+ spatial_shapes (`torch.FloatTensor` of shape `(num_feature_levels, 2)`):
+ Spatial shapes of the feature maps.
+ level_start_index (`torch.LongTensor` of shape `(num_feature_levels)`, *optional*):
+ Indexes for the start of each feature level. In range `[0, sequence_length]`.
+ """
+ if inputs_embeds is not None:
+ hidden_states = inputs_embeds
+
+ # decoder layers
+ intermediate = ()
+ intermediate_reference_points = ()
+ intermediate_logits = ()
+
+ reference_points = F.sigmoid(reference_points)
+
+ # https://github.com/lyuwenyu/RT-DETR/blob/94f5e16708329d2f2716426868ec89aa774af016/rtdetr_pytorch/src/zoo/rtdetr/rtdetr_decoder.py#L252
+ for idx, decoder_layer in enumerate(self.layers):
+ reference_points_input = reference_points.unsqueeze(2)
+ object_queries_position_embeddings = self.query_pos_head(reference_points)
+
+ hidden_states = decoder_layer(
+ hidden_states,
+ object_queries_position_embeddings=object_queries_position_embeddings,
+ encoder_hidden_states=encoder_hidden_states,
+ reference_points=reference_points_input,
+ spatial_shapes=spatial_shapes,
+ spatial_shapes_list=spatial_shapes_list,
+ level_start_index=level_start_index,
+ encoder_attention_mask=encoder_attention_mask,
+ **kwargs,
+ )
+
+ # hack implementation for iterative bounding box refinement
+ if self.bbox_embed is not None:
+ predicted_corners = self.bbox_embed[idx](hidden_states)
+ new_reference_points = F.sigmoid(predicted_corners + inverse_sigmoid(reference_points))
+ reference_points = new_reference_points.detach()
+
+ intermediate += (hidden_states,)
+ intermediate_reference_points += (
+ (new_reference_points,) if self.bbox_embed is not None else (reference_points,)
+ )
+
+ if self.class_embed is not None:
+ logits = self.class_embed[idx](hidden_states)
+ intermediate_logits += (logits,)
+
+ # Keep batch_size as first dimension
+ intermediate = torch.stack(intermediate, dim=1)
+ intermediate_reference_points = torch.stack(intermediate_reference_points, dim=1)
+ if self.class_embed is not None:
+ intermediate_logits = torch.stack(intermediate_logits, dim=1)
+
+ return RTDetrDecoderOutput(
+ last_hidden_state=hidden_states,
+ intermediate_hidden_states=intermediate,
+ intermediate_logits=intermediate_logits,
+ intermediate_reference_points=intermediate_reference_points,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ RT-DETR Model (consisting of a backbone and encoder-decoder) outputting raw hidden states without any head on top.
+ """
+)
+class RTDetrModel(RTDetrPreTrainedModel):
+ def __init__(self, config: RTDetrConfig):
+ super().__init__(config)
+
+ # Create backbone
+ self.backbone = RTDetrConvEncoder(config)
+ intermediate_channel_sizes = self.backbone.intermediate_channel_sizes
+
+ # Create encoder input projection layers
+ # https://github.com/lyuwenyu/RT-DETR/blob/94f5e16708329d2f2716426868ec89aa774af016/rtdetr_pytorch/src/zoo/rtdetr/hybrid_encoder.py#L212
+ num_backbone_outs = len(intermediate_channel_sizes)
+ encoder_input_proj_list = []
+ for i in range(num_backbone_outs):
+ in_channels = intermediate_channel_sizes[i]
+ encoder_input_proj_list.append(
+ nn.Sequential(
+ nn.Conv2d(in_channels, config.encoder_hidden_dim, kernel_size=1, bias=False),
+ nn.BatchNorm2d(config.encoder_hidden_dim),
+ )
+ )
+ self.encoder_input_proj = nn.ModuleList(encoder_input_proj_list)
+
+ # Create encoder
+ self.encoder = RTDetrHybridEncoder(config)
+
+ # denoising part
+ if config.num_denoising > 0:
+ self.denoising_class_embed = nn.Embedding(
+ config.num_labels + 1, config.d_model, padding_idx=config.num_labels
+ )
+
+ # decoder embedding
+ if config.learn_initial_query:
+ self.weight_embedding = nn.Embedding(config.num_queries, config.d_model)
+
+ # encoder head
+ self.enc_output = nn.Sequential(
+ nn.Linear(config.d_model, config.d_model),
+ nn.LayerNorm(config.d_model, eps=config.layer_norm_eps),
+ )
+ self.enc_score_head = nn.Linear(config.d_model, config.num_labels)
+ self.enc_bbox_head = RTDetrMLPPredictionHead(config.d_model, config.d_model, 4, num_layers=3)
+
+ # init encoder output anchors and valid_mask
+ if config.anchor_image_size:
+ self.anchors, self.valid_mask = self.generate_anchors(dtype=self.dtype)
+
+ # Create decoder input projection layers
+ # https://github.com/lyuwenyu/RT-DETR/blob/94f5e16708329d2f2716426868ec89aa774af016/rtdetr_pytorch/src/zoo/rtdetr/rtdetr_decoder.py#L412
+ num_backbone_outs = len(config.decoder_in_channels)
+ decoder_input_proj_list = []
+ for i in range(num_backbone_outs):
+ in_channels = config.decoder_in_channels[i]
+ decoder_input_proj_list.append(
+ nn.Sequential(
+ nn.Conv2d(in_channels, config.d_model, kernel_size=1, bias=False),
+ nn.BatchNorm2d(config.d_model, config.batch_norm_eps),
+ )
+ )
+ for _ in range(config.num_feature_levels - num_backbone_outs):
+ decoder_input_proj_list.append(
+ nn.Sequential(
+ nn.Conv2d(in_channels, config.d_model, kernel_size=3, stride=2, padding=1, bias=False),
+ nn.BatchNorm2d(config.d_model, config.batch_norm_eps),
+ )
+ )
+ in_channels = config.d_model
+ self.decoder_input_proj = nn.ModuleList(decoder_input_proj_list)
+
+ # decoder
+ self.decoder = RTDetrDecoder(config)
+
+ self.post_init()
+
+ def freeze_backbone(self):
+ for param in self.backbone.parameters():
+ param.requires_grad_(False)
+
+ def unfreeze_backbone(self):
+ for param in self.backbone.parameters():
+ param.requires_grad_(True)
+
+ @staticmethod
+ @compile_compatible_method_lru_cache(maxsize=32)
+ def _cached_generate_anchors(
+ spatial_shapes: tuple[tuple[int, int], ...],
+ grid_size: float,
+ device: torch.device | str = "cpu",
+ dtype: torch.dtype = torch.float32,
+ ) -> tuple[torch.Tensor, torch.Tensor]:
+ anchors = []
+ for level, (height, width) in enumerate(spatial_shapes):
+ grid_y, grid_x = torch.meshgrid(
+ torch.arange(end=height, device=device).to(dtype),
+ torch.arange(end=width, device=device).to(dtype),
+ indexing="ij",
+ )
+ grid_xy = torch.stack([grid_x, grid_y], -1)
+ grid_xy = grid_xy.unsqueeze(0) + 0.5
+ grid_xy[..., 0] /= width
+ grid_xy[..., 1] /= height
+ wh = torch.ones_like(grid_xy) * grid_size * (2.0**level)
+ anchors.append(torch.concat([grid_xy, wh], -1).reshape(-1, height * width, 4))
+ # define the valid range for anchor coordinates
+ eps = 1e-2
+ anchors = torch.concat(anchors, 1)
+ valid_mask = ((anchors > eps) * (anchors < 1 - eps)).all(-1, keepdim=True)
+ anchors = torch.log(anchors / (1 - anchors))
+ anchors = torch.where(valid_mask, anchors, torch.tensor(torch.finfo(dtype).max, dtype=dtype, device=device))
+
+ return anchors, valid_mask
+
+ def generate_anchors(self, spatial_shapes=None, grid_size=0.05, device="cpu", dtype=torch.float32):
+ if spatial_shapes is None:
+ spatial_shapes = (
+ (int(self.config.anchor_image_size[0] / s), int(self.config.anchor_image_size[1] / s))
+ for s in self.config.feat_strides
+ )
+ return self._cached_generate_anchors(spatial_shapes, grid_size, device, dtype)
+
+ @auto_docstring
+ @can_return_tuple
+ def forward(
+ self,
+ pixel_values: torch.FloatTensor,
+ pixel_mask: torch.LongTensor | None = None,
+ encoder_outputs: torch.FloatTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: list[dict] | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.FloatTensor] | RTDetrModelOutput:
+ r"""
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
+ Optionally, instead of passing the flattened feature map (output of the backbone + projection layer), you
+ can choose to directly pass a flattened representation of an image.
+ labels (`list[Dict]` of len `(batch_size,)`, *optional*):
+ Labels for computing the bipartite matching loss. List of dicts, each dictionary containing at least the
+ following 2 keys: 'class_labels' and 'boxes' (the class labels and bounding boxes of an image in the batch
+ respectively). The class labels themselves should be a `torch.LongTensor` of len `(number of bounding boxes
+ in the image,)` and the boxes a `torch.FloatTensor` of shape `(number of bounding boxes in the image, 4)`.
+
+ Examples:
+
+ ```python
+ >>> from transformers import AutoImageProcessor, RTDetrModel
+ >>> from PIL import Image
+ >>> import httpx
+ >>> from io import BytesIO
+
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
+ >>> with httpx.stream("GET", url) as response:
+ ... image = Image.open(BytesIO(response.read()))
+
+ >>> image_processor = AutoImageProcessor.from_pretrained("PekingU/rtdetr_r50vd")
+ >>> model = RTDetrModel.from_pretrained("PekingU/rtdetr_r50vd")
+
+ >>> inputs = image_processor(images=image, return_tensors="pt")
+
+ >>> outputs = model(**inputs)
+
+ >>> last_hidden_states = outputs.last_hidden_state
+ >>> list(last_hidden_states.shape)
+ [1, 300, 256]
+ ```"""
+ if pixel_values is None and inputs_embeds is None:
+ raise ValueError("You have to specify either pixel_values or inputs_embeds")
+
+ if inputs_embeds is None:
+ batch_size, num_channels, height, width = pixel_values.shape
+ device = pixel_values.device
+ if pixel_mask is None:
+ pixel_mask = torch.ones(((batch_size, height, width)), device=device)
+ features = self.backbone(pixel_values, pixel_mask)
+ proj_feats = [self.encoder_input_proj[level](source) for level, (source, mask) in enumerate(features)]
+ else:
+ batch_size = inputs_embeds.shape[0]
+ device = inputs_embeds.device
+ proj_feats = inputs_embeds
+
+ if encoder_outputs is None:
+ encoder_outputs = self.encoder(
+ proj_feats,
+ **kwargs,
+ )
+ # If the user passed a tuple for encoder_outputs, we wrap it in a BaseModelOutput
+ elif not isinstance(encoder_outputs, BaseModelOutput):
+ encoder_outputs = BaseModelOutput(
+ last_hidden_state=encoder_outputs[0],
+ hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
+ attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
+ )
+
+ # Equivalent to def _get_encoder_input
+ # https://github.com/lyuwenyu/RT-DETR/blob/94f5e16708329d2f2716426868ec89aa774af016/rtdetr_pytorch/src/zoo/rtdetr/rtdetr_decoder.py#L412
+ sources = []
+ for level, source in enumerate(encoder_outputs.last_hidden_state):
+ sources.append(self.decoder_input_proj[level](source))
+
+ # Lowest resolution feature maps are obtained via 3x3 stride 2 convolutions on the final stage
+ if self.config.num_feature_levels > len(sources):
+ _len_sources = len(sources)
+ sources.append(self.decoder_input_proj[_len_sources](encoder_outputs.last_hidden_state)[-1])
+ for i in range(_len_sources + 1, self.config.num_feature_levels):
+ sources.append(self.decoder_input_proj[i](encoder_outputs.last_hidden_state[-1]))
+
+ # Prepare encoder inputs (by flattening)
+ source_flatten = []
+ spatial_shapes_list = []
+ spatial_shapes = torch.empty((len(sources), 2), device=device, dtype=torch.long)
+ for level, source in enumerate(sources):
+ height, width = source.shape[-2:]
+ spatial_shapes[level, 0] = height
+ spatial_shapes[level, 1] = width
+ spatial_shapes_list.append((height, width))
+ source = source.flatten(2).transpose(1, 2)
+ source_flatten.append(source)
+ source_flatten = torch.cat(source_flatten, 1)
+ level_start_index = torch.cat((spatial_shapes.new_zeros((1,)), spatial_shapes.prod(1).cumsum(0)[:-1]))
+
+ # prepare denoising training
+ if self.training and self.config.num_denoising > 0 and labels is not None:
+ (
+ denoising_class,
+ denoising_bbox_unact,
+ attention_mask,
+ denoising_meta_values,
+ ) = get_contrastive_denoising_training_group(
+ targets=labels,
+ num_classes=self.config.num_labels,
+ num_queries=self.config.num_queries,
+ class_embed=self.denoising_class_embed,
+ num_denoising_queries=self.config.num_denoising,
+ label_noise_ratio=self.config.label_noise_ratio,
+ box_noise_scale=self.config.box_noise_scale,
+ )
+ else:
+ denoising_class, denoising_bbox_unact, attention_mask, denoising_meta_values = None, None, None, None
+
+ batch_size = len(source_flatten)
+ device = source_flatten.device
+ dtype = source_flatten.dtype
+
+ # prepare input for decoder
+ if self.training or self.config.anchor_image_size is None:
+ # Pass spatial_shapes as tuple to make it hashable and make sure
+ # lru_cache is working for generate_anchors()
+ spatial_shapes_tuple = tuple(spatial_shapes_list)
+ anchors, valid_mask = self.generate_anchors(spatial_shapes_tuple, device=device, dtype=dtype)
+ else:
+ anchors, valid_mask = self.anchors, self.valid_mask
+ anchors, valid_mask = anchors.to(device, dtype), valid_mask.to(device, dtype)
+
+ # use the valid_mask to selectively retain values in the feature map where the mask is `True`
+ memory = valid_mask.to(source_flatten.dtype) * source_flatten
+
+ output_memory = self.enc_output(memory)
+
+ enc_outputs_class = self.enc_score_head(output_memory)
+ enc_outputs_coord_logits = self.enc_bbox_head(output_memory) + anchors
+
+ _, topk_ind = torch.topk(enc_outputs_class.max(-1).values, self.config.num_queries, dim=1)
+
+ reference_points_unact = enc_outputs_coord_logits.gather(
+ dim=1, index=topk_ind.unsqueeze(-1).repeat(1, 1, enc_outputs_coord_logits.shape[-1])
+ )
+
+ enc_topk_bboxes = F.sigmoid(reference_points_unact)
+ if denoising_bbox_unact is not None:
+ reference_points_unact = torch.concat([denoising_bbox_unact, reference_points_unact], 1)
+
+ enc_topk_logits = enc_outputs_class.gather(
+ dim=1, index=topk_ind.unsqueeze(-1).repeat(1, 1, enc_outputs_class.shape[-1])
+ )
+
+ # extract region features
+ if self.config.learn_initial_query:
+ target = self.weight_embedding.tile([batch_size, 1, 1])
+ else:
+ target = output_memory.gather(dim=1, index=topk_ind.unsqueeze(-1).repeat(1, 1, output_memory.shape[-1]))
+ target = target.detach()
+
+ if denoising_class is not None:
+ target = torch.concat([denoising_class, target], 1)
+
+ init_reference_points = reference_points_unact.detach()
+
+ # decoder
+ decoder_outputs = self.decoder(
+ inputs_embeds=target,
+ encoder_hidden_states=source_flatten,
+ encoder_attention_mask=attention_mask,
+ reference_points=init_reference_points,
+ spatial_shapes=spatial_shapes,
+ spatial_shapes_list=spatial_shapes_list,
+ level_start_index=level_start_index,
+ **kwargs,
+ )
+
+ return RTDetrModelOutput(
+ last_hidden_state=decoder_outputs.last_hidden_state,
+ intermediate_hidden_states=decoder_outputs.intermediate_hidden_states,
+ intermediate_logits=decoder_outputs.intermediate_logits,
+ intermediate_reference_points=decoder_outputs.intermediate_reference_points,
+ intermediate_predicted_corners=decoder_outputs.intermediate_predicted_corners,
+ initial_reference_points=decoder_outputs.initial_reference_points,
+ decoder_hidden_states=decoder_outputs.hidden_states,
+ decoder_attentions=decoder_outputs.attentions,
+ cross_attentions=decoder_outputs.cross_attentions,
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
+ encoder_hidden_states=encoder_outputs.hidden_states,
+ encoder_attentions=encoder_outputs.attentions,
+ init_reference_points=init_reference_points,
+ enc_topk_logits=enc_topk_logits,
+ enc_topk_bboxes=enc_topk_bboxes,
+ enc_outputs_class=enc_outputs_class,
+ enc_outputs_coord_logits=enc_outputs_coord_logits,
+ denoising_meta_values=denoising_meta_values,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ RT-DETR Model (consisting of a backbone and encoder-decoder) outputting bounding boxes and logits to be further
+ decoded into scores and classes.
+ """
+)
+class RTDetrForObjectDetection(RTDetrPreTrainedModel):
+ # When using clones, all layers > 0 will be clones, but layer 0 *is* required
+ # We can't initialize the model on meta device as some weights are modified during the initialization
+ _no_split_modules = None
+
+ def __init__(self, config: RTDetrConfig):
+ super().__init__(config)
+ self.model = RTDetrModel(config)
+ num_pred = config.decoder_layers
+ self.model.decoder.class_embed = nn.ModuleList(
+ [torch.nn.Linear(config.d_model, config.num_labels) for _ in range(num_pred)]
+ )
+ self.model.decoder.bbox_embed = nn.ModuleList(
+ [RTDetrMLPPredictionHead(config.d_model, config.d_model, 4, num_layers=3) for _ in range(num_pred)]
+ )
+ # if two-stage, the last class_embed and bbox_embed is for region proposal generation
+ self.post_init()
+
+ def _set_aux_loss(self, outputs_class, outputs_coord):
+ return [{"logits": a, "pred_boxes": b} for a, b in zip(outputs_class, outputs_coord)]
+
+ @auto_docstring
+ @can_return_tuple
+ def forward(
+ self,
+ pixel_values: torch.FloatTensor,
+ pixel_mask: torch.LongTensor | None = None,
+ encoder_outputs: torch.FloatTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: list[dict] | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.FloatTensor] | RTDetrObjectDetectionOutput:
+ r"""
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
+ Optionally, instead of passing the flattened feature map (output of the backbone + projection layer), you
+ can choose to directly pass a flattened representation of an image.
+ labels (`list[Dict]` of len `(batch_size,)`, *optional*):
+ Labels for computing the bipartite matching loss. List of dicts, each dictionary containing at least the
+ following 2 keys: 'class_labels' and 'boxes' (the class labels and bounding boxes of an image in the batch
+ respectively). The class labels themselves should be a `torch.LongTensor` of len `(number of bounding boxes
+ in the image,)` and the boxes a `torch.FloatTensor` of shape `(number of bounding boxes in the image, 4)`.
+
+ Examples:
+
+ ```python
+ >>> from transformers import RTDetrImageProcessor, RTDetrForObjectDetection
+ >>> from PIL import Image
+ >>> import httpx
+ >>> from io import BytesIO
+ >>> import torch
+
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
+ >>> with httpx.stream("GET", url) as response:
+ ... image = Image.open(BytesIO(response.read()))
+
+ >>> image_processor = RTDetrImageProcessor.from_pretrained("PekingU/rtdetr_r50vd")
+ >>> model = RTDetrForObjectDetection.from_pretrained("PekingU/rtdetr_r50vd")
+
+ >>> # prepare image for the model
+ >>> inputs = image_processor(images=image, return_tensors="pt")
+
+ >>> # forward pass
+ >>> outputs = model(**inputs)
+
+ >>> logits = outputs.logits
+ >>> list(logits.shape)
+ [1, 300, 80]
+
+ >>> boxes = outputs.pred_boxes
+ >>> list(boxes.shape)
+ [1, 300, 4]
+
+ >>> # convert outputs (bounding boxes and class logits) to Pascal VOC format (xmin, ymin, xmax, ymax)
+ >>> target_sizes = torch.tensor([image.size[::-1]])
+ >>> results = image_processor.post_process_object_detection(outputs, threshold=0.9, target_sizes=target_sizes)[
+ ... 0
+ ... ]
+
+ >>> for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
+ ... box = [round(i, 2) for i in box.tolist()]
+ ... print(
+ ... f"Detected {model.config.id2label[label.item()]} with confidence "
+ ... f"{round(score.item(), 3)} at location {box}"
+ ... )
+ Detected sofa with confidence 0.97 at location [0.14, 0.38, 640.13, 476.21]
+ Detected cat with confidence 0.96 at location [343.38, 24.28, 640.14, 371.5]
+ Detected cat with confidence 0.958 at location [13.23, 54.18, 318.98, 472.22]
+ Detected remote with confidence 0.951 at location [40.11, 73.44, 175.96, 118.48]
+ Detected remote with confidence 0.924 at location [333.73, 76.58, 369.97, 186.99]
+ ```"""
+ outputs = self.model(
+ pixel_values,
+ pixel_mask=pixel_mask,
+ encoder_outputs=encoder_outputs,
+ inputs_embeds=inputs_embeds,
+ labels=labels,
+ **kwargs,
+ )
+
+ denoising_meta_values = outputs.denoising_meta_values if self.training else None
+
+ outputs_class = outputs.intermediate_logits
+ outputs_coord = outputs.intermediate_reference_points
+ predicted_corners = outputs.intermediate_predicted_corners
+ initial_reference_points = outputs.initial_reference_points
+
+ logits = outputs_class[:, -1]
+ pred_boxes = outputs_coord[:, -1]
+
+ loss, loss_dict, auxiliary_outputs, enc_topk_logits, enc_topk_bboxes = None, None, None, None, None
+ if labels is not None:
+ enc_topk_logits = outputs.enc_topk_logits
+ enc_topk_bboxes = outputs.enc_topk_bboxes
+ loss, loss_dict, auxiliary_outputs = self.loss_function(
+ logits,
+ labels,
+ self.device,
+ pred_boxes,
+ self.config,
+ outputs_class,
+ outputs_coord,
+ enc_topk_logits=enc_topk_logits,
+ enc_topk_bboxes=enc_topk_bboxes,
+ denoising_meta_values=denoising_meta_values,
+ predicted_corners=predicted_corners,
+ initial_reference_points=initial_reference_points,
+ **kwargs,
+ )
+
+ return RTDetrObjectDetectionOutput(
+ loss=loss,
+ loss_dict=loss_dict,
+ logits=logits,
+ pred_boxes=pred_boxes,
+ auxiliary_outputs=auxiliary_outputs,
+ last_hidden_state=outputs.last_hidden_state,
+ intermediate_hidden_states=outputs.intermediate_hidden_states,
+ intermediate_logits=outputs.intermediate_logits,
+ intermediate_reference_points=outputs.intermediate_reference_points,
+ intermediate_predicted_corners=outputs.intermediate_predicted_corners,
+ initial_reference_points=outputs.initial_reference_points,
+ decoder_hidden_states=outputs.decoder_hidden_states,
+ decoder_attentions=outputs.decoder_attentions,
+ cross_attentions=outputs.cross_attentions,
+ encoder_last_hidden_state=outputs.encoder_last_hidden_state,
+ encoder_hidden_states=outputs.encoder_hidden_states,
+ encoder_attentions=outputs.encoder_attentions,
+ init_reference_points=outputs.init_reference_points,
+ enc_topk_logits=outputs.enc_topk_logits,
+ enc_topk_bboxes=outputs.enc_topk_bboxes,
+ enc_outputs_class=outputs.enc_outputs_class,
+ enc_outputs_coord_logits=outputs.enc_outputs_coord_logits,
+ denoising_meta_values=outputs.denoising_meta_values,
+ )
+
+
+__all__ = [
+ "RTDetrImageProcessor",
+ "RTDetrImageProcessorPil",
+ "RTDetrForObjectDetection",
+ "RTDetrModel",
+ "RTDetrPreTrainedModel",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/rt_detr_v2/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/rt_detr_v2/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..efc3772ca6d015271102638c3948958777498fd9
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/rt_detr_v2/__init__.py
@@ -0,0 +1,29 @@
+# Copyright 2025 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_rt_detr_v2 import *
+ from .modeling_rt_detr_v2 import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/rt_detr_v2/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/rt_detr_v2/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8c4f991829c62d623f8d66e6d9439954f219d85d
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/rt_detr_v2/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/rt_detr_v2/__pycache__/configuration_rt_detr_v2.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/rt_detr_v2/__pycache__/configuration_rt_detr_v2.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4402bf24471458a830415c928a820f33c48459d3
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/rt_detr_v2/__pycache__/configuration_rt_detr_v2.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/rt_detr_v2/__pycache__/modular_rt_detr_v2.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/rt_detr_v2/__pycache__/modular_rt_detr_v2.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fdf42d2c1ad520b637ca6e9563e439e939b70e6b
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/rt_detr_v2/__pycache__/modular_rt_detr_v2.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/rt_detr_v2/configuration_rt_detr_v2.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/rt_detr_v2/configuration_rt_detr_v2.py
new file mode 100644
index 0000000000000000000000000000000000000000..e888d88c91a12614494b575b8de08329f79ab173
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/rt_detr_v2/configuration_rt_detr_v2.py
@@ -0,0 +1,202 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/rt_detr_v2/modular_rt_detr_v2.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_rt_detr_v2.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2025 Baidu Inc and The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from huggingface_hub.dataclasses import strict
+
+from ...backbone_utils import consolidate_backbone_kwargs_to_config
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring
+from ..auto import AutoConfig
+
+
+@auto_docstring(checkpoint="PekingU/rtdetr_r18vd")
+@strict
+class RTDetrV2Config(PreTrainedConfig):
+ r"""
+ initializer_bias_prior_prob (`float`, *optional*):
+ The prior probability used by the bias initializer to initialize biases for `enc_score_head` and `class_embed`.
+ If `None`, `prior_prob` computed as `prior_prob = 1 / (num_labels + 1)` while initializing model weights.
+ freeze_backbone_batch_norms (`bool`, *optional*, defaults to `True`):
+ Whether to freeze the batch normalization layers in the backbone.
+ encoder_in_channels (`list`, *optional*, defaults to `[512, 1024, 2048]`):
+ Multi level features input for encoder.
+ feat_strides (`list[int]`, *optional*, defaults to `[8, 16, 32]`):
+ Strides used in each feature map.
+ encode_proj_layers (`list[int]`, *optional*, defaults to `[2]`):
+ Indexes of the projected layers to be used in the encoder.
+ positional_encoding_temperature (`int`, *optional*, defaults to 10000):
+ The temperature parameter used to create the positional encodings.
+ encoder_activation_function (`str`, *optional*, defaults to `"gelu"`):
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
+ activation_function (`str`, *optional*, defaults to `"silu"`):
+ The non-linear activation function (function or string) in the general layer. If string, `"gelu"`,
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
+ eval_size (`tuple[int, int]`, *optional*):
+ Height and width used to compute the effective height and width of the position embeddings after taking
+ into account the stride.
+ normalize_before (`bool`, *optional*, defaults to `False`):
+ Determine whether to apply layer normalization in the transformer encoder layer before self-attention and
+ feed-forward modules.
+ hidden_expansion (`float`, *optional*, defaults to 1.0):
+ Expansion ratio to enlarge the dimension size of RepVGGBlock and CSPRepLayer.
+ num_queries (`int`, *optional*, defaults to 300):
+ Number of object queries.
+ decoder_in_channels (`list`, *optional*, defaults to `[256, 256, 256]`):
+ Multi level features dimension for decoder
+ num_feature_levels (`int`, *optional*, defaults to 3):
+ The number of input feature levels.
+ decoder_n_points (`int`, *optional*, defaults to 4):
+ The number of sampled keys in each feature level for each attention head in the decoder.
+ decoder_activation_function (`str`, *optional*, defaults to `"relu"`):
+ The non-linear activation function (function or string) in the decoder. If string, `"gelu"`,
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
+ num_denoising (`int`, *optional*, defaults to 100):
+ The total number of denoising tasks or queries to be used for contrastive denoising.
+ label_noise_ratio (`float`, *optional*, defaults to 0.5):
+ The fraction of denoising labels to which random noise should be added.
+ box_noise_scale (`float`, *optional*, defaults to 1.0):
+ Scale or magnitude of noise to be added to the bounding boxes.
+ learn_initial_query (`bool`, *optional*, defaults to `False`):
+ Indicates whether the initial query embeddings for the decoder should be learned during training
+ anchor_image_size (`tuple[int, int]`, *optional*):
+ Height and width of the input image used during evaluation to generate the bounding box anchors. If None, automatic generate anchor is applied.
+ with_box_refine (`bool`, *optional*, defaults to `True`):
+ Whether to apply iterative bounding box refinement, where each decoder layer refines the bounding boxes
+ based on the predictions from the previous layer.
+ matcher_alpha (`float`, *optional*, defaults to 0.25):
+ Parameter alpha used by the Hungarian Matcher.
+ matcher_gamma (`float`, *optional*, defaults to 2.0):
+ Parameter gamma used by the Hungarian Matcher.
+ matcher_class_cost (`float`, *optional*, defaults to 2.0):
+ The relative weight of the class loss used by the Hungarian Matcher.
+ matcher_bbox_cost (`float`, *optional*, defaults to 5.0):
+ The relative weight of the bounding box loss used by the Hungarian Matcher.
+ matcher_giou_cost (`float`, *optional*, defaults to 2.0):
+ The relative weight of the giou loss of used by the Hungarian Matcher.
+ use_focal_loss (`bool`, *optional*, defaults to `True`):
+ Parameter informing if focal loss should be used.
+ focal_loss_alpha (`float`, *optional*, defaults to 0.75):
+ Parameter alpha used to compute the focal loss.
+ focal_loss_gamma (`float`, *optional*, defaults to 2.0):
+ Parameter gamma used to compute the focal loss.
+ weight_loss_vfl (`float`, *optional*, defaults to 1.0):
+ Relative weight of the varifocal loss in the object detection loss.
+ weight_loss_bbox (`float`, *optional*, defaults to 5.0):
+ Relative weight of the L1 bounding box loss in the object detection loss.
+ weight_loss_giou (`float`, *optional*, defaults to 2.0):
+ Relative weight of the generalized IoU loss in the object detection loss.
+ decoder_n_levels (`int`, *optional*, defaults to 3):
+ The number of feature levels used by the decoder.
+ decoder_offset_scale (`float`, *optional*, defaults to 0.5):
+ Scaling factor applied to the attention offsets in the decoder.
+ decoder_method (`str`, *optional*, defaults to `"default"`):
+ The method to use for the decoder: `"default"` or `"discrete"`.
+
+ Examples:
+
+ ```python
+ >>> from transformers import RTDetrV2Config, RTDetrV2Model
+
+ >>> # Initializing a RT-DETR configuration
+ >>> configuration = RTDetrV2Config()
+
+ >>> # Initializing a model (with random weights) from the configuration
+ >>> model = RTDetrV2Model(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```
+ """
+
+ model_type = "rt_detr_v2"
+ sub_configs = {"backbone_config": AutoConfig}
+ layer_types = ["basic", "bottleneck"]
+ attribute_map = {
+ "hidden_size": "d_model",
+ "num_attention_heads": "encoder_attention_heads",
+ }
+
+ initializer_range: float = 0.01
+ initializer_bias_prior_prob: float | None = None
+ layer_norm_eps: float = 1e-5
+ batch_norm_eps: float = 1e-5
+ backbone_config: dict | PreTrainedConfig | None = None
+ freeze_backbone_batch_norms: bool = True
+ encoder_hidden_dim: int = 256
+ encoder_in_channels: list[int] | tuple[int, ...] = (512, 1024, 2048)
+ feat_strides: list[int] | tuple[int, ...] = (8, 16, 32)
+ encoder_layers: int = 1
+ encoder_ffn_dim: int = 1024
+ encoder_attention_heads: int = 8
+ dropout: float | int = 0.0
+ activation_dropout: float | int = 0.0
+ encode_proj_layers: list[int] | tuple[int, ...] = (2,)
+ positional_encoding_temperature: int = 10000
+ encoder_activation_function: str = "gelu"
+ activation_function: str = "silu"
+ eval_size: int | None = None
+ normalize_before: bool = False
+ hidden_expansion: float = 1.0
+ d_model: int = 256
+ num_queries: int = 300
+ decoder_in_channels: list[int] | tuple[int, ...] = (256, 256, 256)
+ decoder_ffn_dim: int = 1024
+ num_feature_levels: int = 3
+ decoder_n_points: int = 4
+ decoder_layers: int = 6
+ decoder_attention_heads: int = 8
+ decoder_activation_function: str = "relu"
+ attention_dropout: float | int = 0.0
+ num_denoising: int = 100
+ label_noise_ratio: float = 0.5
+ box_noise_scale: float = 1.0
+ learn_initial_query: bool = False
+ anchor_image_size: int | list[int] | None = None
+ with_box_refine: bool = True
+ is_encoder_decoder: bool = True
+ matcher_alpha: float = 0.25
+ matcher_gamma: float = 2.0
+ matcher_class_cost: float = 2.0
+ matcher_bbox_cost: float = 5.0
+ matcher_giou_cost: float = 2.0
+ use_focal_loss: bool = True
+ auxiliary_loss: bool = True
+ focal_loss_alpha: float = 0.75
+ focal_loss_gamma: float = 2.0
+ weight_loss_vfl: float = 1.0
+ weight_loss_bbox: float = 5.0
+ weight_loss_giou: float = 2.0
+ eos_coefficient: float = 1e-4
+ decoder_n_levels: int = 3
+ decoder_offset_scale: float = 0.5
+ decoder_method: str = "default"
+ tie_word_embeddings: bool = True
+
+ def __post_init__(self, **kwargs):
+ self.backbone_config, kwargs = consolidate_backbone_kwargs_to_config(
+ backbone_config=self.backbone_config,
+ default_config_type="rt_detr_resnet",
+ default_config_kwargs={"out_indices": [2, 3, 4]},
+ **kwargs,
+ )
+ super().__post_init__(**kwargs)
+
+
+__all__ = ["RTDetrV2Config"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/rt_detr_v2/modeling_rt_detr_v2.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/rt_detr_v2/modeling_rt_detr_v2.py
new file mode 100644
index 0000000000000000000000000000000000000000..d2115a49cb5cc67dfafb8692be8678a2c7861f2c
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/rt_detr_v2/modeling_rt_detr_v2.py
@@ -0,0 +1,1933 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/rt_detr_v2/modular_rt_detr_v2.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_rt_detr_v2.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2025 Baidu Inc and The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import math
+import warnings
+from collections.abc import Callable
+from dataclasses import dataclass
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from torch import Tensor
+
+from ... import initialization as init
+from ...activations import ACT2CLS, ACT2FN
+from ...backbone_utils import load_backbone
+from ...image_transforms import center_to_corners_format, corners_to_center_format
+from ...modeling_outputs import BaseModelOutput
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
+from ...processing_utils import Unpack
+from ...pytorch_utils import compile_compatible_method_lru_cache
+from ...utils import ModelOutput, TransformersKwargs, auto_docstring, torch_compilable_check, torch_int
+from ...utils.generic import can_return_tuple, merge_with_config_defaults
+from ...utils.output_capturing import capture_outputs
+from .configuration_rt_detr_v2 import RTDetrV2Config
+
+
+def multi_scale_deformable_attention_v2(
+ value: Tensor,
+ value_spatial_shapes: Tensor,
+ sampling_locations: Tensor,
+ attention_weights: Tensor,
+ num_points_list: list[int],
+ method="default",
+) -> Tensor:
+ batch_size, _, num_heads, hidden_dim = value.shape
+ _, num_queries, num_heads, num_levels, num_points = sampling_locations.shape
+ value_list = (
+ value.permute(0, 2, 3, 1)
+ .flatten(0, 1)
+ .split([height * width for height, width in value_spatial_shapes], dim=-1)
+ )
+ # sampling_offsets [8, 480, 8, 12, 2]
+ if method == "default":
+ sampling_grids = 2 * sampling_locations - 1
+ elif method == "discrete":
+ sampling_grids = sampling_locations
+ sampling_grids = sampling_grids.permute(0, 2, 1, 3, 4).flatten(0, 1)
+ sampling_grids = sampling_grids.split(num_points_list, dim=-2)
+ sampling_value_list = []
+ for level_id, (height, width) in enumerate(value_spatial_shapes):
+ # batch_size, height*width, num_heads, hidden_dim
+ # -> batch_size, height*width, num_heads*hidden_dim
+ # -> batch_size, num_heads*hidden_dim, height*width
+ # -> batch_size*num_heads, hidden_dim, height, width
+ value_l_ = value_list[level_id].reshape(batch_size * num_heads, hidden_dim, height, width)
+ # batch_size, num_queries, num_heads, num_points, 2
+ # -> batch_size, num_heads, num_queries, num_points, 2
+ # -> batch_size*num_heads, num_queries, num_points, 2
+ sampling_grid_l_ = sampling_grids[level_id]
+ # batch_size*num_heads, hidden_dim, num_queries, num_points
+ if method == "default":
+ sampling_value_l_ = nn.functional.grid_sample(
+ value_l_, sampling_grid_l_, mode="bilinear", padding_mode="zeros", align_corners=False
+ )
+ elif method == "discrete":
+ sampling_coord = (sampling_grid_l_ * torch.tensor([[width, height]], device=value.device) + 0.5).to(
+ torch.int64
+ )
+
+ # Separate clamping for x and y coordinates
+ sampling_coord_x = sampling_coord[..., 0].clamp(0, width - 1)
+ sampling_coord_y = sampling_coord[..., 1].clamp(0, height - 1)
+
+ # Combine the clamped coordinates
+ sampling_coord = torch.stack([sampling_coord_x, sampling_coord_y], dim=-1)
+ sampling_coord = sampling_coord.reshape(batch_size * num_heads, num_queries * num_points_list[level_id], 2)
+ sampling_idx = (
+ torch.arange(sampling_coord.shape[0], device=value.device)
+ .unsqueeze(-1)
+ .repeat(1, sampling_coord.shape[1])
+ )
+ sampling_value_l_ = value_l_[sampling_idx, :, sampling_coord[..., 1], sampling_coord[..., 0]]
+ sampling_value_l_ = sampling_value_l_.transpose(1, 2).reshape(
+ batch_size * num_heads, hidden_dim, num_queries, num_points_list[level_id]
+ )
+ sampling_value_list.append(sampling_value_l_)
+ # (batch_size, num_queries, num_heads, num_levels, num_points)
+ # -> (batch_size, num_heads, num_queries, num_levels, num_points)
+ # -> (batch_size, num_heads, 1, num_queries, num_levels*num_points)
+ attention_weights = attention_weights.permute(0, 2, 1, 3).reshape(
+ batch_size * num_heads, 1, num_queries, sum(num_points_list)
+ )
+ output = (
+ (torch.concat(sampling_value_list, dim=-1) * attention_weights)
+ .sum(-1)
+ .view(batch_size, num_heads * hidden_dim, num_queries)
+ )
+ return output.transpose(1, 2).contiguous()
+
+
+# the main change
+class RTDetrV2MultiscaleDeformableAttention(nn.Module):
+ """
+ RTDetrV2 version of multiscale deformable attention, extending the base implementation
+ with improved offset handling and initialization.
+ """
+
+ def __init__(self, config: RTDetrV2Config):
+ super().__init__()
+ num_heads = config.decoder_attention_heads
+ n_points = config.decoder_n_points
+
+ if config.d_model % num_heads != 0:
+ raise ValueError(
+ f"embed_dim (d_model) must be divisible by num_heads, but got {config.d_model} and {num_heads}"
+ )
+ dim_per_head = config.d_model // num_heads
+ # check if dim_per_head is power of 2
+ if not ((dim_per_head & (dim_per_head - 1) == 0) and dim_per_head != 0):
+ warnings.warn(
+ "You'd better set embed_dim (d_model) in RTDetrV2MultiscaleDeformableAttention to make the"
+ " dimension of each attention head a power of 2 which is more efficient in the authors' CUDA"
+ " implementation."
+ )
+
+ self.im2col_step = 64
+
+ self.d_model = config.d_model
+
+ # V2-specific attributes
+ self.n_levels = config.decoder_n_levels
+ self.n_heads = num_heads
+ self.n_points = n_points
+
+ self.sampling_offsets = nn.Linear(config.d_model, num_heads * self.n_levels * n_points * 2)
+ self.attention_weights = nn.Linear(config.d_model, num_heads * self.n_levels * n_points)
+ self.value_proj = nn.Linear(config.d_model, config.d_model)
+ self.output_proj = nn.Linear(config.d_model, config.d_model)
+
+ self.offset_scale = config.decoder_offset_scale
+ self.method = config.decoder_method
+
+ # Initialize n_points list and scale
+ n_points_list = [self.n_points for _ in range(self.n_levels)]
+ self.n_points_list = n_points_list
+ n_points_scale = [1 / n for n in n_points_list for _ in range(n)]
+ self.register_buffer("n_points_scale", torch.tensor(n_points_scale, dtype=torch.float32))
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor | None = None,
+ encoder_hidden_states=None,
+ encoder_attention_mask=None,
+ position_embeddings: torch.Tensor | None = None,
+ reference_points=None,
+ spatial_shapes=None,
+ spatial_shapes_list=None,
+ level_start_index=None,
+ **kwargs: Unpack[TransformersKwargs],
+ ):
+ # Process inputs up to sampling locations calculation using parent class logic
+ if position_embeddings is not None:
+ hidden_states = hidden_states + position_embeddings
+
+ batch_size, num_queries, _ = hidden_states.shape
+ batch_size, sequence_length, _ = encoder_hidden_states.shape
+ torch_compilable_check(
+ (spatial_shapes[:, 0] * spatial_shapes[:, 1]).sum() == sequence_length,
+ "Make sure to align the spatial shapes with the sequence length of the encoder hidden states",
+ )
+
+ value = self.value_proj(encoder_hidden_states)
+ if attention_mask is not None:
+ value = value.masked_fill(~attention_mask[..., None], float(0))
+ value = value.view(batch_size, sequence_length, self.n_heads, self.d_model // self.n_heads)
+
+ # V2-specific sampling offsets shape
+ sampling_offsets = self.sampling_offsets(hidden_states).view(
+ batch_size, num_queries, self.n_heads, self.n_levels * self.n_points, 2
+ )
+
+ attention_weights = self.attention_weights(hidden_states).view(
+ batch_size, num_queries, self.n_heads, self.n_levels * self.n_points
+ )
+ attention_weights = F.softmax(attention_weights, -1)
+
+ # V2-specific sampling locations calculation
+ if reference_points.shape[-1] == 2:
+ offset_normalizer = torch.stack([spatial_shapes[..., 1], spatial_shapes[..., 0]], -1)
+ sampling_locations = (
+ reference_points[:, :, None, :, None, :]
+ + sampling_offsets / offset_normalizer[None, None, None, :, None, :]
+ )
+ elif reference_points.shape[-1] == 4:
+ n_points_scale = self.n_points_scale.to(dtype=hidden_states.dtype).unsqueeze(-1)
+ offset = sampling_offsets * n_points_scale * reference_points[:, :, None, :, 2:] * self.offset_scale
+ sampling_locations = reference_points[:, :, None, :, :2] + offset
+ else:
+ raise ValueError(f"Last dim of reference_points must be 2 or 4, but got {reference_points.shape[-1]}")
+
+ # V2-specific attention implementation choice
+ output = multi_scale_deformable_attention_v2(
+ value, spatial_shapes_list, sampling_locations, attention_weights, self.n_points_list, self.method
+ )
+
+ output = self.output_proj(output)
+ return output, attention_weights
+
+
+class RTDetrV2MLP(nn.Module):
+ def __init__(self, config: RTDetrV2Config, hidden_size: int, intermediate_size: int, activation_function: str):
+ super().__init__()
+ self.fc1 = nn.Linear(hidden_size, intermediate_size)
+ self.fc2 = nn.Linear(intermediate_size, hidden_size)
+ self.activation_fn = ACT2FN[activation_function]
+ self.activation_dropout = config.activation_dropout
+ self.dropout = config.dropout
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
+ hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
+ hidden_states = self.fc2(hidden_states)
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
+ return hidden_states
+
+
+def eager_attention_forward(
+ module: nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: torch.Tensor | None,
+ scaling: float | None = None,
+ dropout: float = 0.0,
+ **kwargs: Unpack[TransformersKwargs],
+):
+ if scaling is None:
+ scaling = query.size(-1) ** -0.5
+
+ # Take the dot product between "query" and "key" to get the raw attention scores.
+ attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
+
+ if attention_mask is not None:
+ attn_weights = attn_weights + attention_mask
+
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
+
+ attn_output = torch.matmul(attn_weights, value)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+
+ return attn_output, attn_weights
+
+
+class RTDetrV2SelfAttention(nn.Module):
+ """
+ Multi-headed self-attention from 'Attention Is All You Need' paper.
+
+ In RT_DETR_V2, position embeddings are added to both queries and keys (but not values) in self-attention.
+ """
+
+ def __init__(
+ self,
+ config: RTDetrV2Config,
+ hidden_size: int,
+ num_attention_heads: int,
+ dropout: float = 0.0,
+ bias: bool = True,
+ ):
+ super().__init__()
+ self.config = config
+ self.head_dim = hidden_size // num_attention_heads
+ self.scaling = self.head_dim**-0.5
+ self.attention_dropout = dropout
+ self.is_causal = False
+
+ self.k_proj = nn.Linear(hidden_size, hidden_size, bias=bias)
+ self.v_proj = nn.Linear(hidden_size, hidden_size, bias=bias)
+ self.q_proj = nn.Linear(hidden_size, hidden_size, bias=bias)
+ self.o_proj = nn.Linear(hidden_size, hidden_size, bias=bias)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor | None = None,
+ position_embeddings: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor, torch.Tensor]:
+ """
+ Position embeddings are added to both queries and keys (but not values).
+ """
+ input_shape = hidden_states.shape[:-1]
+ hidden_shape = (*input_shape, -1, self.head_dim)
+
+ query_key_input = hidden_states + position_embeddings if position_embeddings is not None else hidden_states
+
+ query_states = self.q_proj(query_key_input).view(hidden_shape).transpose(1, 2)
+ key_states = self.k_proj(query_key_input).view(hidden_shape).transpose(1, 2)
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_states,
+ key_states,
+ value_states,
+ attention_mask,
+ dropout=0.0 if not self.training else self.attention_dropout,
+ scaling=self.scaling,
+ **kwargs,
+ )
+
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ attn_output = self.o_proj(attn_output)
+ return attn_output, attn_weights
+
+
+class RTDetrV2DecoderLayer(nn.Module):
+ def __init__(self, config: RTDetrV2Config):
+ super().__init__()
+ self.hidden_size = config.d_model
+
+ # self-attention
+ self.self_attn = RTDetrV2SelfAttention(
+ config=config,
+ hidden_size=self.hidden_size,
+ num_attention_heads=config.decoder_attention_heads,
+ dropout=config.attention_dropout,
+ )
+ self.dropout = config.dropout
+
+ self.self_attn_layer_norm = nn.LayerNorm(self.hidden_size, eps=config.layer_norm_eps)
+ # override only the encoder attention module with v2 version
+ self.encoder_attn = RTDetrV2MultiscaleDeformableAttention(config)
+ self.encoder_attn_layer_norm = nn.LayerNorm(self.hidden_size, eps=config.layer_norm_eps)
+ # feedforward neural networks
+ self.mlp = RTDetrV2MLP(config, self.hidden_size, config.decoder_ffn_dim, config.decoder_activation_function)
+ self.final_layer_norm = nn.LayerNorm(self.hidden_size, eps=config.layer_norm_eps)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ object_queries_position_embeddings: torch.Tensor | None = None,
+ reference_points=None,
+ spatial_shapes=None,
+ spatial_shapes_list=None,
+ level_start_index=None,
+ encoder_hidden_states: torch.Tensor | None = None,
+ encoder_attention_mask: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.Tensor:
+ """
+ Args:
+ hidden_states (`torch.FloatTensor`):
+ Input to the layer of shape `(batch, seq_len, hidden_size)`.
+ object_queries_position_embeddings (`torch.FloatTensor`, *optional*):
+ Position embeddings for the object query slots. These are added to both queries and keys
+ in the self-attention layer (not values).
+ reference_points (`torch.FloatTensor`, *optional*):
+ Reference points.
+ spatial_shapes (`torch.LongTensor`, *optional*):
+ Spatial shapes.
+ level_start_index (`torch.LongTensor`, *optional*):
+ Level start index.
+ encoder_hidden_states (`torch.FloatTensor`):
+ cross attention input to the layer of shape `(batch, seq_len, hidden_size)`
+ encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size
+ `(batch, 1, target_len, source_len)` where padding elements are indicated by very large negative
+ values.
+ """
+ residual = hidden_states
+
+ # Self Attention
+ hidden_states, _ = self.self_attn(
+ hidden_states=hidden_states,
+ attention_mask=encoder_attention_mask,
+ position_embeddings=object_queries_position_embeddings,
+ **kwargs,
+ )
+
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
+ hidden_states = residual + hidden_states
+ hidden_states = self.self_attn_layer_norm(hidden_states)
+
+ residual = hidden_states
+
+ # Cross-Attention
+ hidden_states, _ = self.encoder_attn(
+ hidden_states=hidden_states,
+ encoder_hidden_states=encoder_hidden_states,
+ position_embeddings=object_queries_position_embeddings,
+ reference_points=reference_points,
+ spatial_shapes=spatial_shapes,
+ spatial_shapes_list=spatial_shapes_list,
+ level_start_index=level_start_index,
+ **kwargs,
+ )
+
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
+ hidden_states = residual + hidden_states
+
+ hidden_states = self.encoder_attn_layer_norm(hidden_states)
+
+ # Fully Connected
+ residual = hidden_states
+ hidden_states = self.mlp(hidden_states)
+ hidden_states = residual + hidden_states
+ hidden_states = self.final_layer_norm(hidden_states)
+
+ return hidden_states
+
+
+@auto_docstring
+class RTDetrV2PreTrainedModel(PreTrainedModel):
+ config: RTDetrV2Config
+ base_model_prefix = "rt_detr_v2"
+ main_input_name = "pixel_values"
+ input_modalities = ("image",)
+ _no_split_modules = [r"RTDetrV2HybridEncoder", r"RTDetrV2DecoderLayer"]
+ _supports_sdpa = True
+ _supports_flash_attn = True
+ _supports_attention_backend = True
+ _supports_flex_attn = True
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ """Initialize the weights"""
+ if isinstance(module, RTDetrV2ForObjectDetection):
+ if module.model.decoder.class_embed is not None:
+ for layer in module.model.decoder.class_embed:
+ prior_prob = self.config.initializer_bias_prior_prob or 1 / (self.config.num_labels + 1)
+ bias = float(-math.log((1 - prior_prob) / prior_prob))
+ init.xavier_uniform_(layer.weight)
+ init.constant_(layer.bias, bias)
+
+ if module.model.decoder.bbox_embed is not None:
+ for layer in module.model.decoder.bbox_embed:
+ init.constant_(layer.layers[-1].weight, 0)
+ init.constant_(layer.layers[-1].bias, 0)
+
+ elif isinstance(module, RTDetrV2MultiscaleDeformableAttention):
+ init.constant_(module.sampling_offsets.weight, 0.0)
+ default_dtype = torch.get_default_dtype()
+ thetas = torch.arange(module.n_heads, dtype=torch.int64).to(default_dtype) * (
+ 2.0 * math.pi / module.n_heads
+ )
+ grid_init = torch.stack([thetas.cos(), thetas.sin()], -1)
+ grid_init = (
+ (grid_init / grid_init.abs().max(-1, keepdim=True)[0])
+ .view(module.n_heads, 1, 1, 2)
+ .repeat(1, module.n_levels, module.n_points, 1)
+ )
+ for i in range(module.n_points):
+ grid_init[:, :, i, :] *= i + 1
+
+ init.copy_(module.sampling_offsets.bias, grid_init.view(-1))
+ init.constant_(module.attention_weights.weight, 0.0)
+ init.constant_(module.attention_weights.bias, 0.0)
+ init.xavier_uniform_(module.value_proj.weight)
+ init.constant_(module.value_proj.bias, 0.0)
+ init.xavier_uniform_(module.output_proj.weight)
+ init.constant_(module.output_proj.bias, 0.0)
+
+ elif isinstance(module, RTDetrV2Model):
+ prior_prob = self.config.initializer_bias_prior_prob or 1 / (self.config.num_labels + 1)
+ bias = float(-math.log((1 - prior_prob) / prior_prob))
+ init.xavier_uniform_(module.enc_score_head.weight)
+ init.constant_(module.enc_score_head.bias, bias)
+
+ elif isinstance(module, (nn.Linear, nn.Conv2d, nn.BatchNorm2d)):
+ init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
+ if module.bias is not None:
+ init.zeros_(module.bias)
+ if getattr(module, "running_mean", None) is not None:
+ init.zeros_(module.running_mean)
+ init.ones_(module.running_var)
+ init.zeros_(module.num_batches_tracked)
+
+ elif isinstance(module, nn.LayerNorm):
+ init.ones_(module.weight)
+ init.zeros_(module.bias)
+
+ if hasattr(module, "weight_embedding") and self.config.learn_initial_query:
+ init.xavier_uniform_(module.weight_embedding.weight)
+ if hasattr(module, "denoising_class_embed") and self.config.num_denoising > 0:
+ init.xavier_uniform_(module.denoising_class_embed.weight)
+ if isinstance(module, RTDetrV2MultiscaleDeformableAttention):
+ n_points_scale = [1 / n for n in module.n_points_list for _ in range(n)]
+ init.copy_(module.n_points_scale, torch.tensor(n_points_scale, dtype=torch.float32))
+
+
+@auto_docstring(
+ custom_intro="""
+ Base class for outputs of the RTDetrV2Decoder. This class adds two attributes to
+ BaseModelOutputWithCrossAttentions, namely:
+ - a stacked tensor of intermediate decoder hidden states (i.e. the output of each decoder layer)
+ - a stacked tensor of intermediate reference points.
+ """
+)
+@dataclass
+class RTDetrV2DecoderOutput(ModelOutput):
+ r"""
+ intermediate_hidden_states (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, hidden_size)`):
+ Stacked intermediate hidden states (output of each layer of the decoder).
+ intermediate_logits (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, sequence_length, config.num_labels)`):
+ Stacked intermediate logits (logits of each layer of the decoder).
+ intermediate_reference_points (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, sequence_length, hidden_size)`):
+ Stacked intermediate reference points (reference points of each layer of the decoder).
+ intermediate_predicted_corners (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, 4)`):
+ Stacked intermediate predicted corners (predicted corners of each layer of the decoder).
+ initial_reference_points (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, 4)`):
+ Stacked initial reference points (initial reference points of each layer of the decoder).
+ cross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` and `config.add_cross_attention=True` is passed or when `config.output_attentions=True`):
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
+ sequence_length)`. Attentions weights of the decoder's cross-attention layer, after the attention softmax,
+ used to compute the weighted average in the cross-attention heads.
+ """
+
+ last_hidden_state: torch.FloatTensor | None = None
+ intermediate_hidden_states: torch.FloatTensor | None = None
+ intermediate_logits: torch.FloatTensor | None = None
+ intermediate_reference_points: torch.FloatTensor | None = None
+ intermediate_predicted_corners: torch.FloatTensor | None = None
+ initial_reference_points: torch.FloatTensor | None = None
+ hidden_states: tuple[torch.FloatTensor] | None = None
+ attentions: tuple[torch.FloatTensor] | None = None
+ cross_attentions: tuple[torch.FloatTensor] | None = None
+
+
+def inverse_sigmoid(x, eps=1e-5):
+ x = x.clamp(min=0, max=1)
+ x1 = x.clamp(min=eps)
+ x2 = (1 - x).clamp(min=eps)
+ return torch.log(x1 / x2)
+
+
+class RTDetrV2Decoder(RTDetrV2PreTrainedModel):
+ _can_record_outputs = {
+ "hidden_states": RTDetrV2DecoderLayer,
+ "attentions": RTDetrV2SelfAttention,
+ "cross_attentions": RTDetrV2MultiscaleDeformableAttention,
+ }
+
+ def __init__(self, config: RTDetrV2Config):
+ super().__init__(config)
+
+ self.dropout = config.dropout
+ self.layers = nn.ModuleList([RTDetrV2DecoderLayer(config) for _ in range(config.decoder_layers)])
+ self.query_pos_head = RTDetrV2MLPPredictionHead(4, 2 * config.d_model, config.d_model, num_layers=2)
+
+ # hack implementation for iterative bounding box refinement and two-stage Deformable DETR
+ self.bbox_embed = None
+ self.class_embed = None
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @merge_with_config_defaults
+ @capture_outputs
+ def forward(
+ self,
+ inputs_embeds=None,
+ encoder_hidden_states=None,
+ encoder_attention_mask=None,
+ reference_points=None,
+ spatial_shapes=None,
+ spatial_shapes_list=None,
+ level_start_index=None,
+ **kwargs: Unpack[TransformersKwargs],
+ ):
+ r"""
+ Args:
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_size)`):
+ The query embeddings that are passed into the decoder.
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
+ of the decoder.
+ encoder_attention_mask (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Mask to avoid performing cross-attention on padding pixel_values of the encoder. Mask values selected
+ in `[0, 1]`:
+ - 1 for pixels that are real (i.e. **not masked**),
+ - 0 for pixels that are padding (i.e. **masked**).
+ reference_points (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)` is `as_two_stage` else `(batch_size, num_queries, 2)` or , *optional*):
+ Reference point in range `[0, 1]`, top-left (0,0), bottom-right (1, 1), including padding area.
+ spatial_shapes (`torch.FloatTensor` of shape `(num_feature_levels, 2)`):
+ Spatial shapes of the feature maps.
+ level_start_index (`torch.LongTensor` of shape `(num_feature_levels)`, *optional*):
+ Indexes for the start of each feature level. In range `[0, sequence_length]`.
+ """
+ if inputs_embeds is not None:
+ hidden_states = inputs_embeds
+
+ # decoder layers
+ intermediate = ()
+ intermediate_reference_points = ()
+ intermediate_logits = ()
+
+ reference_points = F.sigmoid(reference_points)
+
+ # https://github.com/lyuwenyu/RT-DETR/blob/94f5e16708329d2f2716426868ec89aa774af016/RTDetrV2_pytorch/src/zoo/RTDetrV2/RTDetrV2_decoder.py#L252
+ for idx, decoder_layer in enumerate(self.layers):
+ reference_points_input = reference_points.unsqueeze(2)
+ object_queries_position_embeddings = self.query_pos_head(reference_points)
+
+ hidden_states = decoder_layer(
+ hidden_states,
+ object_queries_position_embeddings=object_queries_position_embeddings,
+ encoder_hidden_states=encoder_hidden_states,
+ reference_points=reference_points_input,
+ spatial_shapes=spatial_shapes,
+ spatial_shapes_list=spatial_shapes_list,
+ level_start_index=level_start_index,
+ encoder_attention_mask=encoder_attention_mask,
+ **kwargs,
+ )
+
+ # hack implementation for iterative bounding box refinement
+ if self.bbox_embed is not None:
+ predicted_corners = self.bbox_embed[idx](hidden_states)
+ new_reference_points = F.sigmoid(predicted_corners + inverse_sigmoid(reference_points))
+ reference_points = new_reference_points.detach()
+
+ intermediate += (hidden_states,)
+ intermediate_reference_points += (
+ (new_reference_points,) if self.bbox_embed is not None else (reference_points,)
+ )
+
+ if self.class_embed is not None:
+ logits = self.class_embed[idx](hidden_states)
+ intermediate_logits += (logits,)
+
+ # Keep batch_size as first dimension
+ intermediate = torch.stack(intermediate, dim=1)
+ intermediate_reference_points = torch.stack(intermediate_reference_points, dim=1)
+ if self.class_embed is not None:
+ intermediate_logits = torch.stack(intermediate_logits, dim=1)
+
+ return RTDetrV2DecoderOutput(
+ last_hidden_state=hidden_states,
+ intermediate_hidden_states=intermediate,
+ intermediate_logits=intermediate_logits,
+ intermediate_reference_points=intermediate_reference_points,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ Base class for outputs of the RT-DETR encoder-decoder model.
+ """
+)
+@dataclass
+class RTDetrV2ModelOutput(ModelOutput):
+ r"""
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_size)`):
+ Sequence of hidden-states at the output of the last layer of the decoder of the model.
+ intermediate_hidden_states (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, hidden_size)`):
+ Stacked intermediate hidden states (output of each layer of the decoder).
+ intermediate_logits (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, sequence_length, config.num_labels)`):
+ Stacked intermediate logits (logits of each layer of the decoder).
+ intermediate_reference_points (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, 4)`):
+ Stacked intermediate reference points (reference points of each layer of the decoder).
+ intermediate_predicted_corners (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, 4)`):
+ Stacked intermediate predicted corners (predicted corners of each layer of the decoder).
+ initial_reference_points (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)`):
+ Initial reference points used for the first decoder layer.
+ init_reference_points (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)`):
+ Initial reference points sent through the Transformer decoder.
+ enc_topk_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.num_labels)`):
+ Predicted bounding boxes scores where the top `config.two_stage_num_proposals` scoring bounding boxes are
+ picked as region proposals in the encoder stage. Output of bounding box binary classification (i.e.
+ foreground and background).
+ enc_topk_bboxes (`torch.FloatTensor` of shape `(batch_size, sequence_length, 4)`):
+ Logits of predicted bounding boxes coordinates in the encoder stage.
+ enc_outputs_class (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.num_labels)`, *optional*, returned when `config.with_box_refine=True` and `config.two_stage=True`):
+ Predicted bounding boxes scores where the top `config.two_stage_num_proposals` scoring bounding boxes are
+ picked as region proposals in the first stage. Output of bounding box binary classification (i.e.
+ foreground and background).
+ enc_outputs_coord_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, 4)`, *optional*, returned when `config.with_box_refine=True` and `config.two_stage=True`):
+ Logits of predicted bounding boxes coordinates in the first stage.
+ denoising_meta_values (`dict`):
+ Extra dictionary for the denoising related values.
+ """
+
+ last_hidden_state: torch.FloatTensor | None = None
+ intermediate_hidden_states: torch.FloatTensor | None = None
+ intermediate_logits: torch.FloatTensor | None = None
+ intermediate_reference_points: torch.FloatTensor | None = None
+ intermediate_predicted_corners: torch.FloatTensor | None = None
+ initial_reference_points: torch.FloatTensor | None = None
+ decoder_hidden_states: tuple[torch.FloatTensor] | None = None
+ decoder_attentions: tuple[torch.FloatTensor] | None = None
+ cross_attentions: tuple[torch.FloatTensor] | None = None
+ encoder_last_hidden_state: torch.FloatTensor | None = None
+ encoder_hidden_states: tuple[torch.FloatTensor] | None = None
+ encoder_attentions: tuple[torch.FloatTensor] | None = None
+ init_reference_points: torch.FloatTensor | None = None
+ enc_topk_logits: torch.FloatTensor | None = None
+ enc_topk_bboxes: torch.FloatTensor | None = None
+ enc_outputs_class: torch.FloatTensor | None = None
+ enc_outputs_coord_logits: torch.FloatTensor | None = None
+ denoising_meta_values: dict | None = None
+
+
+class RTDetrV2FrozenBatchNorm2d(nn.Module):
+ """
+ BatchNorm2d where the batch statistics and the affine parameters are fixed.
+
+ Copy-paste from torchvision.misc.ops with added eps before rqsrt, without which any other models than
+ torchvision.models.resnet[18,34,50,101] produce nans.
+ """
+
+ def __init__(self, n):
+ super().__init__()
+ self.register_buffer("weight", torch.ones(n))
+ self.register_buffer("bias", torch.zeros(n))
+ self.register_buffer("running_mean", torch.zeros(n))
+ self.register_buffer("running_var", torch.ones(n))
+
+ def _load_from_state_dict(
+ self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs
+ ):
+ num_batches_tracked_key = prefix + "num_batches_tracked"
+ if num_batches_tracked_key in state_dict:
+ del state_dict[num_batches_tracked_key]
+
+ super()._load_from_state_dict(
+ state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs
+ )
+
+ def forward(self, x):
+ # move reshapes to the beginning
+ # to make it user-friendly
+ weight = self.weight.reshape(1, -1, 1, 1)
+ bias = self.bias.reshape(1, -1, 1, 1)
+ running_var = self.running_var.reshape(1, -1, 1, 1)
+ running_mean = self.running_mean.reshape(1, -1, 1, 1)
+ epsilon = 1e-5
+ scale = weight * (running_var + epsilon).rsqrt()
+ bias = bias - running_mean * scale
+ return x * scale + bias
+
+
+def replace_batch_norm(model):
+ r"""
+ Recursively replace all `torch.nn.BatchNorm2d` with `RTDetrV2FrozenBatchNorm2d`.
+
+ Args:
+ model (torch.nn.Module):
+ input model
+ """
+ for name, module in model.named_children():
+ if isinstance(module, nn.BatchNorm2d):
+ new_module = RTDetrV2FrozenBatchNorm2d(module.num_features)
+
+ if module.weight.device != torch.device("meta"):
+ new_module.weight.copy_(module.weight)
+ new_module.bias.copy_(module.bias)
+ new_module.running_mean.copy_(module.running_mean)
+ new_module.running_var.copy_(module.running_var)
+
+ model._modules[name] = new_module
+
+ if len(list(module.children())) > 0:
+ replace_batch_norm(module)
+
+
+class RTDetrV2ConvEncoder(nn.Module):
+ """
+ Convolutional backbone using the modeling_rt_detr_v2_resnet.py.
+
+ nn.BatchNorm2d layers are replaced by RTDetrV2FrozenBatchNorm2d as defined above.
+ https://github.com/lyuwenyu/RT-DETR/blob/main/RTDetrV2_pytorch/src/nn/backbone/presnet.py#L142
+ """
+
+ def __init__(self, config):
+ super().__init__()
+
+ backbone = load_backbone(config)
+
+ if config.freeze_backbone_batch_norms:
+ # replace batch norm by frozen batch norm
+ with torch.no_grad():
+ replace_batch_norm(backbone)
+ self.model = backbone
+ self.intermediate_channel_sizes = self.model.channels
+
+ def forward(self, pixel_values: torch.Tensor, pixel_mask: torch.Tensor):
+ # send pixel_values through the model to get list of feature maps
+ features = self.model(pixel_values).feature_maps
+
+ out = []
+ for feature_map in features:
+ # downsample pixel_mask to match shape of corresponding feature_map
+ mask = nn.functional.interpolate(pixel_mask[None].float(), size=feature_map.shape[-2:]).to(torch.bool)[0]
+ out.append((feature_map, mask))
+ return out
+
+
+class RTDetrV2ConvNormLayer(nn.Module):
+ def __init__(self, config, in_channels, out_channels, kernel_size, stride, padding=None, activation=None):
+ super().__init__()
+ self.conv = nn.Conv2d(
+ in_channels,
+ out_channels,
+ kernel_size,
+ stride,
+ padding=(kernel_size - 1) // 2 if padding is None else padding,
+ bias=False,
+ )
+ self.norm = nn.BatchNorm2d(out_channels, config.batch_norm_eps)
+ self.activation = nn.Identity() if activation is None else ACT2CLS[activation]()
+
+ def forward(self, hidden_state):
+ hidden_state = self.conv(hidden_state)
+ hidden_state = self.norm(hidden_state)
+ hidden_state = self.activation(hidden_state)
+ return hidden_state
+
+
+class RTDetrV2EncoderLayer(nn.Module):
+ def __init__(self, config: RTDetrV2Config):
+ super().__init__()
+ self.normalize_before = config.normalize_before
+ self.hidden_size = config.encoder_hidden_dim
+
+ # self-attention
+ self.self_attn = RTDetrV2SelfAttention(
+ config=config,
+ hidden_size=self.hidden_size,
+ num_attention_heads=config.num_attention_heads,
+ dropout=config.dropout,
+ )
+ self.self_attn_layer_norm = nn.LayerNorm(self.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = config.dropout
+ self.mlp = RTDetrV2MLP(config, self.hidden_size, config.encoder_ffn_dim, config.encoder_activation_function)
+ self.final_layer_norm = nn.LayerNorm(self.hidden_size, eps=config.layer_norm_eps)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor,
+ spatial_position_embeddings: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.Tensor:
+ """
+ Args:
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, hidden_size)`
+ attention_mask (`torch.FloatTensor`): attention mask of size
+ `(batch, 1, target_len, source_len)` where padding elements are indicated by very large negative
+ values.
+ spatial_position_embeddings (`torch.FloatTensor`, *optional*):
+ Spatial position embeddings (2D positional encodings of image locations), to be added to both
+ the queries and keys in self-attention (but not to values).
+ """
+ residual = hidden_states
+ if self.normalize_before:
+ hidden_states = self.self_attn_layer_norm(hidden_states)
+
+ hidden_states, _ = self.self_attn(
+ hidden_states=hidden_states,
+ attention_mask=attention_mask,
+ position_embeddings=spatial_position_embeddings,
+ **kwargs,
+ )
+
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
+ hidden_states = residual + hidden_states
+ if not self.normalize_before:
+ hidden_states = self.self_attn_layer_norm(hidden_states)
+
+ if self.normalize_before:
+ hidden_states = self.final_layer_norm(hidden_states)
+ residual = hidden_states
+
+ hidden_states = self.mlp(hidden_states)
+
+ hidden_states = residual + hidden_states
+ if not self.normalize_before:
+ hidden_states = self.final_layer_norm(hidden_states)
+
+ if self.training:
+ if not torch.isfinite(hidden_states).all():
+ clamp_value = torch.finfo(hidden_states.dtype).max - 1000
+ hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
+
+ return hidden_states
+
+
+class RTDetrV2RepVggBlock(nn.Module):
+ """
+ RepVGG architecture block introduced by the work "RepVGG: Making VGG-style ConvNets Great Again".
+ """
+
+ def __init__(self, config: RTDetrV2Config):
+ super().__init__()
+
+ activation = config.activation_function
+ hidden_channels = int(config.encoder_hidden_dim * config.hidden_expansion)
+ self.conv1 = RTDetrV2ConvNormLayer(config, hidden_channels, hidden_channels, 3, 1, padding=1)
+ self.conv2 = RTDetrV2ConvNormLayer(config, hidden_channels, hidden_channels, 1, 1, padding=0)
+ self.activation = nn.Identity() if activation is None else ACT2CLS[activation]()
+
+ def forward(self, x):
+ y = self.conv1(x) + self.conv2(x)
+ return self.activation(y)
+
+
+class RTDetrV2CSPRepLayer(nn.Module):
+ """
+ Cross Stage Partial (CSP) network layer with RepVGG blocks.
+ """
+
+ def __init__(self, config: RTDetrV2Config):
+ super().__init__()
+
+ in_channels = config.encoder_hidden_dim * 2
+ out_channels = config.encoder_hidden_dim
+ num_blocks = 3
+ activation = config.activation_function
+
+ hidden_channels = int(out_channels * config.hidden_expansion)
+ self.conv1 = RTDetrV2ConvNormLayer(config, in_channels, hidden_channels, 1, 1, activation=activation)
+ self.conv2 = RTDetrV2ConvNormLayer(config, in_channels, hidden_channels, 1, 1, activation=activation)
+ self.bottlenecks = nn.Sequential(*[RTDetrV2RepVggBlock(config) for _ in range(num_blocks)])
+ if hidden_channels != out_channels:
+ self.conv3 = RTDetrV2ConvNormLayer(config, hidden_channels, out_channels, 1, 1, activation=activation)
+ else:
+ self.conv3 = nn.Identity()
+
+ def forward(self, hidden_state):
+ hidden_state_1 = self.conv1(hidden_state)
+ hidden_state_1 = self.bottlenecks(hidden_state_1)
+ hidden_state_2 = self.conv2(hidden_state)
+ return self.conv3(hidden_state_1 + hidden_state_2)
+
+
+def build_2d_sinusoidal_position_embedding(
+ height: int,
+ width: int,
+ embed_dim: int = 256,
+ temperature: float = 10000.0,
+ cls_token: bool = False,
+ device: torch.device | None = None,
+ dtype: torch.dtype = torch.float32,
+) -> torch.Tensor:
+ """2D sinusoidal position embeddings for an image patch grid.
+
+ Each (h, w) position gets an ``embed_dim``-dimensional vector laid out as
+ ``[sin_h | cos_h | sin_w | cos_w]``, with row-major (H-outer) patch ordering.
+
+ Args:
+ height: Grid height in patches.
+ width: Grid width in patches.
+ embed_dim: Total embedding dimension; must be divisible by 4.
+ temperature: Base for the frequency decay.
+ cls_token: If `True`, prepend a zero row for a CLS token.
+ device: Target device; defaults to CPU.
+ dtype: Output dtype; frequency arithmetic uses float64 internally.
+
+ Returns:
+ Tensor of shape ``(height * width [+1], embed_dim)``.
+ """
+ if embed_dim % 4 != 0:
+ raise ValueError(f"`embed_dim` must be divisible by 4, got {embed_dim}")
+
+ pos_dim = embed_dim // 4
+ omega = torch.arange(pos_dim, dtype=torch.float64, device=device) / pos_dim
+ omega = 1.0 / temperature**omega # (D/4,)
+
+ grid_h = torch.arange(height, dtype=torch.float64, device=device)
+ grid_w = torch.arange(width, dtype=torch.float64, device=device)
+ grid_h, grid_w = torch.meshgrid(grid_h, grid_w, indexing="ij") # (H, W) each
+
+ emb_h = grid_h.flatten().outer(omega) # (H*W, D/4)
+ emb_w = grid_w.flatten().outer(omega) # (H*W, D/4)
+
+ pos_embed = torch.cat([emb_h.sin(), emb_h.cos(), emb_w.sin(), emb_w.cos()], dim=1)
+
+ if cls_token:
+ pos_embed = torch.cat([torch.zeros(1, embed_dim, dtype=torch.float64, device=device), pos_embed], dim=0)
+
+ return pos_embed.to(dtype)
+
+
+class RTDetrV2SinePositionEmbedding(nn.Module):
+ """
+ 2D sinusoidal position embedding used in RT-DETR hybrid encoder.
+ """
+
+ def __init__(self, embed_dim: int = 256, temperature: int = 10000):
+ super().__init__()
+ self.embed_dim = embed_dim
+ self.temperature = temperature
+
+ @staticmethod
+ @compile_compatible_method_lru_cache(maxsize=32)
+ def _cached_build_2d_sinusoidal_position_embedding(*args, **kwargs) -> torch.Tensor:
+ return build_2d_sinusoidal_position_embedding(*args, **kwargs)
+
+ def forward(
+ self,
+ width: int,
+ height: int,
+ device: torch.device | str,
+ dtype: torch.dtype,
+ ) -> torch.Tensor:
+ """
+ Generate 2D sinusoidal position embeddings.
+
+ Returns:
+ Position embeddings of shape (1, height*width, embed_dim)
+ """
+ return self._cached_build_2d_sinusoidal_position_embedding(
+ height=torch_int(height),
+ width=torch_int(width),
+ embed_dim=self.embed_dim,
+ temperature=self.temperature,
+ device=device,
+ dtype=dtype,
+ ).unsqueeze(0)
+
+
+class RTDetrV2AIFILayer(nn.Module):
+ """
+ AIFI (Attention-based Intra-scale Feature Interaction) layer used in RT-DETR hybrid encoder.
+ """
+
+ def __init__(self, config: RTDetrV2Config):
+ super().__init__()
+ self.config = config
+ self.encoder_hidden_dim = config.encoder_hidden_dim
+ self.eval_size = config.eval_size
+
+ self.position_embedding = RTDetrV2SinePositionEmbedding(
+ embed_dim=self.encoder_hidden_dim,
+ temperature=config.positional_encoding_temperature,
+ )
+ self.layers = nn.ModuleList([RTDetrV2EncoderLayer(config) for _ in range(config.encoder_layers)])
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.Tensor:
+ """
+ Args:
+ hidden_states (`torch.FloatTensor` of shape `(batch_size, channels, height, width)`):
+ Feature map to process.
+ """
+ batch_size = hidden_states.shape[0]
+ height, width = hidden_states.shape[2:]
+
+ hidden_states = hidden_states.flatten(2).transpose(1, 2)
+
+ if self.training or self.eval_size is None:
+ pos_embed = self.position_embedding(
+ width=width,
+ height=height,
+ device=hidden_states.device,
+ dtype=hidden_states.dtype,
+ )
+ else:
+ pos_embed = None
+
+ for layer in self.layers:
+ hidden_states = layer(
+ hidden_states,
+ attention_mask=None,
+ spatial_position_embeddings=pos_embed,
+ **kwargs,
+ )
+
+ hidden_states = (
+ hidden_states.transpose(1, 2).reshape(batch_size, self.encoder_hidden_dim, height, width).contiguous()
+ )
+
+ return hidden_states
+
+
+class RTDetrV2HybridEncoder(RTDetrV2PreTrainedModel):
+ """
+ Hybrid encoder consisting of AIFI (Attention-based Intra-scale Feature Interaction) layers,
+ a top-down Feature Pyramid Network (FPN) and a bottom-up Path Aggregation Network (PAN).
+ More details on the paper: https://huggingface.co/papers/2304.08069
+
+ Args:
+ config: RTDetrV2Config
+ """
+
+ _can_record_outputs = {
+ "hidden_states": RTDetrV2AIFILayer,
+ "attentions": RTDetrV2SelfAttention,
+ }
+
+ def __init__(self, config: RTDetrV2Config):
+ super().__init__(config)
+ self.config = config
+ self.in_channels = config.encoder_in_channels
+ self.feat_strides = config.feat_strides
+ self.encoder_hidden_dim = config.encoder_hidden_dim
+ self.encode_proj_layers = config.encode_proj_layers
+ self.positional_encoding_temperature = config.positional_encoding_temperature
+ self.eval_size = config.eval_size
+ self.out_channels = [self.encoder_hidden_dim for _ in self.in_channels]
+ self.out_strides = self.feat_strides
+ self.num_fpn_stages = len(self.in_channels) - 1
+ self.num_pan_stages = len(self.in_channels) - 1
+
+ # AIFI (Attention-based Intra-scale Feature Interaction) layers
+ self.aifi = nn.ModuleList([RTDetrV2AIFILayer(config) for _ in range(len(self.encode_proj_layers))])
+
+ # top-down FPN
+ self.lateral_convs = nn.ModuleList()
+ self.fpn_blocks = nn.ModuleList()
+ for _ in range(self.num_fpn_stages):
+ lateral_conv = RTDetrV2ConvNormLayer(
+ config,
+ in_channels=self.encoder_hidden_dim,
+ out_channels=self.encoder_hidden_dim,
+ kernel_size=1,
+ stride=1,
+ activation=config.activation_function,
+ )
+ fpn_block = RTDetrV2CSPRepLayer(config)
+ self.lateral_convs.append(lateral_conv)
+ self.fpn_blocks.append(fpn_block)
+
+ # bottom-up PAN
+ self.downsample_convs = nn.ModuleList()
+ self.pan_blocks = nn.ModuleList()
+ for _ in range(self.num_pan_stages):
+ downsample_conv = RTDetrV2ConvNormLayer(
+ config,
+ in_channels=self.encoder_hidden_dim,
+ out_channels=self.encoder_hidden_dim,
+ kernel_size=3,
+ stride=2,
+ activation=config.activation_function,
+ )
+ pan_block = RTDetrV2CSPRepLayer(config)
+ self.downsample_convs.append(downsample_conv)
+ self.pan_blocks.append(pan_block)
+
+ self.post_init()
+
+ @merge_with_config_defaults
+ @capture_outputs(tie_last_hidden_states=False)
+ def forward(
+ self,
+ inputs_embeds=None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> BaseModelOutput:
+ r"""
+ Args:
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
+ Flattened feature map (output of the backbone + projection layer) that is passed to the encoder.
+ """
+ feature_maps = inputs_embeds
+
+ # AIFI: Apply transformer encoder to specified feature levels
+ if self.config.encoder_layers > 0:
+ for i, enc_ind in enumerate(self.encode_proj_layers):
+ feature_maps[enc_ind] = self.aifi[i](feature_maps[enc_ind], **kwargs)
+
+ # top-down FPN
+ fpn_feature_maps = [feature_maps[-1]]
+ for idx, (lateral_conv, fpn_block) in enumerate(zip(self.lateral_convs, self.fpn_blocks)):
+ backbone_feature_map = feature_maps[self.num_fpn_stages - idx - 1]
+ top_fpn_feature_map = fpn_feature_maps[-1]
+ # apply lateral block
+ top_fpn_feature_map = lateral_conv(top_fpn_feature_map)
+ fpn_feature_maps[-1] = top_fpn_feature_map
+ # apply fpn block
+ top_fpn_feature_map = F.interpolate(top_fpn_feature_map, scale_factor=2.0, mode="nearest")
+ fused_feature_map = torch.concat([top_fpn_feature_map, backbone_feature_map], dim=1)
+ new_fpn_feature_map = fpn_block(fused_feature_map)
+ fpn_feature_maps.append(new_fpn_feature_map)
+
+ fpn_feature_maps.reverse()
+
+ # bottom-up PAN
+ pan_feature_maps = [fpn_feature_maps[0]]
+ for idx, (downsample_conv, pan_block) in enumerate(zip(self.downsample_convs, self.pan_blocks)):
+ top_pan_feature_map = pan_feature_maps[-1]
+ fpn_feature_map = fpn_feature_maps[idx + 1]
+ downsampled_feature_map = downsample_conv(top_pan_feature_map)
+ fused_feature_map = torch.concat([downsampled_feature_map, fpn_feature_map], dim=1)
+ new_pan_feature_map = pan_block(fused_feature_map)
+ pan_feature_maps.append(new_pan_feature_map)
+
+ return BaseModelOutput(last_hidden_state=pan_feature_maps)
+
+
+def get_contrastive_denoising_training_group(
+ targets,
+ num_classes,
+ num_queries,
+ class_embed,
+ num_denoising_queries=100,
+ label_noise_ratio=0.5,
+ box_noise_scale=1.0,
+):
+ """
+ Creates a contrastive denoising training group using ground-truth samples. It adds noise to labels and boxes.
+
+ Args:
+ targets (`list[dict]`):
+ The target objects, each containing 'class_labels' and 'boxes' for objects in an image.
+ num_classes (`int`):
+ Total number of classes in the dataset.
+ num_queries (`int`):
+ Number of query slots in the transformer.
+ class_embed (`callable`):
+ A function or a model layer to embed class labels.
+ num_denoising_queries (`int`, *optional*, defaults to 100):
+ Number of denoising queries.
+ label_noise_ratio (`float`, *optional*, defaults to 0.5):
+ Ratio of noise applied to labels.
+ box_noise_scale (`float`, *optional*, defaults to 1.0):
+ Scale of noise applied to bounding boxes.
+ Returns:
+ `tuple` comprising various elements:
+ - **input_query_class** (`torch.FloatTensor`) --
+ Class queries with applied label noise.
+ - **input_query_bbox** (`torch.FloatTensor`) --
+ Bounding box queries with applied box noise.
+ - **attn_mask** (`torch.FloatTensor`) --
+ Attention mask for separating denoising and reconstruction queries.
+ - **denoising_meta_values** (`dict`) --
+ Metadata including denoising positive indices, number of groups, and split sizes.
+ """
+
+ if num_denoising_queries <= 0:
+ return None, None, None, None
+
+ num_ground_truths = [len(t["class_labels"]) for t in targets]
+ device = targets[0]["class_labels"].device
+
+ max_gt_num = max(num_ground_truths)
+ if max_gt_num == 0:
+ return None, None, None, None
+
+ num_groups_denoising_queries = num_denoising_queries // max_gt_num
+ num_groups_denoising_queries = 1 if num_groups_denoising_queries == 0 else num_groups_denoising_queries
+ # pad gt to max_num of a batch
+ batch_size = len(num_ground_truths)
+
+ input_query_class = torch.full([batch_size, max_gt_num], num_classes, dtype=torch.int32, device=device)
+ input_query_bbox = torch.zeros([batch_size, max_gt_num, 4], device=device)
+ pad_gt_mask = torch.zeros([batch_size, max_gt_num], dtype=torch.bool, device=device)
+
+ for i in range(batch_size):
+ num_gt = num_ground_truths[i]
+ if num_gt > 0:
+ input_query_class[i, :num_gt] = targets[i]["class_labels"]
+ input_query_bbox[i, :num_gt] = targets[i]["boxes"]
+ pad_gt_mask[i, :num_gt] = 1
+ # each group has positive and negative queries.
+ input_query_class = input_query_class.tile([1, 2 * num_groups_denoising_queries])
+ input_query_bbox = input_query_bbox.tile([1, 2 * num_groups_denoising_queries, 1])
+ pad_gt_mask = pad_gt_mask.tile([1, 2 * num_groups_denoising_queries])
+ # positive and negative mask
+ negative_gt_mask = torch.zeros([batch_size, max_gt_num * 2, 1], device=device)
+ negative_gt_mask[:, max_gt_num:] = 1
+ negative_gt_mask = negative_gt_mask.tile([1, num_groups_denoising_queries, 1])
+ positive_gt_mask = 1 - negative_gt_mask
+ # contrastive denoising training positive index
+ positive_gt_mask = positive_gt_mask.squeeze(-1) * pad_gt_mask
+ denoise_positive_idx = torch.nonzero(positive_gt_mask)[:, 1]
+ denoise_positive_idx = torch.split(
+ denoise_positive_idx, [n * num_groups_denoising_queries for n in num_ground_truths]
+ )
+ # total denoising queries
+ num_denoising_queries = torch_int(max_gt_num * 2 * num_groups_denoising_queries)
+
+ if label_noise_ratio > 0:
+ mask = torch.rand_like(input_query_class, dtype=torch.float) < (label_noise_ratio * 0.5)
+ # randomly put a new one here
+ new_label = torch.randint_like(mask, 0, num_classes, dtype=input_query_class.dtype)
+ input_query_class = torch.where(mask & pad_gt_mask, new_label, input_query_class)
+
+ if box_noise_scale > 0:
+ known_bbox = center_to_corners_format(input_query_bbox)
+ diff = torch.tile(input_query_bbox[..., 2:] * 0.5, [1, 1, 2]) * box_noise_scale
+ rand_sign = torch.randint_like(input_query_bbox, 0, 2) * 2.0 - 1.0
+ rand_part = torch.rand_like(input_query_bbox)
+ rand_part = (rand_part + 1.0) * negative_gt_mask + rand_part * (1 - negative_gt_mask)
+ rand_part *= rand_sign
+ known_bbox += rand_part * diff
+ known_bbox.clip_(min=0.0, max=1.0)
+ input_query_bbox = corners_to_center_format(known_bbox)
+ input_query_bbox = inverse_sigmoid(input_query_bbox)
+
+ input_query_class = class_embed(input_query_class)
+
+ target_size = num_denoising_queries + num_queries
+ attn_mask = torch.full([target_size, target_size], 0, dtype=torch.float, device=device)
+ # match query cannot see the reconstruction
+ attn_mask[num_denoising_queries:, :num_denoising_queries] = -torch.inf
+
+ # reconstructions cannot see each other
+ for i in range(num_groups_denoising_queries):
+ idx_block_start = max_gt_num * 2 * i
+ idx_block_end = max_gt_num * 2 * (i + 1)
+ attn_mask[idx_block_start:idx_block_end, :idx_block_start] = -torch.inf
+ attn_mask[idx_block_start:idx_block_end, idx_block_end:num_denoising_queries] = -torch.inf
+
+ denoising_meta_values = {
+ "dn_positive_idx": denoise_positive_idx,
+ "dn_num_group": num_groups_denoising_queries,
+ "dn_num_split": [num_denoising_queries, num_queries],
+ }
+
+ return input_query_class, input_query_bbox, attn_mask, denoising_meta_values
+
+
+@auto_docstring(
+ custom_intro="""
+ RT-DETR Model (consisting of a backbone and encoder-decoder) outputting raw hidden states without any head on top.
+ """
+)
+class RTDetrV2Model(RTDetrV2PreTrainedModel):
+ def __init__(self, config: RTDetrV2Config):
+ super().__init__(config)
+
+ # Create backbone
+ self.backbone = RTDetrV2ConvEncoder(config)
+ intermediate_channel_sizes = self.backbone.intermediate_channel_sizes
+
+ # Create encoder input projection layers
+ # https://github.com/lyuwenyu/RT-DETR/blob/94f5e16708329d2f2716426868ec89aa774af016/RTDetrV2_pytorch/src/zoo/RTDetrV2/hybrid_encoder.py#L212
+ num_backbone_outs = len(intermediate_channel_sizes)
+ encoder_input_proj_list = []
+ for i in range(num_backbone_outs):
+ in_channels = intermediate_channel_sizes[i]
+ encoder_input_proj_list.append(
+ nn.Sequential(
+ nn.Conv2d(in_channels, config.encoder_hidden_dim, kernel_size=1, bias=False),
+ nn.BatchNorm2d(config.encoder_hidden_dim),
+ )
+ )
+ self.encoder_input_proj = nn.ModuleList(encoder_input_proj_list)
+
+ # Create encoder
+ self.encoder = RTDetrV2HybridEncoder(config)
+
+ # denoising part
+ if config.num_denoising > 0:
+ self.denoising_class_embed = nn.Embedding(
+ config.num_labels + 1, config.d_model, padding_idx=config.num_labels
+ )
+
+ # decoder embedding
+ if config.learn_initial_query:
+ self.weight_embedding = nn.Embedding(config.num_queries, config.d_model)
+
+ # encoder head
+ self.enc_output = nn.Sequential(
+ nn.Linear(config.d_model, config.d_model),
+ nn.LayerNorm(config.d_model, eps=config.layer_norm_eps),
+ )
+ self.enc_score_head = nn.Linear(config.d_model, config.num_labels)
+ self.enc_bbox_head = RTDetrV2MLPPredictionHead(config.d_model, config.d_model, 4, num_layers=3)
+
+ # init encoder output anchors and valid_mask
+ if config.anchor_image_size:
+ self.anchors, self.valid_mask = self.generate_anchors(dtype=self.dtype)
+
+ # Create decoder input projection layers
+ # https://github.com/lyuwenyu/RT-DETR/blob/94f5e16708329d2f2716426868ec89aa774af016/RTDetrV2_pytorch/src/zoo/RTDetrV2/RTDetrV2_decoder.py#L412
+ num_backbone_outs = len(config.decoder_in_channels)
+ decoder_input_proj_list = []
+ for i in range(num_backbone_outs):
+ in_channels = config.decoder_in_channels[i]
+ decoder_input_proj_list.append(
+ nn.Sequential(
+ nn.Conv2d(in_channels, config.d_model, kernel_size=1, bias=False),
+ nn.BatchNorm2d(config.d_model, config.batch_norm_eps),
+ )
+ )
+ for _ in range(config.num_feature_levels - num_backbone_outs):
+ decoder_input_proj_list.append(
+ nn.Sequential(
+ nn.Conv2d(in_channels, config.d_model, kernel_size=3, stride=2, padding=1, bias=False),
+ nn.BatchNorm2d(config.d_model, config.batch_norm_eps),
+ )
+ )
+ in_channels = config.d_model
+ self.decoder_input_proj = nn.ModuleList(decoder_input_proj_list)
+ # decoder
+ self.decoder = RTDetrV2Decoder(config)
+
+ self.post_init()
+
+ def freeze_backbone(self):
+ for param in self.backbone.parameters():
+ param.requires_grad_(False)
+
+ def unfreeze_backbone(self):
+ for param in self.backbone.parameters():
+ param.requires_grad_(True)
+
+ @staticmethod
+ @compile_compatible_method_lru_cache(maxsize=32)
+ def _cached_generate_anchors(
+ spatial_shapes: tuple[tuple[int, int], ...],
+ grid_size: float,
+ device: torch.device | str = "cpu",
+ dtype: torch.dtype = torch.float32,
+ ) -> tuple[torch.Tensor, torch.Tensor]:
+ anchors = []
+ for level, (height, width) in enumerate(spatial_shapes):
+ grid_y, grid_x = torch.meshgrid(
+ torch.arange(end=height, device=device).to(dtype),
+ torch.arange(end=width, device=device).to(dtype),
+ indexing="ij",
+ )
+ grid_xy = torch.stack([grid_x, grid_y], -1)
+ grid_xy = grid_xy.unsqueeze(0) + 0.5
+ grid_xy[..., 0] /= width
+ grid_xy[..., 1] /= height
+ wh = torch.ones_like(grid_xy) * grid_size * (2.0**level)
+ anchors.append(torch.concat([grid_xy, wh], -1).reshape(-1, height * width, 4))
+ # define the valid range for anchor coordinates
+ eps = 1e-2
+ anchors = torch.concat(anchors, 1)
+ valid_mask = ((anchors > eps) * (anchors < 1 - eps)).all(-1, keepdim=True)
+ anchors = torch.log(anchors / (1 - anchors))
+ anchors = torch.where(valid_mask, anchors, torch.tensor(torch.finfo(dtype).max, dtype=dtype, device=device))
+
+ return anchors, valid_mask
+
+ def generate_anchors(self, spatial_shapes=None, grid_size=0.05, device="cpu", dtype=torch.float32):
+ if spatial_shapes is None:
+ spatial_shapes = (
+ (int(self.config.anchor_image_size[0] / s), int(self.config.anchor_image_size[1] / s))
+ for s in self.config.feat_strides
+ )
+ return self._cached_generate_anchors(spatial_shapes, grid_size, device, dtype)
+
+ @auto_docstring
+ @can_return_tuple
+ def forward(
+ self,
+ pixel_values: torch.FloatTensor,
+ pixel_mask: torch.LongTensor | None = None,
+ encoder_outputs: torch.FloatTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: list[dict] | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.FloatTensor] | RTDetrV2ModelOutput:
+ r"""
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
+ Optionally, instead of passing the flattened feature map (output of the backbone + projection layer), you
+ can choose to directly pass a flattened representation of an image.
+ labels (`list[Dict]` of len `(batch_size,)`, *optional*):
+ Labels for computing the bipartite matching loss. List of dicts, each dictionary containing at least the
+ following 2 keys: 'class_labels' and 'boxes' (the class labels and bounding boxes of an image in the batch
+ respectively). The class labels themselves should be a `torch.LongTensor` of len `(number of bounding boxes
+ in the image,)` and the boxes a `torch.FloatTensor` of shape `(number of bounding boxes in the image, 4)`.
+
+ Examples:
+
+ ```python
+ >>> from transformers import AutoImageProcessor, RTDetrV2Model
+ >>> from PIL import Image
+ >>> import httpx
+ >>> from io import BytesIO
+
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
+ >>> with httpx.stream("GET", url) as response:
+ ... image = Image.open(BytesIO(response.read()))
+
+ >>> image_processor = AutoImageProcessor.from_pretrained("PekingU/RTDetrV2_r50vd")
+ >>> model = RTDetrV2Model.from_pretrained("PekingU/RTDetrV2_r50vd")
+
+ >>> inputs = image_processor(images=image, return_tensors="pt")
+
+ >>> outputs = model(**inputs)
+
+ >>> last_hidden_states = outputs.last_hidden_state
+ >>> list(last_hidden_states.shape)
+ [1, 300, 256]
+ ```"""
+ if pixel_values is None and inputs_embeds is None:
+ raise ValueError("You have to specify either pixel_values or inputs_embeds")
+
+ if inputs_embeds is None:
+ batch_size, num_channels, height, width = pixel_values.shape
+ device = pixel_values.device
+ if pixel_mask is None:
+ pixel_mask = torch.ones(((batch_size, height, width)), device=device)
+ features = self.backbone(pixel_values, pixel_mask)
+ proj_feats = [self.encoder_input_proj[level](source) for level, (source, mask) in enumerate(features)]
+ else:
+ batch_size = inputs_embeds.shape[0]
+ device = inputs_embeds.device
+ proj_feats = inputs_embeds
+
+ if encoder_outputs is None:
+ encoder_outputs = self.encoder(
+ proj_feats,
+ **kwargs,
+ )
+ # If the user passed a tuple for encoder_outputs, we wrap it in a BaseModelOutput
+ elif not isinstance(encoder_outputs, BaseModelOutput):
+ encoder_outputs = BaseModelOutput(
+ last_hidden_state=encoder_outputs[0],
+ hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
+ attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
+ )
+
+ # Equivalent to def _get_encoder_input
+ # https://github.com/lyuwenyu/RT-DETR/blob/94f5e16708329d2f2716426868ec89aa774af016/RTDetrV2_pytorch/src/zoo/RTDetrV2/RTDetrV2_decoder.py#L412
+ sources = []
+ for level, source in enumerate(encoder_outputs.last_hidden_state):
+ sources.append(self.decoder_input_proj[level](source))
+
+ # Lowest resolution feature maps are obtained via 3x3 stride 2 convolutions on the final stage
+ if self.config.num_feature_levels > len(sources):
+ _len_sources = len(sources)
+ sources.append(self.decoder_input_proj[_len_sources](encoder_outputs.last_hidden_state)[-1])
+ for i in range(_len_sources + 1, self.config.num_feature_levels):
+ sources.append(self.decoder_input_proj[i](encoder_outputs.last_hidden_state[-1]))
+
+ # Prepare encoder inputs (by flattening)
+ source_flatten = []
+ spatial_shapes_list = []
+ spatial_shapes = torch.empty((len(sources), 2), device=device, dtype=torch.long)
+ for level, source in enumerate(sources):
+ height, width = source.shape[-2:]
+ spatial_shapes[level, 0] = height
+ spatial_shapes[level, 1] = width
+ spatial_shapes_list.append((height, width))
+ source = source.flatten(2).transpose(1, 2)
+ source_flatten.append(source)
+ source_flatten = torch.cat(source_flatten, 1)
+ level_start_index = torch.cat((spatial_shapes.new_zeros((1,)), spatial_shapes.prod(1).cumsum(0)[:-1]))
+
+ # prepare denoising training
+ if self.training and self.config.num_denoising > 0 and labels is not None:
+ (
+ denoising_class,
+ denoising_bbox_unact,
+ attention_mask,
+ denoising_meta_values,
+ ) = get_contrastive_denoising_training_group(
+ targets=labels,
+ num_classes=self.config.num_labels,
+ num_queries=self.config.num_queries,
+ class_embed=self.denoising_class_embed,
+ num_denoising_queries=self.config.num_denoising,
+ label_noise_ratio=self.config.label_noise_ratio,
+ box_noise_scale=self.config.box_noise_scale,
+ )
+ else:
+ denoising_class, denoising_bbox_unact, attention_mask, denoising_meta_values = None, None, None, None
+
+ batch_size = len(source_flatten)
+ device = source_flatten.device
+ dtype = source_flatten.dtype
+
+ # prepare input for decoder
+ if self.training or self.config.anchor_image_size is None:
+ # Pass spatial_shapes as tuple to make it hashable and make sure
+ # lru_cache is working for generate_anchors()
+ spatial_shapes_tuple = tuple(spatial_shapes_list)
+ anchors, valid_mask = self.generate_anchors(spatial_shapes_tuple, device=device, dtype=dtype)
+ else:
+ anchors, valid_mask = self.anchors, self.valid_mask
+ anchors, valid_mask = anchors.to(device, dtype), valid_mask.to(device, dtype)
+
+ # use the valid_mask to selectively retain values in the feature map where the mask is `True`
+ memory = valid_mask.to(source_flatten.dtype) * source_flatten
+
+ output_memory = self.enc_output(memory)
+
+ enc_outputs_class = self.enc_score_head(output_memory)
+ enc_outputs_coord_logits = self.enc_bbox_head(output_memory) + anchors
+
+ _, topk_ind = torch.topk(enc_outputs_class.max(-1).values, self.config.num_queries, dim=1)
+
+ reference_points_unact = enc_outputs_coord_logits.gather(
+ dim=1, index=topk_ind.unsqueeze(-1).repeat(1, 1, enc_outputs_coord_logits.shape[-1])
+ )
+
+ enc_topk_bboxes = F.sigmoid(reference_points_unact)
+ if denoising_bbox_unact is not None:
+ reference_points_unact = torch.concat([denoising_bbox_unact, reference_points_unact], 1)
+
+ enc_topk_logits = enc_outputs_class.gather(
+ dim=1, index=topk_ind.unsqueeze(-1).repeat(1, 1, enc_outputs_class.shape[-1])
+ )
+
+ # extract region features
+ if self.config.learn_initial_query:
+ target = self.weight_embedding.tile([batch_size, 1, 1])
+ else:
+ target = output_memory.gather(dim=1, index=topk_ind.unsqueeze(-1).repeat(1, 1, output_memory.shape[-1]))
+ target = target.detach()
+
+ if denoising_class is not None:
+ target = torch.concat([denoising_class, target], 1)
+
+ init_reference_points = reference_points_unact.detach()
+
+ # decoder
+ decoder_outputs = self.decoder(
+ inputs_embeds=target,
+ encoder_hidden_states=source_flatten,
+ encoder_attention_mask=attention_mask,
+ reference_points=init_reference_points,
+ spatial_shapes=spatial_shapes,
+ spatial_shapes_list=spatial_shapes_list,
+ level_start_index=level_start_index,
+ **kwargs,
+ )
+
+ return RTDetrV2ModelOutput(
+ last_hidden_state=decoder_outputs.last_hidden_state,
+ intermediate_hidden_states=decoder_outputs.intermediate_hidden_states,
+ intermediate_logits=decoder_outputs.intermediate_logits,
+ intermediate_reference_points=decoder_outputs.intermediate_reference_points,
+ intermediate_predicted_corners=decoder_outputs.intermediate_predicted_corners,
+ initial_reference_points=decoder_outputs.initial_reference_points,
+ decoder_hidden_states=decoder_outputs.hidden_states,
+ decoder_attentions=decoder_outputs.attentions,
+ cross_attentions=decoder_outputs.cross_attentions,
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
+ encoder_hidden_states=encoder_outputs.hidden_states,
+ encoder_attentions=encoder_outputs.attentions,
+ init_reference_points=init_reference_points,
+ enc_topk_logits=enc_topk_logits,
+ enc_topk_bboxes=enc_topk_bboxes,
+ enc_outputs_class=enc_outputs_class,
+ enc_outputs_coord_logits=enc_outputs_coord_logits,
+ denoising_meta_values=denoising_meta_values,
+ )
+
+
+class RTDetrV2MLPPredictionHead(nn.Module):
+ """
+ Very simple multi-layer perceptron (MLP, also called FFN), used to predict the normalized center coordinates,
+ height and width of a bounding box w.r.t. an image.
+
+ """
+
+ def __init__(self, input_dim, hidden_dim, output_dim, num_layers):
+ super().__init__()
+ self.num_layers = num_layers
+ h = [hidden_dim] * (num_layers - 1)
+ self.layers = nn.ModuleList(nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim]))
+
+ def forward(self, x):
+ for i, layer in enumerate(self.layers):
+ x = nn.functional.relu(layer(x)) if i < self.num_layers - 1 else layer(x)
+ return x
+
+
+@auto_docstring(
+ custom_intro="""
+ Output type of [`RTDetrV2ForObjectDetection`].
+ """
+)
+@dataclass
+class RTDetrV2ObjectDetectionOutput(ModelOutput):
+ r"""
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` are provided)):
+ Total loss as a linear combination of a negative log-likehood (cross-entropy) for class prediction and a
+ bounding box loss. The latter is defined as a linear combination of the L1 loss and the generalized
+ scale-invariant IoU loss.
+ loss_dict (`Dict`, *optional*):
+ A dictionary containing the individual losses. Useful for logging.
+ logits (`torch.FloatTensor` of shape `(batch_size, num_queries, num_classes + 1)`):
+ Classification logits (including no-object) for all queries.
+ pred_boxes (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)`):
+ Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height). These
+ values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding
+ possible padding). You can use [`~RTDetrV2ImageProcessor.post_process_object_detection`] to retrieve the
+ unnormalized (absolute) bounding boxes.
+ auxiliary_outputs (`list[Dict]`, *optional*):
+ Optional, only returned when auxiliary losses are activated (i.e. `config.auxiliary_loss` is set to `True`)
+ and labels are provided. It is a list of dictionaries containing the two above keys (`logits` and
+ `pred_boxes`) for each decoder layer.
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_size)`):
+ Sequence of hidden-states at the output of the last layer of the decoder of the model.
+ intermediate_hidden_states (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, hidden_size)`):
+ Stacked intermediate hidden states (output of each layer of the decoder).
+ intermediate_logits (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, config.num_labels)`):
+ Stacked intermediate logits (logits of each layer of the decoder).
+ intermediate_reference_points (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, 4)`):
+ Stacked intermediate reference points (reference points of each layer of the decoder).
+ intermediate_predicted_corners (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, 4)`):
+ Stacked intermediate predicted corners (predicted corners of each layer of the decoder).
+ initial_reference_points (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, 4)`):
+ Stacked initial reference points (initial reference points of each layer of the decoder).
+ init_reference_points (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)`):
+ Initial reference points sent through the Transformer decoder.
+ enc_topk_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.num_labels)`, *optional*, returned when `config.with_box_refine=True` and `config.two_stage=True`):
+ Logits of predicted bounding boxes coordinates in the encoder.
+ enc_topk_bboxes (`torch.FloatTensor` of shape `(batch_size, sequence_length, 4)`, *optional*, returned when `config.with_box_refine=True` and `config.two_stage=True`):
+ Logits of predicted bounding boxes coordinates in the encoder.
+ enc_outputs_class (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.num_labels)`, *optional*, returned when `config.with_box_refine=True` and `config.two_stage=True`):
+ Predicted bounding boxes scores where the top `config.two_stage_num_proposals` scoring bounding boxes are
+ picked as region proposals in the first stage. Output of bounding box binary classification (i.e.
+ foreground and background).
+ enc_outputs_coord_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, 4)`, *optional*, returned when `config.with_box_refine=True` and `config.two_stage=True`):
+ Logits of predicted bounding boxes coordinates in the first stage.
+ denoising_meta_values (`dict`):
+ Extra dictionary for the denoising related values
+ """
+
+ loss: torch.FloatTensor | None = None
+ loss_dict: dict | None = None
+ logits: torch.FloatTensor | None = None
+ pred_boxes: torch.FloatTensor | None = None
+ auxiliary_outputs: list[dict] | None = None
+ last_hidden_state: torch.FloatTensor | None = None
+ intermediate_hidden_states: torch.FloatTensor | None = None
+ intermediate_logits: torch.FloatTensor | None = None
+ intermediate_reference_points: torch.FloatTensor | None = None
+ intermediate_predicted_corners: torch.FloatTensor | None = None
+ initial_reference_points: torch.FloatTensor | None = None
+ decoder_hidden_states: tuple[torch.FloatTensor] | None = None
+ decoder_attentions: tuple[torch.FloatTensor] | None = None
+ cross_attentions: tuple[torch.FloatTensor] | None = None
+ encoder_last_hidden_state: torch.FloatTensor | None = None
+ encoder_hidden_states: tuple[torch.FloatTensor] | None = None
+ encoder_attentions: tuple[torch.FloatTensor] | None = None
+ init_reference_points: tuple[torch.FloatTensor] | None = None
+ enc_topk_logits: torch.FloatTensor | None = None
+ enc_topk_bboxes: torch.FloatTensor | None = None
+ enc_outputs_class: torch.FloatTensor | None = None
+ enc_outputs_coord_logits: torch.FloatTensor | None = None
+ denoising_meta_values: dict | None = None
+
+
+@auto_docstring(
+ custom_intro="""
+ RT-DETR Model (consisting of a backbone and encoder-decoder) outputting bounding boxes and logits to be further
+ decoded into scores and classes.
+ """
+)
+class RTDetrV2ForObjectDetection(RTDetrV2PreTrainedModel):
+ # When using clones, all layers > 0 will be clones, but layer 0 *is* required
+ # We can't initialize the model on meta device as some weights are modified during the initialization
+ _no_split_modules = None
+ _tied_weights_keys = {
+ r"bbox_embed.(?![0])\d+": r"bbox_embed.0",
+ r"class_embed.(?![0])\d+": r"^class_embed.0",
+ "class_embed": "model.decoder.class_embed",
+ "bbox_embed": "model.decoder.bbox_embed",
+ }
+
+ def __init__(self, config: RTDetrV2Config):
+ super().__init__(config)
+ # RTDETR encoder-decoder model
+ self.model = RTDetrV2Model(config)
+ self.class_embed = nn.ModuleList(
+ [torch.nn.Linear(config.d_model, config.num_labels) for _ in range(config.decoder_layers)]
+ )
+ self.bbox_embed = nn.ModuleList(
+ [
+ RTDetrV2MLPPredictionHead(config.d_model, config.d_model, 4, num_layers=3)
+ for _ in range(config.decoder_layers)
+ ]
+ )
+ self.model.decoder.class_embed = self.class_embed
+ self.model.decoder.bbox_embed = self.bbox_embed
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def _set_aux_loss(self, outputs_class, outputs_coord):
+ return [{"logits": a, "pred_boxes": b} for a, b in zip(outputs_class, outputs_coord)]
+
+ @auto_docstring
+ @can_return_tuple
+ def forward(
+ self,
+ pixel_values: torch.FloatTensor,
+ pixel_mask: torch.LongTensor | None = None,
+ encoder_outputs: torch.FloatTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: list[dict] | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.FloatTensor] | RTDetrV2ObjectDetectionOutput:
+ r"""
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
+ Optionally, instead of passing the flattened feature map (output of the backbone + projection layer), you
+ can choose to directly pass a flattened representation of an image.
+ labels (`list[Dict]` of len `(batch_size,)`, *optional*):
+ Labels for computing the bipartite matching loss. List of dicts, each dictionary containing at least the
+ following 2 keys: 'class_labels' and 'boxes' (the class labels and bounding boxes of an image in the batch
+ respectively). The class labels themselves should be a `torch.LongTensor` of len `(number of bounding boxes
+ in the image,)` and the boxes a `torch.FloatTensor` of shape `(number of bounding boxes in the image, 4)`.
+
+ Examples:
+
+ ```python
+ >>> from transformers import RTDetrV2ImageProcessor, RTDetrV2ForObjectDetection
+ >>> from PIL import Image
+ >>> import httpx
+ >>> from io import BytesIO
+ >>> import torch
+
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
+ >>> with httpx.stream("GET", url) as response:
+ ... image = Image.open(BytesIO(response.read()))
+
+ >>> image_processor = RTDetrV2ImageProcessor.from_pretrained("PekingU/RTDetrV2_r50vd")
+ >>> model = RTDetrV2ForObjectDetection.from_pretrained("PekingU/RTDetrV2_r50vd")
+
+ >>> # prepare image for the model
+ >>> inputs = image_processor(images=image, return_tensors="pt")
+
+ >>> # forward pass
+ >>> outputs = model(**inputs)
+
+ >>> logits = outputs.logits
+ >>> list(logits.shape)
+ [1, 300, 80]
+
+ >>> boxes = outputs.pred_boxes
+ >>> list(boxes.shape)
+ [1, 300, 4]
+
+ >>> # convert outputs (bounding boxes and class logits) to Pascal VOC format (xmin, ymin, xmax, ymax)
+ >>> target_sizes = torch.tensor([image.size[::-1]])
+ >>> results = image_processor.post_process_object_detection(outputs, threshold=0.9, target_sizes=target_sizes)[
+ ... 0
+ ... ]
+
+ >>> for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
+ ... box = [round(i, 2) for i in box.tolist()]
+ ... print(
+ ... f"Detected {model.config.id2label[label.item()]} with confidence "
+ ... f"{round(score.item(), 3)} at location {box}"
+ ... )
+ Detected sofa with confidence 0.97 at location [0.14, 0.38, 640.13, 476.21]
+ Detected cat with confidence 0.96 at location [343.38, 24.28, 640.14, 371.5]
+ Detected cat with confidence 0.958 at location [13.23, 54.18, 318.98, 472.22]
+ Detected remote with confidence 0.951 at location [40.11, 73.44, 175.96, 118.48]
+ Detected remote with confidence 0.924 at location [333.73, 76.58, 369.97, 186.99]
+ ```"""
+ outputs = self.model(
+ pixel_values,
+ pixel_mask=pixel_mask,
+ encoder_outputs=encoder_outputs,
+ inputs_embeds=inputs_embeds,
+ labels=labels,
+ **kwargs,
+ )
+
+ denoising_meta_values = outputs.denoising_meta_values if self.training else None
+
+ outputs_class = outputs.intermediate_logits
+ outputs_coord = outputs.intermediate_reference_points
+ predicted_corners = outputs.intermediate_predicted_corners
+ initial_reference_points = outputs.initial_reference_points
+
+ logits = outputs_class[:, -1]
+ pred_boxes = outputs_coord[:, -1]
+
+ loss, loss_dict, auxiliary_outputs, enc_topk_logits, enc_topk_bboxes = None, None, None, None, None
+ if labels is not None:
+ enc_topk_logits = outputs.enc_topk_logits
+ enc_topk_bboxes = outputs.enc_topk_bboxes
+ loss, loss_dict, auxiliary_outputs = self.loss_function(
+ logits,
+ labels,
+ self.device,
+ pred_boxes,
+ self.config,
+ outputs_class,
+ outputs_coord,
+ enc_topk_logits=enc_topk_logits,
+ enc_topk_bboxes=enc_topk_bboxes,
+ denoising_meta_values=denoising_meta_values,
+ predicted_corners=predicted_corners,
+ initial_reference_points=initial_reference_points,
+ **kwargs,
+ )
+
+ return RTDetrV2ObjectDetectionOutput(
+ loss=loss,
+ loss_dict=loss_dict,
+ logits=logits,
+ pred_boxes=pred_boxes,
+ auxiliary_outputs=auxiliary_outputs,
+ last_hidden_state=outputs.last_hidden_state,
+ intermediate_hidden_states=outputs.intermediate_hidden_states,
+ intermediate_logits=outputs.intermediate_logits,
+ intermediate_reference_points=outputs.intermediate_reference_points,
+ intermediate_predicted_corners=outputs.intermediate_predicted_corners,
+ initial_reference_points=outputs.initial_reference_points,
+ decoder_hidden_states=outputs.decoder_hidden_states,
+ decoder_attentions=outputs.decoder_attentions,
+ cross_attentions=outputs.cross_attentions,
+ encoder_last_hidden_state=outputs.encoder_last_hidden_state,
+ encoder_hidden_states=outputs.encoder_hidden_states,
+ encoder_attentions=outputs.encoder_attentions,
+ init_reference_points=outputs.init_reference_points,
+ enc_topk_logits=outputs.enc_topk_logits,
+ enc_topk_bboxes=outputs.enc_topk_bboxes,
+ enc_outputs_class=outputs.enc_outputs_class,
+ enc_outputs_coord_logits=outputs.enc_outputs_coord_logits,
+ denoising_meta_values=outputs.denoising_meta_values,
+ )
+
+
+__all__ = ["RTDetrV2Model", "RTDetrV2PreTrainedModel", "RTDetrV2ForObjectDetection"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/rt_detr_v2/modular_rt_detr_v2.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/rt_detr_v2/modular_rt_detr_v2.py
new file mode 100644
index 0000000000000000000000000000000000000000..ccd3997c9bce52988c0da4e4e7807b2d5a26a1ed
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/rt_detr_v2/modular_rt_detr_v2.py
@@ -0,0 +1,465 @@
+# Copyright 2025 Baidu Inc and The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import warnings
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from huggingface_hub.dataclasses import strict
+from torch import Tensor
+
+from ... import initialization as init
+from ...backbone_utils import consolidate_backbone_kwargs_to_config
+from ...configuration_utils import PreTrainedConfig
+from ...processing_utils import Unpack
+from ...utils import TransformersKwargs, auto_docstring, logging, torch_compilable_check
+from ..auto import AutoConfig
+from ..rt_detr.modeling_rt_detr import (
+ RTDetrDecoder,
+ RTDetrDecoderLayer,
+ RTDetrForObjectDetection,
+ RTDetrMLPPredictionHead,
+ RTDetrModel,
+ RTDetrPreTrainedModel,
+)
+
+
+logger = logging.get_logger(__name__)
+
+
+@auto_docstring(checkpoint="PekingU/rtdetr_r18vd")
+@strict
+class RTDetrV2Config(PreTrainedConfig):
+ r"""
+ initializer_bias_prior_prob (`float`, *optional*):
+ The prior probability used by the bias initializer to initialize biases for `enc_score_head` and `class_embed`.
+ If `None`, `prior_prob` computed as `prior_prob = 1 / (num_labels + 1)` while initializing model weights.
+ freeze_backbone_batch_norms (`bool`, *optional*, defaults to `True`):
+ Whether to freeze the batch normalization layers in the backbone.
+ encoder_in_channels (`list`, *optional*, defaults to `[512, 1024, 2048]`):
+ Multi level features input for encoder.
+ feat_strides (`list[int]`, *optional*, defaults to `[8, 16, 32]`):
+ Strides used in each feature map.
+ encode_proj_layers (`list[int]`, *optional*, defaults to `[2]`):
+ Indexes of the projected layers to be used in the encoder.
+ positional_encoding_temperature (`int`, *optional*, defaults to 10000):
+ The temperature parameter used to create the positional encodings.
+ encoder_activation_function (`str`, *optional*, defaults to `"gelu"`):
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
+ activation_function (`str`, *optional*, defaults to `"silu"`):
+ The non-linear activation function (function or string) in the general layer. If string, `"gelu"`,
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
+ eval_size (`tuple[int, int]`, *optional*):
+ Height and width used to compute the effective height and width of the position embeddings after taking
+ into account the stride.
+ normalize_before (`bool`, *optional*, defaults to `False`):
+ Determine whether to apply layer normalization in the transformer encoder layer before self-attention and
+ feed-forward modules.
+ hidden_expansion (`float`, *optional*, defaults to 1.0):
+ Expansion ratio to enlarge the dimension size of RepVGGBlock and CSPRepLayer.
+ num_queries (`int`, *optional*, defaults to 300):
+ Number of object queries.
+ decoder_in_channels (`list`, *optional*, defaults to `[256, 256, 256]`):
+ Multi level features dimension for decoder
+ num_feature_levels (`int`, *optional*, defaults to 3):
+ The number of input feature levels.
+ decoder_n_points (`int`, *optional*, defaults to 4):
+ The number of sampled keys in each feature level for each attention head in the decoder.
+ decoder_activation_function (`str`, *optional*, defaults to `"relu"`):
+ The non-linear activation function (function or string) in the decoder. If string, `"gelu"`,
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
+ num_denoising (`int`, *optional*, defaults to 100):
+ The total number of denoising tasks or queries to be used for contrastive denoising.
+ label_noise_ratio (`float`, *optional*, defaults to 0.5):
+ The fraction of denoising labels to which random noise should be added.
+ box_noise_scale (`float`, *optional*, defaults to 1.0):
+ Scale or magnitude of noise to be added to the bounding boxes.
+ learn_initial_query (`bool`, *optional*, defaults to `False`):
+ Indicates whether the initial query embeddings for the decoder should be learned during training
+ anchor_image_size (`tuple[int, int]`, *optional*):
+ Height and width of the input image used during evaluation to generate the bounding box anchors. If None, automatic generate anchor is applied.
+ with_box_refine (`bool`, *optional*, defaults to `True`):
+ Whether to apply iterative bounding box refinement, where each decoder layer refines the bounding boxes
+ based on the predictions from the previous layer.
+ matcher_alpha (`float`, *optional*, defaults to 0.25):
+ Parameter alpha used by the Hungarian Matcher.
+ matcher_gamma (`float`, *optional*, defaults to 2.0):
+ Parameter gamma used by the Hungarian Matcher.
+ matcher_class_cost (`float`, *optional*, defaults to 2.0):
+ The relative weight of the class loss used by the Hungarian Matcher.
+ matcher_bbox_cost (`float`, *optional*, defaults to 5.0):
+ The relative weight of the bounding box loss used by the Hungarian Matcher.
+ matcher_giou_cost (`float`, *optional*, defaults to 2.0):
+ The relative weight of the giou loss of used by the Hungarian Matcher.
+ use_focal_loss (`bool`, *optional*, defaults to `True`):
+ Parameter informing if focal loss should be used.
+ focal_loss_alpha (`float`, *optional*, defaults to 0.75):
+ Parameter alpha used to compute the focal loss.
+ focal_loss_gamma (`float`, *optional*, defaults to 2.0):
+ Parameter gamma used to compute the focal loss.
+ weight_loss_vfl (`float`, *optional*, defaults to 1.0):
+ Relative weight of the varifocal loss in the object detection loss.
+ weight_loss_bbox (`float`, *optional*, defaults to 5.0):
+ Relative weight of the L1 bounding box loss in the object detection loss.
+ weight_loss_giou (`float`, *optional*, defaults to 2.0):
+ Relative weight of the generalized IoU loss in the object detection loss.
+ decoder_n_levels (`int`, *optional*, defaults to 3):
+ The number of feature levels used by the decoder.
+ decoder_offset_scale (`float`, *optional*, defaults to 0.5):
+ Scaling factor applied to the attention offsets in the decoder.
+ decoder_method (`str`, *optional*, defaults to `"default"`):
+ The method to use for the decoder: `"default"` or `"discrete"`.
+
+ Examples:
+
+ ```python
+ >>> from transformers import RTDetrV2Config, RTDetrV2Model
+
+ >>> # Initializing a RT-DETR configuration
+ >>> configuration = RTDetrV2Config()
+
+ >>> # Initializing a model (with random weights) from the configuration
+ >>> model = RTDetrV2Model(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```
+ """
+
+ model_type = "rt_detr_v2"
+ sub_configs = {"backbone_config": AutoConfig}
+ layer_types = ["basic", "bottleneck"]
+ attribute_map = {
+ "hidden_size": "d_model",
+ "num_attention_heads": "encoder_attention_heads",
+ }
+
+ initializer_range: float = 0.01
+ initializer_bias_prior_prob: float | None = None
+ layer_norm_eps: float = 1e-5
+ batch_norm_eps: float = 1e-5
+ backbone_config: dict | PreTrainedConfig | None = None
+ freeze_backbone_batch_norms: bool = True
+ encoder_hidden_dim: int = 256
+ encoder_in_channels: list[int] | tuple[int, ...] = (512, 1024, 2048)
+ feat_strides: list[int] | tuple[int, ...] = (8, 16, 32)
+ encoder_layers: int = 1
+ encoder_ffn_dim: int = 1024
+ encoder_attention_heads: int = 8
+ dropout: float | int = 0.0
+ activation_dropout: float | int = 0.0
+ encode_proj_layers: list[int] | tuple[int, ...] = (2,)
+ positional_encoding_temperature: int = 10000
+ encoder_activation_function: str = "gelu"
+ activation_function: str = "silu"
+ eval_size: int | None = None
+ normalize_before: bool = False
+ hidden_expansion: float = 1.0
+ d_model: int = 256
+ num_queries: int = 300
+ decoder_in_channels: list[int] | tuple[int, ...] = (256, 256, 256)
+ decoder_ffn_dim: int = 1024
+ num_feature_levels: int = 3
+ decoder_n_points: int = 4
+ decoder_layers: int = 6
+ decoder_attention_heads: int = 8
+ decoder_activation_function: str = "relu"
+ attention_dropout: float | int = 0.0
+ num_denoising: int = 100
+ label_noise_ratio: float = 0.5
+ box_noise_scale: float = 1.0
+ learn_initial_query: bool = False
+ anchor_image_size: int | list[int] | None = None
+ with_box_refine: bool = True
+ is_encoder_decoder: bool = True
+ matcher_alpha: float = 0.25
+ matcher_gamma: float = 2.0
+ matcher_class_cost: float = 2.0
+ matcher_bbox_cost: float = 5.0
+ matcher_giou_cost: float = 2.0
+ use_focal_loss: bool = True
+ auxiliary_loss: bool = True
+ focal_loss_alpha: float = 0.75
+ focal_loss_gamma: float = 2.0
+ weight_loss_vfl: float = 1.0
+ weight_loss_bbox: float = 5.0
+ weight_loss_giou: float = 2.0
+ eos_coefficient: float = 1e-4
+ decoder_n_levels: int = 3
+ decoder_offset_scale: float = 0.5
+ decoder_method: str = "default"
+ tie_word_embeddings: bool = True
+
+ def __post_init__(self, **kwargs):
+ self.backbone_config, kwargs = consolidate_backbone_kwargs_to_config(
+ backbone_config=self.backbone_config,
+ default_config_type="rt_detr_resnet",
+ default_config_kwargs={"out_indices": [2, 3, 4]},
+ **kwargs,
+ )
+ super().__post_init__(**kwargs)
+
+
+def multi_scale_deformable_attention_v2(
+ value: Tensor,
+ value_spatial_shapes: Tensor,
+ sampling_locations: Tensor,
+ attention_weights: Tensor,
+ num_points_list: list[int],
+ method="default",
+) -> Tensor:
+ batch_size, _, num_heads, hidden_dim = value.shape
+ _, num_queries, num_heads, num_levels, num_points = sampling_locations.shape
+ value_list = (
+ value.permute(0, 2, 3, 1)
+ .flatten(0, 1)
+ .split([height * width for height, width in value_spatial_shapes], dim=-1)
+ )
+ # sampling_offsets [8, 480, 8, 12, 2]
+ if method == "default":
+ sampling_grids = 2 * sampling_locations - 1
+ elif method == "discrete":
+ sampling_grids = sampling_locations
+ sampling_grids = sampling_grids.permute(0, 2, 1, 3, 4).flatten(0, 1)
+ sampling_grids = sampling_grids.split(num_points_list, dim=-2)
+ sampling_value_list = []
+ for level_id, (height, width) in enumerate(value_spatial_shapes):
+ # batch_size, height*width, num_heads, hidden_dim
+ # -> batch_size, height*width, num_heads*hidden_dim
+ # -> batch_size, num_heads*hidden_dim, height*width
+ # -> batch_size*num_heads, hidden_dim, height, width
+ value_l_ = value_list[level_id].reshape(batch_size * num_heads, hidden_dim, height, width)
+ # batch_size, num_queries, num_heads, num_points, 2
+ # -> batch_size, num_heads, num_queries, num_points, 2
+ # -> batch_size*num_heads, num_queries, num_points, 2
+ sampling_grid_l_ = sampling_grids[level_id]
+ # batch_size*num_heads, hidden_dim, num_queries, num_points
+ if method == "default":
+ sampling_value_l_ = nn.functional.grid_sample(
+ value_l_, sampling_grid_l_, mode="bilinear", padding_mode="zeros", align_corners=False
+ )
+ elif method == "discrete":
+ sampling_coord = (sampling_grid_l_ * torch.tensor([[width, height]], device=value.device) + 0.5).to(
+ torch.int64
+ )
+
+ # Separate clamping for x and y coordinates
+ sampling_coord_x = sampling_coord[..., 0].clamp(0, width - 1)
+ sampling_coord_y = sampling_coord[..., 1].clamp(0, height - 1)
+
+ # Combine the clamped coordinates
+ sampling_coord = torch.stack([sampling_coord_x, sampling_coord_y], dim=-1)
+ sampling_coord = sampling_coord.reshape(batch_size * num_heads, num_queries * num_points_list[level_id], 2)
+ sampling_idx = (
+ torch.arange(sampling_coord.shape[0], device=value.device)
+ .unsqueeze(-1)
+ .repeat(1, sampling_coord.shape[1])
+ )
+ sampling_value_l_ = value_l_[sampling_idx, :, sampling_coord[..., 1], sampling_coord[..., 0]]
+ sampling_value_l_ = sampling_value_l_.transpose(1, 2).reshape(
+ batch_size * num_heads, hidden_dim, num_queries, num_points_list[level_id]
+ )
+ sampling_value_list.append(sampling_value_l_)
+ # (batch_size, num_queries, num_heads, num_levels, num_points)
+ # -> (batch_size, num_heads, num_queries, num_levels, num_points)
+ # -> (batch_size, num_heads, 1, num_queries, num_levels*num_points)
+ attention_weights = attention_weights.permute(0, 2, 1, 3).reshape(
+ batch_size * num_heads, 1, num_queries, sum(num_points_list)
+ )
+ output = (
+ (torch.concat(sampling_value_list, dim=-1) * attention_weights)
+ .sum(-1)
+ .view(batch_size, num_heads * hidden_dim, num_queries)
+ )
+ return output.transpose(1, 2).contiguous()
+
+
+# the main change
+class RTDetrV2MultiscaleDeformableAttention(nn.Module):
+ """
+ RTDetrV2 version of multiscale deformable attention, extending the base implementation
+ with improved offset handling and initialization.
+ """
+
+ def __init__(self, config: RTDetrV2Config):
+ super().__init__()
+ num_heads = config.decoder_attention_heads
+ n_points = config.decoder_n_points
+
+ if config.d_model % num_heads != 0:
+ raise ValueError(
+ f"embed_dim (d_model) must be divisible by num_heads, but got {config.d_model} and {num_heads}"
+ )
+ dim_per_head = config.d_model // num_heads
+ # check if dim_per_head is power of 2
+ if not ((dim_per_head & (dim_per_head - 1) == 0) and dim_per_head != 0):
+ warnings.warn(
+ "You'd better set embed_dim (d_model) in RTDetrV2MultiscaleDeformableAttention to make the"
+ " dimension of each attention head a power of 2 which is more efficient in the authors' CUDA"
+ " implementation."
+ )
+
+ self.im2col_step = 64
+
+ self.d_model = config.d_model
+
+ # V2-specific attributes
+ self.n_levels = config.decoder_n_levels
+ self.n_heads = num_heads
+ self.n_points = n_points
+
+ self.sampling_offsets = nn.Linear(config.d_model, num_heads * self.n_levels * n_points * 2)
+ self.attention_weights = nn.Linear(config.d_model, num_heads * self.n_levels * n_points)
+ self.value_proj = nn.Linear(config.d_model, config.d_model)
+ self.output_proj = nn.Linear(config.d_model, config.d_model)
+
+ self.offset_scale = config.decoder_offset_scale
+ self.method = config.decoder_method
+
+ # Initialize n_points list and scale
+ n_points_list = [self.n_points for _ in range(self.n_levels)]
+ self.n_points_list = n_points_list
+ n_points_scale = [1 / n for n in n_points_list for _ in range(n)]
+ self.register_buffer("n_points_scale", torch.tensor(n_points_scale, dtype=torch.float32))
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor | None = None,
+ encoder_hidden_states=None,
+ encoder_attention_mask=None,
+ position_embeddings: torch.Tensor | None = None,
+ reference_points=None,
+ spatial_shapes=None,
+ spatial_shapes_list=None,
+ level_start_index=None,
+ **kwargs: Unpack[TransformersKwargs],
+ ):
+ # Process inputs up to sampling locations calculation using parent class logic
+ if position_embeddings is not None:
+ hidden_states = hidden_states + position_embeddings
+
+ batch_size, num_queries, _ = hidden_states.shape
+ batch_size, sequence_length, _ = encoder_hidden_states.shape
+ torch_compilable_check(
+ (spatial_shapes[:, 0] * spatial_shapes[:, 1]).sum() == sequence_length,
+ "Make sure to align the spatial shapes with the sequence length of the encoder hidden states",
+ )
+
+ value = self.value_proj(encoder_hidden_states)
+ if attention_mask is not None:
+ value = value.masked_fill(~attention_mask[..., None], float(0))
+ value = value.view(batch_size, sequence_length, self.n_heads, self.d_model // self.n_heads)
+
+ # V2-specific sampling offsets shape
+ sampling_offsets = self.sampling_offsets(hidden_states).view(
+ batch_size, num_queries, self.n_heads, self.n_levels * self.n_points, 2
+ )
+
+ attention_weights = self.attention_weights(hidden_states).view(
+ batch_size, num_queries, self.n_heads, self.n_levels * self.n_points
+ )
+ attention_weights = F.softmax(attention_weights, -1)
+
+ # V2-specific sampling locations calculation
+ if reference_points.shape[-1] == 2:
+ offset_normalizer = torch.stack([spatial_shapes[..., 1], spatial_shapes[..., 0]], -1)
+ sampling_locations = (
+ reference_points[:, :, None, :, None, :]
+ + sampling_offsets / offset_normalizer[None, None, None, :, None, :]
+ )
+ elif reference_points.shape[-1] == 4:
+ n_points_scale = self.n_points_scale.to(dtype=hidden_states.dtype).unsqueeze(-1)
+ offset = sampling_offsets * n_points_scale * reference_points[:, :, None, :, 2:] * self.offset_scale
+ sampling_locations = reference_points[:, :, None, :, :2] + offset
+ else:
+ raise ValueError(f"Last dim of reference_points must be 2 or 4, but got {reference_points.shape[-1]}")
+
+ # V2-specific attention implementation choice
+ output = multi_scale_deformable_attention_v2(
+ value, spatial_shapes_list, sampling_locations, attention_weights, self.n_points_list, self.method
+ )
+
+ output = self.output_proj(output)
+ return output, attention_weights
+
+
+class RTDetrV2DecoderLayer(RTDetrDecoderLayer):
+ def __init__(self, config: RTDetrV2Config):
+ # initialize parent class
+ super().__init__(config)
+ # override only the encoder attention module with v2 version
+ self.encoder_attn = RTDetrV2MultiscaleDeformableAttention(config)
+
+
+class RTDetrV2PreTrainedModel(RTDetrPreTrainedModel):
+ def _init_weights(self, module):
+ super()._init_weights(module)
+ if isinstance(module, RTDetrV2MultiscaleDeformableAttention):
+ n_points_scale = [1 / n for n in module.n_points_list for _ in range(n)]
+ init.copy_(module.n_points_scale, torch.tensor(n_points_scale, dtype=torch.float32))
+
+
+class RTDetrV2Decoder(RTDetrDecoder):
+ def __init__(self, config: RTDetrV2Config):
+ super().__init__(config)
+ self.layers = nn.ModuleList([RTDetrV2DecoderLayer(config) for _ in range(config.decoder_layers)])
+
+
+class RTDetrV2Model(RTDetrModel):
+ def __init__(self, config: RTDetrV2Config):
+ super().__init__(config)
+ # decoder
+ self.decoder = RTDetrV2Decoder(config)
+
+
+class RTDetrV2MLPPredictionHead(RTDetrMLPPredictionHead):
+ pass
+
+
+class RTDetrV2ForObjectDetection(RTDetrForObjectDetection, RTDetrV2PreTrainedModel):
+ _tied_weights_keys = {
+ r"bbox_embed.(?![0])\d+": r"bbox_embed.0",
+ r"class_embed.(?![0])\d+": r"^class_embed.0",
+ "class_embed": "model.decoder.class_embed",
+ "bbox_embed": "model.decoder.bbox_embed",
+ }
+
+ def __init__(self, config: RTDetrV2Config):
+ RTDetrV2PreTrainedModel.__init__(self, config)
+ # RTDETR encoder-decoder model
+ self.model = RTDetrV2Model(config)
+ self.class_embed = nn.ModuleList(
+ [torch.nn.Linear(config.d_model, config.num_labels) for _ in range(config.decoder_layers)]
+ )
+ self.bbox_embed = nn.ModuleList(
+ [
+ RTDetrV2MLPPredictionHead(config.d_model, config.d_model, 4, num_layers=3)
+ for _ in range(config.decoder_layers)
+ ]
+ )
+ self.model.decoder.class_embed = self.class_embed
+ self.model.decoder.bbox_embed = self.bbox_embed
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+
+__all__ = [
+ "RTDetrV2Config",
+ "RTDetrV2Model",
+ "RTDetrV2PreTrainedModel",
+ "RTDetrV2ForObjectDetection",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/sam_hq/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/sam_hq/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..f56ba4c932c5fc6a011cb876a48964f2322ef1b7
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/sam_hq/__init__.py
@@ -0,0 +1,28 @@
+# Copyright 2025 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_sam_hq import *
+ from .modeling_sam_hq import *
+ from .processing_sam_hq import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/sam_hq/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/sam_hq/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4025ed55b4086b383258acd9ea74dbc2541544a3
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/sam_hq/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/sam_hq/__pycache__/configuration_sam_hq.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/sam_hq/__pycache__/configuration_sam_hq.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..21bbd22037e9eafc8b0569dcb06d4ff9f003568f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/sam_hq/__pycache__/configuration_sam_hq.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/sam_hq/__pycache__/modeling_sam_hq.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/sam_hq/__pycache__/modeling_sam_hq.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..759605d79b48fcfcca7bd21ea804d197ae78bb87
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/sam_hq/__pycache__/modeling_sam_hq.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/sam_hq/__pycache__/modular_sam_hq.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/sam_hq/__pycache__/modular_sam_hq.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b491c4c6bd9b08fd8ba07bc7d055a318603b6a0e
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/sam_hq/__pycache__/modular_sam_hq.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/sam_hq/__pycache__/processing_sam_hq.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/sam_hq/__pycache__/processing_sam_hq.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..160c4fc1ff365f1a348578d9b84e5a3cfd42aa86
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/sam_hq/__pycache__/processing_sam_hq.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/sam_hq/configuration_sam_hq.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/sam_hq/configuration_sam_hq.py
new file mode 100644
index 0000000000000000000000000000000000000000..a6dfa78ce2e4ed91013a23470c6920dadf85fab8
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/sam_hq/configuration_sam_hq.py
@@ -0,0 +1,193 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/sam_hq/modular_sam_hq.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_sam_hq.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2025 Google Inc. HuggingFace Inc. team. All rights reserved.
+#
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring
+
+
+@auto_docstring(checkpoint="syscv-community/sam-hq-vit-base")
+@strict
+class SamHQPromptEncoderConfig(PreTrainedConfig):
+ r"""
+ mask_input_channels (`int`, *optional*, defaults to 16):
+ The number of channels to be fed to the `MaskDecoder` module.
+ num_point_embeddings (`int`, *optional*, defaults to 4):
+ The number of point embeddings to be used.
+ """
+
+ base_config_key = "prompt_encoder_config"
+
+ hidden_size: int = 256
+ image_size: int | list[int] | tuple[int, int] = 1024
+ patch_size: int | list[int] | tuple[int, int] = 16
+ mask_input_channels: int = 16
+ num_point_embeddings: int = 4
+ hidden_act: str = "gelu"
+ layer_norm_eps: float = 1e-6
+
+ def __post_init__(self, **kwargs):
+ self.image_embedding_size = self.image_size // self.patch_size
+ super().__post_init__(**kwargs)
+
+
+@auto_docstring(checkpoint="syscv-community/sam-hq-vit-base")
+@strict
+class SamHQVisionConfig(PreTrainedConfig):
+ r"""
+ output_channels (`int`, *optional*, defaults to 256):
+ Dimensionality of the output channels in the Patch Encoder.
+ use_rel_pos (`bool`, *optional*, defaults to `True`):
+ Whether to use relative position embedding.
+ window_size (`int`, *optional*, defaults to 14):
+ Window size for relative position.
+ global_attn_indexes (`list[int]`, *optional*, defaults to `[2, 5, 8, 11]`):
+ The indexes of the global attention layers.
+ num_pos_feats (`int`, *optional*, defaults to 128):
+ The dimensionality of the position embedding.
+ mlp_dim (`int`, *optional*):
+ The dimensionality of the MLP layer in the Transformer encoder. If `None`, defaults to `mlp_ratio *
+ hidden_size`.
+
+ Example:
+
+ ```python
+ >>> from transformers import (
+ ... SamHQVisionConfig,
+ ... SamHQVisionModel,
+ ... )
+
+ >>> # Initializing a SamHQVisionConfig with `"facebook/sam_hq-vit-huge"` style configuration
+ >>> configuration = SamHQVisionConfig()
+
+ >>> # Initializing a SamHQVisionModel (with random weights) from the `"facebook/sam_hq-vit-huge"` style configuration
+ >>> model = SamHQVisionModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ base_config_key = "vision_config"
+ model_type = "sam_hq_vision_model"
+
+ hidden_size: int = 768
+ output_channels: int = 256
+ num_hidden_layers: int = 12
+ num_attention_heads: int = 12
+ num_channels: int = 3
+ image_size: int | list[int] | tuple[int, int] = 1024
+ patch_size: int | list[int] | tuple[int, int] = 16
+ hidden_act: str = "gelu"
+ layer_norm_eps: float = 1e-06
+ attention_dropout: float | int = 0.0
+ initializer_range: float = 1e-10
+ qkv_bias: bool = True
+ mlp_ratio: float = 4.0
+ use_abs_pos: bool = True
+ use_rel_pos: bool = True
+ window_size: int = 14
+ global_attn_indexes: list[int] | tuple[int, ...] = (2, 5, 8, 11)
+ num_pos_feats: int = 128
+ mlp_dim: int | None = None
+
+ def __post_init__(self, **kwargs):
+ self.mlp_dim = int(self.hidden_size * self.mlp_ratio) if self.mlp_dim is None else self.mlp_dim
+ self.scale = self.hidden_size // 2
+ super().__post_init__(**kwargs)
+
+
+@auto_docstring(checkpoint="syscv-community/sam-hq-vit-base")
+@strict
+class SamHQMaskDecoderConfig(PreTrainedConfig):
+ r"""
+ mlp_dim (`int`, *optional*, defaults to 2048):
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
+ attention_downsample_rate (`int`, *optional*, defaults to 2):
+ The downsampling rate of the attention layer.
+ num_multimask_outputs (`int`, *optional*, defaults to 3):
+ The number of outputs from the `SamMaskDecoder` module. In the Segment Anything paper, this is set to 3.
+ iou_head_depth (`int`, *optional*, defaults to 3):
+ The number of layers in the IoU head module.
+ iou_head_hidden_dim (`int`, *optional*, defaults to 256):
+ The dimensionality of the hidden states in the IoU head module.
+ vit_dim (`int`, *optional*, defaults to 768):
+ Dimensionality of the Vision Transformer (ViT) used in the `SamHQMaskDecoder` module.
+ """
+
+ base_config_key = "mask_decoder_config"
+
+ hidden_size: int = 256
+ hidden_act: str = "relu"
+ mlp_dim: int = 2048
+ num_hidden_layers: int = 2
+ num_attention_heads: int = 8
+ attention_downsample_rate: int = 2
+ num_multimask_outputs: int = 3
+ iou_head_depth: int = 3
+ iou_head_hidden_dim: int = 256
+ layer_norm_eps: float = 1e-6
+
+ vit_dim: int = 768
+
+
+@auto_docstring(checkpoint="syscv-community/sam-hq-vit-base")
+@strict
+class SamHQConfig(PreTrainedConfig):
+ r"""
+ prompt_encoder_config (Union[`dict`, `SamHQPromptEncoderConfig`], *optional*):
+ Dictionary of configuration options used to initialize [`SamHQPromptEncoderConfig`].
+ mask_decoder_config (Union[`dict`, `SamHQMaskDecoderConfig`], *optional*):
+ Dictionary of configuration options used to initialize [`SamHQMaskDecoderConfig`].
+ """
+
+ model_type = "sam_hq"
+ sub_configs = {
+ "prompt_encoder_config": SamHQPromptEncoderConfig,
+ "mask_decoder_config": SamHQMaskDecoderConfig,
+ "vision_config": SamHQVisionConfig,
+ }
+
+ vision_config: dict | PreTrainedConfig | None = None
+ prompt_encoder_config: dict | PreTrainedConfig | None = None
+ mask_decoder_config: dict | PreTrainedConfig | None = None
+ initializer_range: float = 0.02
+ tie_word_embeddings: bool = True
+
+ def __post_init__(self, **kwargs):
+ if isinstance(self.vision_config, dict):
+ self.vision_config = SamHQVisionConfig(**self.vision_config)
+ elif self.vision_config is None:
+ self.vision_config = SamHQVisionConfig()
+
+ if isinstance(self.prompt_encoder_config, dict):
+ self.prompt_encoder_config = SamHQPromptEncoderConfig(**self.prompt_encoder_config)
+ elif self.prompt_encoder_config is None:
+ self.prompt_encoder_config = SamHQPromptEncoderConfig()
+
+ if isinstance(self.mask_decoder_config, dict):
+ self.mask_decoder_config = SamHQMaskDecoderConfig(**self.mask_decoder_config)
+ elif self.mask_decoder_config is None:
+ self.mask_decoder_config = SamHQMaskDecoderConfig()
+
+ super().__post_init__(**kwargs)
+
+
+__all__ = ["SamHQVisionConfig", "SamHQMaskDecoderConfig", "SamHQPromptEncoderConfig", "SamHQConfig"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/sam_hq/modeling_sam_hq.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/sam_hq/modeling_sam_hq.py
new file mode 100644
index 0000000000000000000000000000000000000000..00c92f1d07998fe9bc229b127137fb3891ba3ea4
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/sam_hq/modeling_sam_hq.py
@@ -0,0 +1,1490 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/sam_hq/modular_sam_hq.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_sam_hq.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2025 Google Inc. HuggingFace Inc. team. All rights reserved.
+#
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import collections
+from collections.abc import Callable
+from dataclasses import dataclass
+
+import numpy as np
+import torch
+import torch.nn.functional as F
+from torch import Tensor, nn
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import BaseModelOutput
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import auto_docstring, logging
+from ...utils.generic import ModelOutput, TransformersKwargs, merge_with_config_defaults
+from ...utils.output_capturing import OutputRecorder, capture_outputs
+from .configuration_sam_hq import SamHQConfig, SamHQMaskDecoderConfig, SamHQPromptEncoderConfig, SamHQVisionConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+@auto_docstring(
+ custom_intro="""
+ Base class for sam_hq vision model's outputs that also contains image embeddings obtained by applying the projection
+ layer to the pooler_output.
+ """
+)
+@dataclass
+class SamHQVisionEncoderOutput(ModelOutput):
+ r"""
+ image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
+ The image embeddings obtained by applying the projection layer to the pooler_output.
+ intermediate_embeddings (`list(torch.FloatTensor)`, *optional*):
+ A list of intermediate embeddings collected from certain blocks within the model, typically those without
+ windowed attention. Each element in the list is of shape `(batch_size, sequence_length, hidden_size)`.
+ This is specific to SAM-HQ and not present in base SAM.
+ """
+
+ image_embeds: torch.FloatTensor | None = None
+ last_hidden_state: torch.FloatTensor | None = None
+ hidden_states: tuple[torch.FloatTensor, ...] | None = None
+ attentions: tuple[torch.FloatTensor, ...] | None = None
+
+ intermediate_embeddings: list[torch.FloatTensor] | None = None
+
+
+@dataclass
+class SamHQMMaskDecoderOutputs(ModelOutput):
+ r"""
+ masks (`torch.FloatTensor` of shape `(batch_size, num_prompts, num_masks, height, width)`):
+ The predicted masks for the input image. The masks are of shape `(batch_size, num_prompts, num_masks, height, width)`.
+ iou_scores (`torch.FloatTensor` of shape `(batch_size, num_prompts, num_masks)`):
+ The predicted IoU scores for each mask. The scores are of shape `(batch_size, num_prompts, num_masks)`.
+ mask_decoder_attentions (`torch.FloatTensor`, *optional*):
+ The attention weights from the mask decoder, if `output_attentions=True` was passed during the forward pass.
+ This is specific to SAM-HQ and not present in base SAM.
+ """
+
+ masks: torch.FloatTensor
+ iou_scores: torch.FloatTensor | None = None
+ mask_decoder_attentions: torch.FloatTensor | None = None
+
+
+@auto_docstring(
+ custom_intro="""
+ Base class for Segment-Anything model's output
+ """
+)
+@dataclass
+class SamHQImageSegmentationOutput(ModelOutput):
+ r"""
+ iou_scores (`torch.FloatTensor` of shape `(batch_size, num_masks)`):
+ The iou scores of the predicted masks.
+ pred_masks (`torch.FloatTensor` of shape `(batch_size, num_masks, height, width)`):
+ The predicted low resolutions masks. Needs to be post-processed by the processor
+ vision_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
+
+ Hidden-states of the vision model at the output of each layer plus the optional initial embedding outputs.
+ vision_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
+ sequence_length)`.
+
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
+ heads.
+ mask_decoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
+ sequence_length)`.
+
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
+ heads.
+ """
+
+ iou_scores: torch.FloatTensor | None = None
+ pred_masks: torch.FloatTensor | None = None
+ vision_hidden_states: tuple[torch.FloatTensor, ...] | None = None
+ vision_attentions: tuple[torch.FloatTensor, ...] | None = None
+ mask_decoder_attentions: tuple[torch.FloatTensor, ...] | None = None
+
+
+class SamHQVisionAttention(nn.Module):
+ """Multi-head Attention block with relative position embeddings."""
+
+ def __init__(self, config, window_size):
+ super().__init__()
+ input_size = (
+ (config.image_size // config.patch_size, config.image_size // config.patch_size)
+ if window_size == 0
+ else (window_size, window_size)
+ )
+
+ self.num_attention_heads = config.num_attention_heads
+ head_dim = config.hidden_size // config.num_attention_heads
+ self.scale = head_dim**-0.5
+ self.dropout = config.attention_dropout
+
+ self.qkv = nn.Linear(config.hidden_size, config.hidden_size * 3, bias=config.qkv_bias)
+ self.proj = nn.Linear(config.hidden_size, config.hidden_size)
+
+ self.use_rel_pos = config.use_rel_pos
+ if self.use_rel_pos:
+ if input_size is None:
+ raise ValueError("Input size must be provided if using relative positional encoding.")
+
+ # initialize relative positional embeddings
+ self.rel_pos_h = nn.Parameter(torch.zeros(2 * input_size[0] - 1, head_dim))
+ self.rel_pos_w = nn.Parameter(torch.zeros(2 * input_size[1] - 1, head_dim))
+
+ def get_rel_pos(self, q_size: int, k_size: int, rel_pos: torch.Tensor) -> torch.Tensor:
+ """
+ Get relative positional embeddings according to the relative positions of
+ query and key sizes.
+
+ Args:
+ q_size (int):
+ size of the query.
+ k_size (int):
+ size of key k.
+ rel_pos (`torch.Tensor`):
+ relative position embeddings (L, channel).
+
+ Returns:
+ Extracted positional embeddings according to relative positions.
+ """
+ max_rel_dist = int(2 * max(q_size, k_size) - 1)
+ # Interpolate rel pos.
+ rel_pos_resized = F.interpolate(
+ rel_pos.reshape(1, rel_pos.shape[0], -1).transpose(1, 2),
+ size=max_rel_dist,
+ mode="linear",
+ )
+ rel_pos_resized = rel_pos_resized.reshape(-1, max_rel_dist).permute(1, 0)
+
+ # Scale the coords with short length if shapes for q and k are different.
+ q_coords = torch.arange(q_size)[:, None] * max(k_size / q_size, 1.0)
+ k_coords = torch.arange(k_size)[None, :] * max(q_size / k_size, 1.0)
+ relative_coords = (q_coords - k_coords) + (k_size - 1) * max(q_size / k_size, 1.0)
+
+ return rel_pos_resized[relative_coords.long()]
+
+ def get_decomposed_rel_pos(
+ self,
+ query: torch.Tensor,
+ rel_pos_h: torch.Tensor,
+ rel_pos_w: torch.Tensor,
+ q_size: tuple[int, int],
+ k_size: tuple[int, int],
+ ) -> torch.Tensor:
+ """
+ Calculate decomposed Relative Positional Embeddings from :paper:`mvitv2`.
+ https://github.com/facebookresearch/mvit/blob/19786631e330df9f3622e5402b4a419a263a2c80/mvit/models/attention.py
+
+ Args:
+ query (`torch.Tensor`):
+ query q in the attention layer with shape (batch_size, query_height * query_width, channel).
+ rel_pos_h (`torch.Tensor`):
+ relative position embeddings (Lh, channel) for height axis.
+ rel_pos_w (`torch.Tensor`):
+ relative position embeddings (Lw, channel) for width axis.
+ q_size (tuple):
+ spatial sequence size of query q with (query_height, query_width).
+ k_size (tuple):
+ spatial sequence size of key k with (key_height, key_width).
+
+ Returns:
+ decomposed_rel_pos (`torch.Tensor`):
+ decomposed relative position embeddings.
+ """
+ query_height, query_width = q_size
+ key_height, key_width = k_size
+ relative_position_height = self.get_rel_pos(query_height, key_height, rel_pos_h)
+ relative_position_width = self.get_rel_pos(query_width, key_width, rel_pos_w)
+
+ batch_size, _, dim = query.shape
+ reshaped_query = query.reshape(batch_size, query_height, query_width, dim)
+ rel_h = torch.einsum("bhwc,hkc->bhwk", reshaped_query, relative_position_height)
+ rel_w = torch.einsum("bhwc,wkc->bhwk", reshaped_query, relative_position_width)
+
+ decomposed_rel_pos = rel_h[:, :, :, :, None] + rel_w[:, :, :, None, :]
+
+ return decomposed_rel_pos
+
+ def forward(self, hidden_states: torch.Tensor, output_attentions=None) -> tuple[torch.Tensor, torch.Tensor]:
+ batch_size, height, width, _ = hidden_states.shape
+ # qkv with shape (3, batch_size, nHead, height * width, channel)
+ qkv = (
+ self.qkv(hidden_states)
+ .reshape(batch_size, height * width, 3, self.num_attention_heads, -1)
+ .permute(2, 0, 3, 1, 4)
+ )
+ # q, k, v with shape (batch_size * nHead, height * width, channel)
+ query, key, value = qkv.reshape(3, batch_size * self.num_attention_heads, height * width, -1).unbind(0)
+
+ attn_weights = (query * self.scale) @ key.transpose(-2, -1)
+
+ if self.use_rel_pos:
+ decomposed_rel_pos = self.get_decomposed_rel_pos(
+ query, self.rel_pos_h, self.rel_pos_w, (height, width), (height, width)
+ )
+ decomposed_rel_pos = decomposed_rel_pos.reshape_as(attn_weights)
+ attn_weights = attn_weights + decomposed_rel_pos
+
+ attn_weights = torch.nn.functional.softmax(attn_weights, dtype=torch.float32, dim=-1).to(query.dtype)
+
+ attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
+
+ attn_output = (attn_probs @ value).reshape(batch_size, self.num_attention_heads, height, width, -1)
+ attn_output = attn_output.permute(0, 2, 3, 1, 4).reshape(batch_size, height, width, -1)
+
+ attn_output = self.proj(attn_output)
+ return attn_output, attn_weights
+
+
+class SamHQMLPBlock(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.lin1 = nn.Linear(config.hidden_size, config.mlp_dim)
+ self.lin2 = nn.Linear(config.mlp_dim, config.hidden_size)
+ self.act = ACT2FN[config.hidden_act]
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.lin1(hidden_states)
+ hidden_states = self.act(hidden_states)
+ hidden_states = self.lin2(hidden_states)
+ return hidden_states
+
+
+class SamHQVisionSdpaAttention(SamHQVisionAttention):
+ """
+ Multi-head Attention block with relative position embeddings.
+ Using SDPA instead of the default attention.
+ """
+
+ def __init__(self, config, window_size):
+ super().__init__(config, window_size)
+
+ def forward(self, hidden_states: torch.Tensor, output_attentions=False) -> torch.Tensor:
+ if output_attentions:
+ logger.warning_once(
+ f"{self.__class__.__name__} does not support `output_attentions=True`. The returned attention weights will "
+ "be `None`. If you want to get attention weights, please set `attn_implementation='eager'` when loading the model."
+ )
+ batch_size, height, width, _ = hidden_states.shape
+ # qkv with shape (3, B, nHead, H * W, C)
+ qkv = (
+ self.qkv(hidden_states)
+ .reshape(batch_size, height * width, 3, self.num_attention_heads, -1)
+ .permute(2, 0, 3, 1, 4)
+ )
+ # q, k, v with shape (B * nHead, H * W, C)
+ query, key, value = qkv.reshape(3, batch_size * self.num_attention_heads, height * width, -1).unbind(0)
+
+ attn_bias = None
+ if self.use_rel_pos:
+ decomposed_rel_pos = self.get_decomposed_rel_pos(
+ query, self.rel_pos_h, self.rel_pos_w, (height, width), (height, width)
+ )
+ decomposed_rel_pos = decomposed_rel_pos.reshape(
+ batch_size, self.num_attention_heads, height * width, height * width
+ )
+ attn_bias = decomposed_rel_pos
+
+ query = query.view(batch_size, self.num_attention_heads, height * width, -1)
+ key = key.view(batch_size, self.num_attention_heads, height * width, -1)
+ value = value.view(batch_size, self.num_attention_heads, height * width, -1)
+
+ attn_output = torch.nn.functional.scaled_dot_product_attention(query, key, value, attn_mask=attn_bias)
+
+ attn_output = (
+ attn_output.view(batch_size, self.num_attention_heads, height, width, -1)
+ .permute(0, 2, 3, 1, 4)
+ .reshape(batch_size, height, width, -1)
+ )
+
+ attn_output = self.proj(attn_output)
+ return attn_output, None
+
+
+SAM_HQ_VISION_ATTENTION_CLASSES = {
+ "eager": SamHQVisionAttention,
+ "sdpa": SamHQVisionSdpaAttention,
+}
+
+
+class SamHQVisionLayer(GradientCheckpointingLayer):
+ def __init__(self, config, window_size):
+ super().__init__()
+ self.layer_norm1 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.attn = SAM_HQ_VISION_ATTENTION_CLASSES[config._attn_implementation](config, window_size)
+ self.layer_norm2 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.mlp = SamHQMLPBlock(config)
+ self.window_size = window_size
+
+ def window_partition(self, hidden_states: torch.Tensor, window_size: int) -> tuple[torch.Tensor, tuple[int, int]]:
+ """
+ Args:
+ Partition into non-overlapping windows with padding if needed.
+ hidden_states (tensor): input tokens with [batch_size, height, width, channel]. window_size (int): window
+ size.
+
+ Returns:
+ windows: windows after partition with [batch_size * num_windows, window_size, window_size, channel].
+ (pad_height, pad_width): padded height and width before partition
+ """
+ batch_size, height, width, channel = hidden_states.shape
+
+ pad_h = (window_size - height % window_size) % window_size
+ pad_w = (window_size - width % window_size) % window_size
+ hidden_states = F.pad(hidden_states, (0, 0, 0, pad_w, 0, pad_h))
+ pad_height, pad_width = height + pad_h, width + pad_w
+
+ hidden_states = hidden_states.reshape(
+ batch_size, pad_height // window_size, window_size, pad_width // window_size, window_size, channel
+ )
+ windows = hidden_states.permute(0, 1, 3, 2, 4, 5).contiguous().reshape(-1, window_size, window_size, channel)
+ return windows, (pad_height, pad_width)
+
+ def window_unpartition(
+ self, windows: torch.Tensor, window_size: int, padding_shape: tuple[int, int], original_shape: tuple[int, int]
+ ) -> torch.Tensor:
+ """
+ Args:
+ Window unpartition into original sequences and removing padding.
+ hidden_states (tensor):
+ input tokens with [batch_size * num_windows, window_size, window_size, channel].
+ window_size (int):
+ window size.
+ padding_shape (Tuple):
+ padded height and width (pad_height, pad_width).
+ original_shape (Tuple): original height and width (height, width) before padding.
+
+ Returns:
+ hidden_states: unpartitioned sequences with [batch_size, height, width, channel].
+ """
+ pad_height, pad_width = padding_shape
+ height, width = original_shape
+ batch_size = windows.shape[0] // (pad_height * pad_width // window_size // window_size)
+ hidden_states = windows.reshape(
+ batch_size, pad_height // window_size, pad_width // window_size, window_size, window_size, -1
+ )
+ hidden_states = (
+ hidden_states.permute(0, 1, 3, 2, 4, 5).contiguous().reshape(batch_size, pad_height, pad_width, -1)
+ )
+
+ hidden_states = hidden_states[:, :height, :width, :].contiguous()
+ return hidden_states
+
+ def forward(self, hidden_states: torch.Tensor) -> tuple[torch.FloatTensor]:
+ residual = hidden_states
+ hidden_states = self.layer_norm1(hidden_states)
+ # Window partition
+ if self.window_size > 0:
+ height, width = hidden_states.shape[1], hidden_states.shape[2]
+ hidden_states, padding_shape = self.window_partition(hidden_states, self.window_size)
+
+ hidden_states, attn_weights = self.attn(
+ hidden_states=hidden_states,
+ )
+ # Reverse window partition
+ if self.window_size > 0:
+ hidden_states = self.window_unpartition(hidden_states, self.window_size, padding_shape, (height, width))
+
+ hidden_states = residual + hidden_states
+ layernorm_output = self.layer_norm2(hidden_states)
+ hidden_states = hidden_states + self.mlp(layernorm_output)
+ return hidden_states
+
+
+class SamHQPositionalEmbedding(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.scale = config.scale
+ self.positional_embedding = nn.Parameter(self.scale * torch.randn((2, config.num_pos_feats)))
+
+ def forward(self, input_coords, input_shape=None):
+ """Positionally encode points that are normalized to [0,1]."""
+ coordinates = input_coords.clone()
+
+ if input_shape is not None:
+ coordinates[:, :, :, 0] = coordinates[:, :, :, 0] / input_shape[1]
+ coordinates[:, :, :, 1] = coordinates[:, :, :, 1] / input_shape[0]
+
+ # assuming coords are in [0, 1]^2 square and have d_1 x ... x d_n x 2 shape
+ coordinates = 2 * coordinates - 1
+ coordinates = coordinates.to(self.positional_embedding.dtype)
+ coordinates = coordinates @ self.positional_embedding
+ coordinates = 2 * np.pi * coordinates
+ # outputs d_1 x ... x d_n x channel shape
+ return torch.cat([torch.sin(coordinates), torch.cos(coordinates)], dim=-1)
+
+
+@auto_docstring
+class SamHQPreTrainedModel(PreTrainedModel):
+ config: SamHQConfig
+ base_model_prefix = "sam_hq"
+ main_input_name = "pixel_values"
+ input_modalities = ("image",)
+ _no_split_modules = ["SamHQVisionAttention"]
+ supports_gradient_checkpointing = True
+ _supports_sdpa = True
+
+ @torch.no_grad()
+ def _init_weights(self, module: nn.Module):
+ super()._init_weights(module)
+ if isinstance(module, SamHQVisionAttention):
+ if module.use_rel_pos:
+ init.zeros_(module.rel_pos_h)
+ init.zeros_(module.rel_pos_w)
+ elif isinstance(module, SamHQVisionEncoder):
+ if self.config.use_abs_pos:
+ init.zeros_(module.pos_embed)
+ elif isinstance(module, SamHQPositionalEmbedding):
+ init.normal_(module.positional_embedding, std=module.scale)
+
+
+class SamHQPatchEmbeddings(nn.Module):
+ """
+ This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
+ `hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
+ Transformer.
+ """
+
+ def __init__(self, config):
+ super().__init__()
+ image_size, patch_size = config.image_size, config.patch_size
+ num_channels, hidden_size = config.num_channels, config.hidden_size
+ image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
+ patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
+ num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
+ self.image_size = image_size
+ self.patch_size = patch_size
+ self.num_channels = num_channels
+ self.num_patches = num_patches
+
+ self.projection = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=patch_size)
+
+ def forward(self, pixel_values):
+ batch_size, num_channels, height, width = pixel_values.shape
+ if num_channels != self.num_channels:
+ raise ValueError(
+ "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
+ )
+ if height != self.image_size[0] or width != self.image_size[1]:
+ raise ValueError(
+ f"Input image size ({height}*{width}) doesn't match model ({self.image_size[0]}*{self.image_size[1]})."
+ )
+ embeddings = self.projection(pixel_values).permute(0, 2, 3, 1)
+ return embeddings
+
+
+class SamHQVisionNeck(nn.Module):
+ def __init__(self, config: SamHQVisionConfig):
+ super().__init__()
+ self.config = config
+
+ self.conv1 = nn.Conv2d(config.hidden_size, config.output_channels, kernel_size=1, bias=False)
+ self.layer_norm1 = SamHQLayerNorm(config.output_channels, data_format="channels_first")
+ self.conv2 = nn.Conv2d(config.output_channels, config.output_channels, kernel_size=3, padding=1, bias=False)
+ self.layer_norm2 = SamHQLayerNorm(config.output_channels, data_format="channels_first")
+
+ def forward(self, hidden_states):
+ hidden_states = hidden_states.permute(0, 3, 1, 2)
+ hidden_states = self.conv1(hidden_states)
+ hidden_states = self.layer_norm1(hidden_states)
+
+ hidden_states = self.conv2(hidden_states)
+ hidden_states = self.layer_norm2(hidden_states)
+ return hidden_states
+
+
+class SamHQVisionEncoder(SamHQPreTrainedModel):
+ _can_record_outputs = {
+ "hidden_states": SamHQVisionLayer,
+ "attentions": SamHQVisionAttention,
+ }
+
+ def __init__(self, config: SamHQVisionConfig):
+ super().__init__(config)
+ self.config = config
+ self.image_size = config.image_size
+ self.patch_embed = SamHQPatchEmbeddings(config)
+
+ self.pos_embed = None
+ if config.use_abs_pos:
+ # Initialize absolute positional embedding with pretrain image size.
+ self.pos_embed = nn.Parameter(
+ torch.zeros(
+ 1,
+ config.image_size // config.patch_size,
+ config.image_size // config.patch_size,
+ config.hidden_size,
+ )
+ )
+
+ self.layers = nn.ModuleList()
+ for i in range(config.num_hidden_layers):
+ layer = SamHQVisionLayer(
+ config,
+ window_size=config.window_size if i not in config.global_attn_indexes else 0,
+ )
+ self.layers.append(layer)
+
+ self.neck = SamHQVisionNeck(config)
+
+ self.gradient_checkpointing = False
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.patch_embed
+
+ @merge_with_config_defaults
+ @capture_outputs(tie_last_hidden_states=False)
+ def forward(
+ self, pixel_values: torch.FloatTensor | None = None, **kwargs: Unpack[TransformersKwargs]
+ ) -> tuple | SamHQVisionEncoderOutput:
+ if pixel_values is None:
+ raise ValueError("You have to specify pixel_values")
+
+ hidden_states = self.patch_embed(pixel_values)
+ if self.pos_embed is not None:
+ hidden_states = hidden_states + self.pos_embed
+
+ intermediate_embeddings = []
+
+ for layer_module in self.layers:
+ hidden_states = layer_module(hidden_states)
+
+ # Collect embeddings from non-windowed blocks
+ if hasattr(layer_module, "window_size") and layer_module.window_size == 0:
+ intermediate_embeddings.append(hidden_states)
+
+ hidden_states = self.neck(hidden_states)
+
+ return SamHQVisionEncoderOutput(
+ last_hidden_state=hidden_states,
+ intermediate_embeddings=intermediate_embeddings,
+ )
+
+
+class SamHQLayerNorm(nn.LayerNorm):
+ r"""LayerNorm that supports two data formats: channels_last (default) or channels_first.
+ The ordering of the dimensions in the inputs. channels_last corresponds to inputs with shape (batch_size, height,
+ width, channels) while channels_first corresponds to inputs with shape (batch_size, channels, height, width).
+ """
+
+ def __init__(self, normalized_shape, *, eps=1e-6, data_format="channels_last", **kwargs):
+ super().__init__(normalized_shape, eps=eps, **kwargs)
+ if data_format not in ["channels_last", "channels_first"]:
+ raise NotImplementedError(f"Unsupported data format: {data_format}")
+ self.data_format = data_format
+
+ def forward(self, features: torch.Tensor) -> torch.Tensor:
+ """
+ Args:
+ features: Tensor of shape (batch_size, channels, height, width) OR (batch_size, height, width, channels)
+ """
+ if self.data_format == "channels_first":
+ features = features.permute(0, 2, 3, 1)
+ features = super().forward(features)
+ features = features.permute(0, 3, 1, 2)
+ else:
+ features = super().forward(features)
+ return features
+
+
+def eager_attention_forward(
+ module: nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: torch.Tensor | None,
+ scaling: float,
+ dropout: float = 0.0,
+ **kwargs,
+):
+ attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
+ if attention_mask is not None:
+ attn_weights = attn_weights + attention_mask
+
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
+ attn_output = torch.matmul(attn_weights, value)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+
+ return attn_output, attn_weights
+
+
+class SamHQAttention(nn.Module):
+ """
+ SAM_HQ's attention layer that allows for downscaling the size of the embedding after projection to queries, keys, and
+ values.
+ """
+
+ def __init__(self, config, downsample_rate=None):
+ super().__init__()
+ self.config = config
+ self.hidden_size = config.hidden_size
+
+ downsample_rate = config.attention_downsample_rate if downsample_rate is None else downsample_rate
+
+ self.internal_dim = config.hidden_size // downsample_rate
+ self.num_attention_heads = config.num_attention_heads
+ if self.internal_dim % config.num_attention_heads != 0:
+ raise ValueError("num_attention_heads must divide hidden_size.")
+ self.scaling = (self.internal_dim // config.num_attention_heads) ** -0.5
+
+ self.q_proj = nn.Linear(self.hidden_size, self.internal_dim)
+ self.k_proj = nn.Linear(self.hidden_size, self.internal_dim)
+ self.v_proj = nn.Linear(self.hidden_size, self.internal_dim)
+ self.out_proj = nn.Linear(self.internal_dim, self.hidden_size)
+
+ self.is_causal = False
+
+ def _separate_heads(self, hidden_states: Tensor, num_attention_heads: int) -> Tensor:
+ batch, point_batch_size, n_tokens, channel = hidden_states.shape
+ c_per_head = channel // num_attention_heads
+ hidden_states = hidden_states.reshape(batch * point_batch_size, n_tokens, num_attention_heads, c_per_head)
+ return hidden_states.transpose(1, 2)
+
+ def _recombine_heads(self, hidden_states: Tensor, point_batch_size: int) -> Tensor:
+ batch, n_tokens, n_heads, c_per_head = hidden_states.shape
+ return hidden_states.reshape(batch // point_batch_size, point_batch_size, n_tokens, n_heads * c_per_head)
+
+ def forward(
+ self,
+ query: Tensor,
+ key: Tensor,
+ value: Tensor,
+ attention_similarity: Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> Tensor:
+ # Input projections
+ query = self.q_proj(query)
+ key = self.k_proj(key)
+ value = self.v_proj(value)
+
+ point_batch_size = query.shape[1]
+ # Separate into heads
+ query = self._separate_heads(query, self.num_attention_heads)
+ key = self._separate_heads(key, self.num_attention_heads)
+ value = self._separate_heads(value, self.num_attention_heads)
+
+ # SamHQAttention
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query,
+ key,
+ value,
+ attention_mask=attention_similarity,
+ dropout=0.0,
+ scaling=self.scaling,
+ is_causal=self.is_causal,
+ **kwargs,
+ )
+
+ attn_output = self._recombine_heads(attn_output, point_batch_size)
+ attn_output = self.out_proj(attn_output)
+
+ return attn_output, attn_weights
+
+
+class SamHQTwoWayAttentionBlock(nn.Module):
+ def __init__(self, config, attention_downsample_rate: int = 2, skip_first_layer_pe: bool = False):
+ """
+ A transformer block with four layers:
+ (1) self-attention of sparse inputs (2) cross attention of sparse inputs -> dense inputs (3) mlp block on
+ sparse inputs (4) cross attention of dense inputs -> sparse inputs
+
+ Arguments:
+ config (`SamHQMaskDecoderConfig`):
+ The configuration file used to instantiate the block
+ attention_downsample_rate (*optionalk*, int, defaults to 2):
+ The downsample ratio of the block used to reduce the inner dim of the attention.
+ skip_first_layer_pe (*optional*, bool, defaults to `False`):
+ Whether or not to skip the addition of the query_point_embedding on the first layer.
+ """
+ super().__init__()
+
+ self.hidden_size = config.hidden_size
+ self.layer_norm_eps = config.layer_norm_eps
+
+ self.self_attn = SamHQAttention(config, downsample_rate=1)
+ self.layer_norm1 = nn.LayerNorm(self.hidden_size, eps=self.layer_norm_eps)
+
+ self.cross_attn_token_to_image = SamHQAttention(config, downsample_rate=attention_downsample_rate)
+ self.layer_norm2 = nn.LayerNorm(self.hidden_size, eps=self.layer_norm_eps)
+
+ self.mlp = SamHQMLPBlock(config)
+ self.layer_norm3 = nn.LayerNorm(self.hidden_size, eps=self.layer_norm_eps)
+
+ self.layer_norm4 = nn.LayerNorm(self.hidden_size, eps=self.layer_norm_eps)
+ self.cross_attn_image_to_token = SamHQAttention(config, downsample_rate=attention_downsample_rate)
+ self.skip_first_layer_pe = skip_first_layer_pe
+
+ def forward(
+ self,
+ queries: Tensor,
+ keys: Tensor,
+ query_point_embedding: Tensor,
+ key_point_embedding: Tensor,
+ attention_similarity: Tensor,
+ **kwargs: Unpack[TransformersKwargs],
+ ):
+ # Self attention block
+ if self.skip_first_layer_pe:
+ queries, _ = self.self_attn(query=queries, key=queries, value=queries)
+ else:
+ query = queries + query_point_embedding
+ attn_out, _ = self.self_attn(query=query, key=query, value=queries)
+ queries = queries + attn_out
+ queries = self.layer_norm1(queries)
+
+ # Cross attention block, tokens attending to image embedding
+ query = queries + query_point_embedding
+ key = keys + key_point_embedding
+
+ attn_out, _ = self.cross_attn_token_to_image(
+ query=query, key=key, value=keys, attention_similarity=attention_similarity
+ )
+ queries = queries + attn_out
+
+ queries = self.layer_norm2(queries)
+
+ # MLP block
+ mlp_out = self.mlp(queries)
+ queries = queries + mlp_out
+ queries = self.layer_norm3(queries)
+
+ # Cross attention block, image embedding attending to tokens
+ query = queries + query_point_embedding
+ key = keys + key_point_embedding
+
+ attn_out, _ = self.cross_attn_image_to_token(query=key, key=query, value=queries)
+ keys = keys + attn_out
+
+ keys = self.layer_norm4(keys)
+ return queries, keys, attn_out
+
+
+class SamHQTwoWayTransformer(nn.Module):
+ def __init__(self, config: SamHQMaskDecoderConfig):
+ super().__init__()
+ self.config = config
+
+ self.num_hidden_layers = config.num_hidden_layers
+ self.layers = nn.ModuleList()
+
+ for i in range(self.num_hidden_layers):
+ self.layers.append(SamHQTwoWayAttentionBlock(config, skip_first_layer_pe=(i == 0)))
+
+ self.final_attn_token_to_image = SamHQAttention(config)
+ self.layer_norm_final_attn = nn.LayerNorm(config.hidden_size)
+
+ def forward(
+ self,
+ point_embeddings: Tensor,
+ image_embeddings: Tensor,
+ image_positional_embeddings: Tensor,
+ attention_similarity: Tensor,
+ target_embedding=None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutput:
+ if image_embeddings is None:
+ raise ValueError("You have to specify an image_embedding")
+
+ image_embeddings = image_embeddings.flatten(2).transpose(1, 2).unsqueeze(1)
+ image_positional_embeddings = image_positional_embeddings.flatten(2).transpose(1, 2).unsqueeze(1)
+
+ # Prepare queries
+ queries = point_embeddings
+ keys = image_embeddings
+
+ # Apply transformer blocks and final layernorm
+ for layer in self.layers:
+ if target_embedding is not None:
+ queries += target_embedding
+
+ queries, keys, _ = layer(
+ queries=queries,
+ keys=keys,
+ query_point_embedding=point_embeddings,
+ key_point_embedding=image_positional_embeddings,
+ attention_similarity=attention_similarity,
+ **kwargs,
+ )
+ # Apply the final attention layer from the points to the image
+ query = queries + point_embeddings
+ key = keys + image_positional_embeddings
+
+ attn_out, _ = self.final_attn_token_to_image(query=query, key=key, value=keys)
+
+ queries = queries + attn_out
+ queries = self.layer_norm_final_attn(queries)
+ return queries, keys
+
+
+class SamHQFeedForward(nn.Module):
+ def __init__(
+ self, input_dim: int, hidden_dim: int, output_dim: int, num_layers: int, sigmoid_output: bool = False
+ ):
+ super().__init__()
+ self.num_layers = num_layers
+ self.activation = nn.ReLU()
+ self.proj_in = nn.Linear(input_dim, hidden_dim)
+ self.proj_out = nn.Linear(hidden_dim, output_dim)
+ self.layers = nn.ModuleList([nn.Linear(hidden_dim, hidden_dim) for _ in range(num_layers - 2)])
+ self.sigmoid_output = sigmoid_output
+
+ def forward(self, hidden_states):
+ hidden_states = self.proj_in(hidden_states)
+ hidden_states = self.activation(hidden_states)
+ for layer in self.layers:
+ hidden_states = self.activation(layer(hidden_states))
+
+ hidden_states = self.proj_out(hidden_states)
+ if self.sigmoid_output:
+ hidden_states = F.sigmoid(hidden_states)
+ return hidden_states
+
+
+class SamHQMaskDecoder(nn.Module):
+ def __init__(self, config: SamHQMaskDecoderConfig):
+ super().__init__()
+ self.hidden_size = config.hidden_size
+
+ self.num_multimask_outputs = config.num_multimask_outputs
+ self.num_mask_tokens = config.num_multimask_outputs + 1
+
+ self.iou_token = nn.Embedding(1, self.hidden_size)
+ self.mask_tokens = nn.Embedding(self.num_mask_tokens, self.hidden_size)
+
+ self.transformer = SamHQTwoWayTransformer(config)
+
+ self.upscale_conv1 = nn.ConvTranspose2d(self.hidden_size, self.hidden_size // 4, kernel_size=2, stride=2)
+ self.upscale_conv2 = nn.ConvTranspose2d(self.hidden_size // 4, self.hidden_size // 8, kernel_size=2, stride=2)
+ self.upscale_layer_norm = SamHQLayerNorm(self.hidden_size // 4, data_format="channels_first")
+ self.activation = nn.GELU()
+
+ mlps_list = []
+ for _ in range(self.num_mask_tokens):
+ mlps_list += [SamHQFeedForward(self.hidden_size, self.hidden_size, self.hidden_size // 8, 3)]
+ self.output_hypernetworks_mlps = nn.ModuleList(mlps_list)
+
+ self.iou_prediction_head = SamHQFeedForward(
+ self.hidden_size, config.iou_head_hidden_dim, self.num_mask_tokens, config.iou_head_depth
+ )
+
+ self.hq_token = nn.Embedding(1, self.hidden_size)
+ self.hq_mask_mlp = SamHQFeedForward(self.hidden_size, self.hidden_size, self.hidden_size // 8, 3)
+ self.num_mask_tokens = self.num_mask_tokens + 1
+
+ # Compress ViT features
+ self.compress_vit_conv1 = nn.ConvTranspose2d(config.vit_dim, self.hidden_size, kernel_size=2, stride=2)
+ self.compress_vit_norm = SamHQLayerNorm(self.hidden_size, data_format="channels_first")
+ self.compress_vit_conv2 = nn.ConvTranspose2d(self.hidden_size, self.hidden_size // 8, kernel_size=2, stride=2)
+
+ # Embedding encoder
+ self.encoder_conv1 = nn.ConvTranspose2d(self.hidden_size, self.hidden_size // 4, kernel_size=2, stride=2)
+ self.encoder_norm = SamHQLayerNorm(self.hidden_size // 4, data_format="channels_first")
+ self.encoder_conv2 = nn.ConvTranspose2d(self.hidden_size // 4, self.hidden_size // 8, kernel_size=2, stride=2)
+
+ # Embedding mask feature
+ self.mask_conv1 = nn.Conv2d(self.hidden_size // 8, self.hidden_size // 4, kernel_size=3, stride=1, padding=1)
+ self.mask_norm = SamHQLayerNorm(self.hidden_size // 4, data_format="channels_first")
+ self.mask_conv2 = nn.Conv2d(self.hidden_size // 4, self.hidden_size // 8, kernel_size=3, stride=1, padding=1)
+
+ def forward(
+ self,
+ image_embeddings: torch.Tensor,
+ image_positional_embeddings: torch.Tensor,
+ sparse_prompt_embeddings: torch.Tensor,
+ dense_prompt_embeddings: torch.Tensor,
+ multimask_output: bool,
+ hq_token_only: bool,
+ intermediate_embeddings: list[torch.Tensor] | None = None,
+ attention_similarity: torch.Tensor | None = None,
+ target_embedding: torch.Tensor | None = None,
+ ) -> SamHQMMaskDecoderOutputs:
+ """
+ Predict high-quality masks given image and prompt embeddings.
+
+ Args:
+ image_embeddings (`torch.Tensor`):
+ The embeddings from the image encoder.
+ image_positional_embedding (`torch.Tensor`):
+ Positional encoding with the shape of image_embeddings.
+ sparse_prompt_embeddings (`torch.Tensor`):
+ The embeddings of the points and boxes.
+ dense_prompt_embeddings (`torch.Tensor`):
+ The embeddings of the mask inputs.
+ multimask_output (bool):
+ Whether to return multiple masks or a single mask.
+ hq_token_only (bool):
+ Whether to use only the high-quality token output or combine with SAM output.
+ intermediate_embeddings (`torch.Tensor`):
+ Intermediate embeddings from the vision encoder for feature fusion.
+ attention_similarity (`torch.Tensor`, *optional*):
+ Optional tensor for attention similarity computation.
+ target_embedding (`torch.Tensor`, *optional*):
+ Optional target embedding for transformer processing.
+
+ Returns:
+ `Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]]`: A tuple of tensors containing:
+ - A tensor of shape `(batch_size, num_prompts, num_masks, height, width)` containing the output masks.
+ - A tensor of shape `(batch_size, num_prompts, num_masks)` containing the iou predictions for each mask.
+ - (Optional) A tuple containing attention tensors if output_attentions is True.
+ """
+ batch_size, num_channels, height, width = image_embeddings.shape
+ point_batch_size = sparse_prompt_embeddings.shape[1] if sparse_prompt_embeddings is not None else 1
+
+ has_intermediate = intermediate_embeddings is not None and len(intermediate_embeddings) > 0
+
+ if has_intermediate:
+ vit_features = intermediate_embeddings[0].permute(0, 3, 1, 2).contiguous()
+
+ embed_encode = self.encoder_conv1(image_embeddings)
+ embed_encode = self.activation(self.encoder_norm(embed_encode))
+ embed_encode = self.encoder_conv2(embed_encode)
+
+ if has_intermediate:
+ compressed_vit_features = self.compress_vit_conv1(vit_features)
+ compressed_vit_features = self.activation(self.compress_vit_norm(compressed_vit_features))
+ compressed_vit_features = self.compress_vit_conv2(compressed_vit_features)
+
+ hq_features = embed_encode + compressed_vit_features
+ else:
+ hq_features = embed_encode
+
+ output_tokens = torch.cat([self.iou_token.weight, self.mask_tokens.weight, self.hq_token.weight], dim=0)
+ output_tokens = output_tokens.repeat(batch_size, point_batch_size, 1, 1)
+
+ if sparse_prompt_embeddings is not None:
+ tokens = torch.cat([output_tokens, sparse_prompt_embeddings], dim=2)
+ else:
+ tokens = output_tokens
+ point_embeddings = tokens.to(self.iou_token.weight.dtype)
+ image_embeddings = image_embeddings + dense_prompt_embeddings
+ image_embeddings = image_embeddings.repeat_interleave(point_batch_size, 0)
+ image_positional_embeddings = image_positional_embeddings.repeat_interleave(point_batch_size, 0)
+
+ point_embedding, iou_token_out = self.transformer(
+ point_embeddings=point_embeddings,
+ image_embeddings=image_embeddings,
+ image_positional_embeddings=image_positional_embeddings,
+ attention_similarity=attention_similarity,
+ target_embedding=target_embedding,
+ )
+ iou_token_out = point_embedding[:, :, 0, :]
+ mask_tokens_out = point_embedding[:, :, 1 : (1 + self.num_mask_tokens), :]
+
+ image_embeddings = image_embeddings.transpose(2, 3).reshape(
+ batch_size * point_batch_size, num_channels, height, width
+ )
+
+ upscaled_embedding = self.upscale_conv1(image_embeddings)
+ upscaled_embedding = self.activation(self.upscale_layer_norm(upscaled_embedding))
+ upscaled_embedding = self.activation(self.upscale_conv2(upscaled_embedding))
+
+ upscaled_embedding_hq = self.mask_conv1(upscaled_embedding)
+ upscaled_embedding_hq = self.activation(self.mask_norm(upscaled_embedding_hq))
+ upscaled_embedding_hq = self.mask_conv2(upscaled_embedding_hq)
+
+ if hq_features.shape[0] == 1:
+ hq_features = hq_features.repeat(batch_size * point_batch_size, 1, 1, 1)
+ elif hq_features.shape[0] == batch_size and batch_size * point_batch_size != batch_size:
+ hq_features = hq_features.repeat_interleave(point_batch_size, 0)
+ upscaled_embedding_hq = upscaled_embedding_hq + hq_features
+
+ hyper_in_list = []
+ for mask_token_index in range(self.num_mask_tokens):
+ if mask_token_index < self.num_mask_tokens - 1:
+ current_mlp = self.output_hypernetworks_mlps[mask_token_index]
+ else:
+ current_mlp = self.hq_mask_mlp
+ hyper_in_list += [current_mlp(mask_tokens_out[:, :, mask_token_index, :])]
+
+ hyper_in = torch.stack(hyper_in_list, dim=2)
+ _, num_channels, height, width = upscaled_embedding.shape
+ upscaled_embedding = upscaled_embedding.reshape(batch_size, point_batch_size, num_channels, height * width)
+ upscaled_embedding_hq = upscaled_embedding_hq.reshape(
+ batch_size, point_batch_size, num_channels, height * width
+ )
+
+ masks_sam = (hyper_in[:, :, : self.num_mask_tokens - 1] @ upscaled_embedding).reshape(
+ batch_size, point_batch_size, -1, height, width
+ )
+ masks_hq = (hyper_in[:, :, self.num_mask_tokens - 1 :] @ upscaled_embedding_hq).reshape(
+ batch_size, point_batch_size, -1, height, width
+ )
+ masks = torch.cat([masks_sam, masks_hq], dim=2)
+
+ iou_pred = self.iou_prediction_head(iou_token_out)
+
+ if multimask_output:
+ mask_slice = slice(1, self.num_mask_tokens - 1)
+ iou_pred = iou_pred[:, :, mask_slice]
+ # Sort the IoU scores in descending order and get indices
+ iou_pred_sorted, sort_indices = torch.sort(iou_pred, dim=2, descending=True)
+ # Reorder the masks according to sorted scores
+ masks_sam = masks[:, :, mask_slice, :, :]
+ masks_sam = torch.gather(
+ masks_sam,
+ 2,
+ sort_indices[..., None, None].expand(-1, -1, -1, masks_sam.shape[3], masks_sam.shape[4]),
+ )
+ # Update iou_pred with sorted scores
+ iou_pred = iou_pred_sorted
+ else:
+ mask_slice = slice(0, 1)
+ iou_pred = iou_pred[:, :, mask_slice]
+ masks_sam = masks[:, :, mask_slice, :, :]
+
+ masks_hq = masks[:, :, slice(self.num_mask_tokens - 1, self.num_mask_tokens), :, :]
+ if hq_token_only:
+ masks = masks_hq
+ else:
+ masks = masks_sam + masks_hq
+
+ return masks, iou_pred
+
+
+@auto_docstring(
+ custom_intro="""
+ The vision model from SamHQ without any head or projection on top.
+ """
+)
+class SamHQVisionModel(SamHQPreTrainedModel):
+ config: SamHQVisionConfig
+ main_input_name = "pixel_values"
+
+ def __init__(self, config: SamHQVisionConfig):
+ super().__init__(config)
+ self.vision_encoder = SamHQVisionEncoder(config)
+ self.post_init()
+
+ def get_input_embeddings(self) -> nn.Module:
+ return self.vision_encoder.patch_embed
+
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: torch.FloatTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | SamHQVisionEncoderOutput:
+ return self.vision_encoder(pixel_values, **kwargs)
+
+
+class SamHQMaskEmbedding(nn.Module):
+ def __init__(self, config: SamHQPromptEncoderConfig):
+ super().__init__()
+ self.mask_input_channels = config.mask_input_channels // 4
+ self.activation = ACT2FN[config.hidden_act]
+ self.conv1 = nn.Conv2d(1, self.mask_input_channels, kernel_size=2, stride=2)
+ self.conv2 = nn.Conv2d(self.mask_input_channels, config.mask_input_channels, kernel_size=2, stride=2)
+ self.conv3 = nn.Conv2d(config.mask_input_channels, config.hidden_size, kernel_size=1)
+ self.layer_norm1 = SamHQLayerNorm(
+ self.mask_input_channels, eps=config.layer_norm_eps, data_format="channels_first"
+ )
+ self.layer_norm2 = SamHQLayerNorm(
+ self.mask_input_channels * 4, eps=config.layer_norm_eps, data_format="channels_first"
+ )
+
+ def forward(self, masks):
+ hidden_states = self.conv1(masks)
+ hidden_states = self.layer_norm1(hidden_states)
+ hidden_states = self.activation(hidden_states)
+
+ hidden_states = self.conv2(hidden_states)
+ hidden_states = self.layer_norm2(hidden_states)
+ hidden_states = self.activation(hidden_states)
+ dense_embeddings = self.conv3(hidden_states)
+ return dense_embeddings
+
+
+class SamHQPromptEncoder(nn.Module):
+ def __init__(self, config: SamHQConfig):
+ super().__init__()
+ self.shared_embedding = SamHQPositionalEmbedding(config.vision_config)
+ config = config.prompt_encoder_config
+ self.mask_embed = SamHQMaskEmbedding(config)
+ self.no_mask_embed = nn.Embedding(1, config.hidden_size)
+
+ self.image_embedding_size = (config.image_embedding_size, config.image_embedding_size)
+ self.input_image_size = config.image_size
+
+ self.point_embed = nn.ModuleList(
+ [nn.Embedding(1, config.hidden_size) for i in range(config.num_point_embeddings)]
+ )
+ self.hidden_size = config.hidden_size
+ self.not_a_point_embed = nn.Embedding(1, config.hidden_size)
+
+ def _embed_points(self, points: torch.Tensor, labels: torch.Tensor, pad: bool) -> torch.Tensor:
+ """Embeds point prompts."""
+ points = points + 0.5 # Shift to center of pixel
+ if pad:
+ target_point_shape = (points.shape[0], points.shape[1], 1, points.shape[-1])
+ target_labels_shape = (points.shape[0], points.shape[1], 1)
+ padding_point = torch.zeros(target_point_shape, device=points.device)
+ padding_label = -torch.ones(target_labels_shape, device=labels.device)
+ points = torch.cat([points, padding_point], dim=2)
+ labels = torch.cat([labels, padding_label], dim=2)
+ input_shape = (self.input_image_size, self.input_image_size)
+ point_embedding = self.shared_embedding(points, input_shape)
+
+ # torch.where and expanding the labels tensor is required by the ONNX export
+ point_embedding = torch.where(labels[..., None] == -1, self.not_a_point_embed.weight, point_embedding)
+
+ # This is required for the ONNX export. The dtype, device need to be explicitly
+ # specified as otherwise torch.onnx.export interprets as double
+ point_embedding = torch.where(labels[..., None] != -10, point_embedding, torch.zeros_like(point_embedding))
+
+ point_embedding = torch.where(
+ (labels == 0)[:, :, :, None],
+ point_embedding + self.point_embed[0].weight[None, None, :, :],
+ point_embedding,
+ )
+
+ point_embedding = torch.where(
+ (labels == 1)[:, :, :, None],
+ point_embedding + self.point_embed[1].weight[None, None, :, :],
+ point_embedding,
+ )
+
+ return point_embedding
+
+ def _embed_boxes(self, boxes: torch.Tensor) -> torch.Tensor:
+ """Embeds box prompts."""
+ boxes = boxes + 0.5 # Shift to center of pixel
+ batch_size, nb_boxes = boxes.shape[:2]
+ coords = boxes.reshape(batch_size, nb_boxes, 2, 2)
+ input_shape = (self.input_image_size, self.input_image_size)
+ corner_embedding = self.shared_embedding(coords, input_shape)
+ corner_embedding[:, :, 0, :] += self.point_embed[2].weight
+ corner_embedding[:, :, 1, :] += self.point_embed[3].weight
+ return corner_embedding
+
+ def forward(
+ self,
+ input_points: tuple[torch.Tensor, torch.Tensor] | None,
+ input_labels: torch.Tensor | None,
+ input_boxes: torch.Tensor | None,
+ input_masks: torch.Tensor | None,
+ ) -> tuple[torch.Tensor, torch.Tensor]:
+ """
+ Embeds different types of prompts, returning both sparse and dense embeddings.
+
+ Args:
+ points (`torch.Tensor`, *optional*):
+ point coordinates and labels to embed.
+ boxes (`torch.Tensor`, *optional*):
+ boxes to embed
+ masks (`torch.Tensor`, *optional*):
+ masks to embed
+ """
+ sparse_embeddings = None
+ batch_size = 1
+ if input_points is not None:
+ batch_size = input_points.shape[0]
+ if input_labels is None:
+ raise ValueError("If points are provided, labels must also be provided.")
+ point_embeddings = self._embed_points(input_points, input_labels, pad=(input_boxes is None))
+ sparse_embeddings = point_embeddings
+ if input_boxes is not None:
+ batch_size = input_boxes.shape[0]
+ box_embeddings = self._embed_boxes(input_boxes)
+ if sparse_embeddings is None:
+ sparse_embeddings = box_embeddings
+ else:
+ sparse_embeddings = torch.cat([sparse_embeddings, box_embeddings], dim=2)
+ if input_masks is not None:
+ dense_embeddings = self.mask_embed(input_masks)
+ else:
+ dense_embeddings = self.no_mask_embed.weight.reshape(1, -1, 1, 1).expand(
+ batch_size, -1, self.image_embedding_size[0], self.image_embedding_size[1]
+ )
+
+ return sparse_embeddings, dense_embeddings
+
+
+@auto_docstring(
+ custom_intro="""
+ Segment Anything Model HQ (SAM-HQ) for generating masks, given an input image and optional 2D location and bounding boxes.
+ """
+)
+class SamHQModel(SamHQPreTrainedModel):
+ input_modalities = ("image", "text")
+ _can_record_outputs = {"mask_decoder_attentions": OutputRecorder(SamHQTwoWayAttentionBlock, index=2)}
+ _tied_weights_keys = {
+ "prompt_encoder.shared_embedding.positional_embedding": "shared_image_embedding.positional_embedding"
+ }
+
+ def __init__(self, config):
+ super().__init__(config)
+ self.shared_image_embedding = SamHQPositionalEmbedding(config.vision_config)
+ self.vision_encoder = SamHQVisionEncoder(config.vision_config)
+ self.prompt_encoder = SamHQPromptEncoder(config)
+ # The module using it is not a PreTrainedModel subclass so we need this
+ config.mask_decoder_config._attn_implementation = config._attn_implementation
+
+ self.mask_decoder = SamHQMaskDecoder(config.mask_decoder_config)
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.vision_encoder.get_input_embeddings()
+
+ def get_image_wide_positional_embeddings(self):
+ size = self.config.prompt_encoder_config.image_embedding_size
+ target_device = self.shared_image_embedding.positional_embedding.device
+ target_dtype = self.shared_image_embedding.positional_embedding.dtype
+ grid = torch.ones((size, size), device=target_device, dtype=target_dtype)
+ y_embed = grid.cumsum(dim=0) - 0.5
+ x_embed = grid.cumsum(dim=1) - 0.5
+ y_embed = y_embed / size
+ x_embed = x_embed / size
+
+ positional_embedding = self.shared_image_embedding(torch.stack([x_embed, y_embed], dim=-1))
+ return positional_embedding.permute(2, 0, 1).unsqueeze(0) # channel x height x width
+
+ @torch.no_grad()
+ def get_image_embeddings(
+ self,
+ pixel_values,
+ ):
+ r"""
+ Returns the image embeddings by passing the pixel values through the vision encoder.
+
+ Args:
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
+ Input pixel values
+ """
+ vision_output = self.vision_encoder(pixel_values=pixel_values)
+ image_embeddings = vision_output[0]
+ intermediate_embeddings = vision_output[1]
+ return image_embeddings, intermediate_embeddings
+
+ @torch.no_grad()
+ def get_prompt_embeddings(
+ self,
+ input_points: torch.FloatTensor | None = None,
+ input_labels: torch.LongTensor | None = None,
+ input_boxes: torch.FloatTensor | None = None,
+ input_masks: torch.LongTensor | None = None,
+ ):
+ r"""
+ Returns the prompt embeddings by passing the input points, labels, boxes and masks through the prompt encoder.
+
+ Args:
+ input_points (`torch.FloatTensor` of shape `(batch_size, point_batch_size, num_points_per_image, 2)`):
+ Optional input points for the prompt encoder. The padding of the point is automatically done by the
+ processor. `point_batch_size` refers to the number of masks that we want the model to predict per
+ point. The model will output `point_batch_size` times 3 masks in total.
+ input_labels (`torch.LongTensor` of shape `(batch_size, point_batch_size, num_points_per_image)`):
+ Optional input labels for the prompt encoder. The padding of the labels is automatically done by the
+ processor, or can be fed by the user.
+ input_boxes (`torch.FloatTensor` of shape `(batch_size, num_boxes_per_image, 4)`):
+ Optional input boxes for the prompt encoder. The padding of the boxes is automatically done by the
+ processor. users can also pass manually the input boxes.
+ input_masks (`torch.LongTensor` of shape `(batch_size, image_size, image_size)`):
+ Optional input masks for the prompt encoder.
+ """
+ prompt_output = self.prompt_encoder(
+ input_points=input_points,
+ input_labels=input_labels,
+ input_boxes=input_boxes,
+ input_masks=input_masks,
+ )
+ return prompt_output
+
+ @merge_with_config_defaults
+ @capture_outputs
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: torch.FloatTensor | None = None,
+ input_points: torch.FloatTensor | None = None,
+ input_labels: torch.LongTensor | None = None,
+ input_boxes: torch.FloatTensor | None = None,
+ input_masks: torch.LongTensor | None = None,
+ image_embeddings: torch.FloatTensor | None = None,
+ multimask_output: bool = True,
+ hq_token_only: bool = False,
+ attention_similarity: torch.FloatTensor | None = None,
+ target_embedding: torch.FloatTensor | None = None,
+ intermediate_embeddings: list[torch.FloatTensor] | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> list[dict[str, torch.Tensor]]:
+ r"""
+ input_points (`torch.FloatTensor` of shape `(batch_size, num_points, 2)`):
+ Input 2D spatial points, this is used by the prompt encoder to encode the prompt. Generally yields to much
+ better results. The points can be obtained by passing a list of list of list to the processor that will
+ create corresponding `torch` tensors of dimension 4. The first dimension is the image batch size, the
+ second dimension is the point batch size (i.e. how many segmentation masks do we want the model to predict
+ per input point), the third dimension is the number of points per segmentation mask (it is possible to pass
+ multiple points for a single mask), and the last dimension is the x (vertical) and y (horizontal)
+ coordinates of the point. If a different number of points is passed either for each image, or for each
+ mask, the processor will create "PAD" points that will correspond to the (0, 0) coordinate, and the
+ computation of the embedding will be skipped for these points using the labels.
+ input_labels (`torch.LongTensor` of shape `(batch_size, point_batch_size, num_points)`):
+ Input labels for the points, this is used by the prompt encoder to encode the prompt. According to the
+ official implementation, there are 3 types of labels
+
+ - `1`: the point is a point that contains the object of interest
+ - `0`: the point is a point that does not contain the object of interest
+ - `-1`: the point corresponds to the background
+
+ We added the label:
+
+ - `-10`: the point is a padding point, thus should be ignored by the prompt encoder
+
+ The padding labels should be automatically done by the processor.
+ input_boxes (`torch.FloatTensor` of shape `(batch_size, num_boxes, 4)`):
+ Input boxes for the points, this is used by the prompt encoder to encode the prompt. Generally yields to
+ much better generated masks. The boxes can be obtained by passing a list of list of list to the processor,
+ that will generate a `torch` tensor, with each dimension corresponding respectively to the image batch
+ size, the number of boxes per image and the coordinates of the top left and bottom right point of the box.
+ In the order (`x1`, `y1`, `x2`, `y2`):
+
+ - `x1`: the x coordinate of the top left point of the input box
+ - `y1`: the y coordinate of the top left point of the input box
+ - `x2`: the x coordinate of the bottom right point of the input box
+ - `y2`: the y coordinate of the bottom right point of the input box
+ input_masks (`torch.FloatTensor` of shape `(batch_size, image_size, image_size)`):
+ SAM_HQ model also accepts segmentation masks as input. The mask will be embedded by the prompt encoder to
+ generate a corresponding embedding, that will be fed later on to the mask decoder. These masks needs to be
+ manually fed by the user, and they need to be of shape (`batch_size`, `image_size`, `image_size`).
+ image_embeddings (`torch.FloatTensor` of shape `(batch_size, output_channels, window_size, window_size)`):
+ Image embeddings, this is used by the mask decder to generate masks and iou scores. For more memory
+ efficient computation, users can first retrieve the image embeddings using the `get_image_embeddings`
+ method, and then feed them to the `forward` method instead of feeding the `pixel_values`.
+ multimask_output (`bool`, *optional*):
+ In the original implementation and paper, the model always outputs 3 masks per image (or per point / per
+ bounding box if relevant). However, it is possible to just output a single mask, that corresponds to the
+ "best" mask, by specifying `multimask_output=False`.
+ hq_token_only (`bool`, *optional*, defaults to `False`):
+ Whether to use only the HQ token path for mask generation. When False, combines both standard and HQ paths.
+ This is specific to SAM-HQ's architecture.
+ attention_similarity (`torch.FloatTensor`, *optional*):
+ Attention similarity tensor, to be provided to the mask decoder for target-guided attention in case the
+ model is used for personalization as introduced in [PerSAM](https://huggingface.co/papers/2305.03048).
+ target_embedding (`torch.FloatTensor`, *optional*):
+ Embedding of the target concept, to be provided to the mask decoder for target-semantic prompting in case
+ the model is used for personalization as introduced in [PerSAM](https://huggingface.co/papers/2305.03048).
+ intermediate_embeddings (`List[torch.FloatTensor]`, *optional*):
+ Intermediate embeddings from vision encoder's non-windowed blocks, used by SAM-HQ for enhanced mask quality.
+ Required when providing pre-computed image_embeddings instead of pixel_values.
+
+ Example:
+
+ ```python
+ >>> from PIL import Image
+ >>> import httpx
+ >>> from io import BytesIO
+ >>> from transformers import AutoModel, AutoProcessor
+
+ >>> model = AutoModel.from_pretrained("sushmanth/sam_hq_vit_b")
+ >>> processor = AutoProcessor.from_pretrained("sushmanth/sam_hq_vit_b")
+
+ >>> url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/sam-car.png"
+ >>> with httpx.stream("GET", url) as response:
+ ... image = Image.open(BytesIO(response.read())).convert("RGB")
+ >>> input_points = [[[400, 650]]] # 2D location of a window on the car
+ >>> inputs = processor(images=image, input_points=input_points, return_tensors="pt")
+
+ >>> # Get high-quality segmentation mask
+ >>> outputs = model(**inputs)
+
+ >>> # For high-quality mask only
+ >>> outputs = model(**inputs, hq_token_only=True)
+
+ >>> # Postprocess masks
+ >>> masks = processor.post_process_masks(
+ ... outputs.pred_masks, inputs["original_sizes"], inputs["reshaped_input_sizes"]
+ ... )
+ ```
+ """
+ if pixel_values is None and image_embeddings is None:
+ raise ValueError("Either pixel_values or image_embeddings must be provided.")
+
+ if pixel_values is not None and image_embeddings is not None:
+ raise ValueError("Only one of pixel_values and image_embeddings can be provided.")
+
+ if input_points is not None and len(input_points.shape) != 4:
+ raise ValueError(
+ "The input_points must be a 4D tensor. Of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`."
+ f" got {input_points.shape}."
+ )
+
+ if input_boxes is not None and len(input_boxes.shape) != 3:
+ raise ValueError(
+ "The input_boxes must be a 3D tensor. Of shape `batch_size`, `nb_boxes`, `4`."
+ f" got {input_boxes.shape}."
+ )
+
+ # Add validation for point and box batch sizes
+ if input_points is not None and input_boxes is not None:
+ point_batch_size = input_points.shape[1]
+ box_batch_size = input_boxes.shape[1]
+ if point_batch_size != box_batch_size:
+ raise ValueError(
+ f"You should provide as many bounding boxes as input points per box. Got {point_batch_size} and {box_batch_size}."
+ )
+
+ image_positional_embeddings = self.get_image_wide_positional_embeddings()
+ # repeat with batch size
+ batch_size = pixel_values.shape[0] if pixel_values is not None else image_embeddings.shape[0]
+ image_positional_embeddings = image_positional_embeddings.repeat(batch_size, 1, 1, 1)
+
+ if pixel_values is not None:
+ vision_outputs = self.vision_encoder(pixel_values, **kwargs)
+ image_embeddings = vision_outputs.last_hidden_state
+ intermediate_embeddings = vision_outputs.intermediate_embeddings
+ if input_points is not None and input_labels is None:
+ input_labels = torch.ones_like(input_points[:, :, :, 0], dtype=torch.int, device=input_points.device)
+
+ sparse_embeddings, dense_embeddings = self.prompt_encoder(
+ input_points=input_points,
+ input_labels=input_labels,
+ input_boxes=input_boxes,
+ input_masks=input_masks,
+ )
+
+ # Predict masks
+ mask_decoder_output = self.mask_decoder(
+ image_embeddings=image_embeddings,
+ image_positional_embeddings=image_positional_embeddings,
+ sparse_prompt_embeddings=sparse_embeddings,
+ dense_prompt_embeddings=dense_embeddings,
+ multimask_output=multimask_output,
+ hq_token_only=hq_token_only,
+ intermediate_embeddings=intermediate_embeddings,
+ attention_similarity=attention_similarity,
+ target_embedding=target_embedding,
+ )
+ return SamHQImageSegmentationOutput(
+ iou_scores=mask_decoder_output[1],
+ pred_masks=mask_decoder_output[0],
+ vision_hidden_states=vision_outputs.hidden_states if pixel_values is not None else None,
+ vision_attentions=vision_outputs.attentions if pixel_values is not None else None,
+ )
+
+
+__all__ = ["SamHQModel", "SamHQPreTrainedModel", "SamHQVisionModel"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/sam_hq/modular_sam_hq.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/sam_hq/modular_sam_hq.py
new file mode 100644
index 0000000000000000000000000000000000000000..5122ed9da2f6a7381f1af70659fc991f96e107fd
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/sam_hq/modular_sam_hq.py
@@ -0,0 +1,595 @@
+# Copyright 2025 Google Inc. HuggingFace Inc. team. All rights reserved.
+#
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from dataclasses import dataclass
+
+import torch
+from huggingface_hub.dataclasses import strict
+from torch import nn
+
+from ...processing_utils import Unpack
+from ...utils import auto_docstring, logging
+from ...utils.generic import ModelOutput, TransformersKwargs, merge_with_config_defaults
+from ...utils.output_capturing import capture_outputs
+from ..sam.configuration_sam import SamConfig, SamMaskDecoderConfig, SamPromptEncoderConfig, SamVisionConfig
+from ..sam.modeling_sam import (
+ SamFeedForward,
+ SamImageSegmentationOutput,
+ SamLayerNorm,
+ SamModel,
+ SamPreTrainedModel,
+ SamTwoWayTransformer,
+ SamVisionAttention,
+ SamVisionEncoder,
+ SamVisionEncoderOutput,
+ SamVisionLayer,
+ SamVisionModel,
+)
+
+
+logger = logging.get_logger(__name__)
+
+
+@auto_docstring(checkpoint="syscv-community/sam-hq-vit-base")
+@strict
+class SamHQPromptEncoderConfig(SamPromptEncoderConfig):
+ pass
+
+
+@auto_docstring(checkpoint="syscv-community/sam-hq-vit-base")
+@strict
+class SamHQVisionConfig(SamVisionConfig):
+ pass
+
+
+@auto_docstring(checkpoint="syscv-community/sam-hq-vit-base")
+@strict
+class SamHQMaskDecoderConfig(SamMaskDecoderConfig):
+ r"""
+ mlp_dim (`int`, *optional*, defaults to 2048):
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
+ attention_downsample_rate (`int`, *optional*, defaults to 2):
+ The downsampling rate of the attention layer.
+ num_multimask_outputs (`int`, *optional*, defaults to 3):
+ The number of outputs from the `SamMaskDecoder` module. In the Segment Anything paper, this is set to 3.
+ iou_head_depth (`int`, *optional*, defaults to 3):
+ The number of layers in the IoU head module.
+ iou_head_hidden_dim (`int`, *optional*, defaults to 256):
+ The dimensionality of the hidden states in the IoU head module.
+ vit_dim (`int`, *optional*, defaults to 768):
+ Dimensionality of the Vision Transformer (ViT) used in the `SamHQMaskDecoder` module.
+ """
+
+ vit_dim: int = 768
+
+
+@auto_docstring(checkpoint="syscv-community/sam-hq-vit-base")
+@strict
+class SamHQConfig(SamConfig):
+ r"""
+ prompt_encoder_config (Union[`dict`, `SamHQPromptEncoderConfig`], *optional*):
+ Dictionary of configuration options used to initialize [`SamHQPromptEncoderConfig`].
+ mask_decoder_config (Union[`dict`, `SamHQMaskDecoderConfig`], *optional*):
+ Dictionary of configuration options used to initialize [`SamHQMaskDecoderConfig`].
+ """
+
+
+class SamHQVisionEncoderOutput(SamVisionEncoderOutput):
+ r"""
+ image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
+ The image embeddings obtained by applying the projection layer to the pooler_output.
+ intermediate_embeddings (`list(torch.FloatTensor)`, *optional*):
+ A list of intermediate embeddings collected from certain blocks within the model, typically those without
+ windowed attention. Each element in the list is of shape `(batch_size, sequence_length, hidden_size)`.
+ This is specific to SAM-HQ and not present in base SAM.
+ """
+
+ intermediate_embeddings: list[torch.FloatTensor] | None = None
+
+
+@dataclass
+class SamHQMMaskDecoderOutputs(ModelOutput):
+ r"""
+ masks (`torch.FloatTensor` of shape `(batch_size, num_prompts, num_masks, height, width)`):
+ The predicted masks for the input image. The masks are of shape `(batch_size, num_prompts, num_masks, height, width)`.
+ iou_scores (`torch.FloatTensor` of shape `(batch_size, num_prompts, num_masks)`):
+ The predicted IoU scores for each mask. The scores are of shape `(batch_size, num_prompts, num_masks)`.
+ mask_decoder_attentions (`torch.FloatTensor`, *optional*):
+ The attention weights from the mask decoder, if `output_attentions=True` was passed during the forward pass.
+ This is specific to SAM-HQ and not present in base SAM.
+ """
+
+ masks: torch.FloatTensor
+ iou_scores: torch.FloatTensor | None = None
+ mask_decoder_attentions: torch.FloatTensor | None = None
+
+
+class SamHQImageSegmentationOutput(SamImageSegmentationOutput):
+ pass
+
+
+class SamHQVisionAttention(SamVisionAttention):
+ pass
+
+
+class SamHQVisionLayer(SamVisionLayer):
+ pass
+
+
+class SamHQPreTrainedModel(SamPreTrainedModel):
+ pass
+
+
+class SamHQVisionEncoder(SamVisionEncoder, SamHQPreTrainedModel):
+ _can_record_outputs = {
+ "hidden_states": SamHQVisionLayer,
+ "attentions": SamHQVisionAttention,
+ }
+
+ @merge_with_config_defaults
+ @capture_outputs(tie_last_hidden_states=False)
+ def forward(
+ self, pixel_values: torch.FloatTensor | None = None, **kwargs: Unpack[TransformersKwargs]
+ ) -> tuple | SamHQVisionEncoderOutput:
+ if pixel_values is None:
+ raise ValueError("You have to specify pixel_values")
+
+ hidden_states = self.patch_embed(pixel_values)
+ if self.pos_embed is not None:
+ hidden_states = hidden_states + self.pos_embed
+
+ intermediate_embeddings = []
+
+ for layer_module in self.layers:
+ hidden_states = layer_module(hidden_states)
+
+ # Collect embeddings from non-windowed blocks
+ if hasattr(layer_module, "window_size") and layer_module.window_size == 0:
+ intermediate_embeddings.append(hidden_states)
+
+ hidden_states = self.neck(hidden_states)
+
+ return SamHQVisionEncoderOutput(
+ last_hidden_state=hidden_states,
+ intermediate_embeddings=intermediate_embeddings,
+ )
+
+
+class SamHQLayerNorm(SamLayerNorm):
+ pass
+
+
+class SamHQTwoWayTransformer(SamTwoWayTransformer):
+ pass
+
+
+class SamHQFeedForward(SamFeedForward):
+ pass
+
+
+class SamHQMaskDecoder(nn.Module):
+ def __init__(self, config: SamHQMaskDecoderConfig):
+ super().__init__()
+ self.hidden_size = config.hidden_size
+
+ self.num_multimask_outputs = config.num_multimask_outputs
+ self.num_mask_tokens = config.num_multimask_outputs + 1
+
+ self.iou_token = nn.Embedding(1, self.hidden_size)
+ self.mask_tokens = nn.Embedding(self.num_mask_tokens, self.hidden_size)
+
+ self.transformer = SamHQTwoWayTransformer(config)
+
+ self.upscale_conv1 = nn.ConvTranspose2d(self.hidden_size, self.hidden_size // 4, kernel_size=2, stride=2)
+ self.upscale_conv2 = nn.ConvTranspose2d(self.hidden_size // 4, self.hidden_size // 8, kernel_size=2, stride=2)
+ self.upscale_layer_norm = SamHQLayerNorm(self.hidden_size // 4, data_format="channels_first")
+ self.activation = nn.GELU()
+
+ mlps_list = []
+ for _ in range(self.num_mask_tokens):
+ mlps_list += [SamHQFeedForward(self.hidden_size, self.hidden_size, self.hidden_size // 8, 3)]
+ self.output_hypernetworks_mlps = nn.ModuleList(mlps_list)
+
+ self.iou_prediction_head = SamHQFeedForward(
+ self.hidden_size, config.iou_head_hidden_dim, self.num_mask_tokens, config.iou_head_depth
+ )
+
+ self.hq_token = nn.Embedding(1, self.hidden_size)
+ self.hq_mask_mlp = SamHQFeedForward(self.hidden_size, self.hidden_size, self.hidden_size // 8, 3)
+ self.num_mask_tokens = self.num_mask_tokens + 1
+
+ # Compress ViT features
+ self.compress_vit_conv1 = nn.ConvTranspose2d(config.vit_dim, self.hidden_size, kernel_size=2, stride=2)
+ self.compress_vit_norm = SamHQLayerNorm(self.hidden_size, data_format="channels_first")
+ self.compress_vit_conv2 = nn.ConvTranspose2d(self.hidden_size, self.hidden_size // 8, kernel_size=2, stride=2)
+
+ # Embedding encoder
+ self.encoder_conv1 = nn.ConvTranspose2d(self.hidden_size, self.hidden_size // 4, kernel_size=2, stride=2)
+ self.encoder_norm = SamHQLayerNorm(self.hidden_size // 4, data_format="channels_first")
+ self.encoder_conv2 = nn.ConvTranspose2d(self.hidden_size // 4, self.hidden_size // 8, kernel_size=2, stride=2)
+
+ # Embedding mask feature
+ self.mask_conv1 = nn.Conv2d(self.hidden_size // 8, self.hidden_size // 4, kernel_size=3, stride=1, padding=1)
+ self.mask_norm = SamHQLayerNorm(self.hidden_size // 4, data_format="channels_first")
+ self.mask_conv2 = nn.Conv2d(self.hidden_size // 4, self.hidden_size // 8, kernel_size=3, stride=1, padding=1)
+
+ def forward(
+ self,
+ image_embeddings: torch.Tensor,
+ image_positional_embeddings: torch.Tensor,
+ sparse_prompt_embeddings: torch.Tensor,
+ dense_prompt_embeddings: torch.Tensor,
+ multimask_output: bool,
+ hq_token_only: bool,
+ intermediate_embeddings: list[torch.Tensor] | None = None,
+ attention_similarity: torch.Tensor | None = None,
+ target_embedding: torch.Tensor | None = None,
+ ) -> SamHQMMaskDecoderOutputs:
+ """
+ Predict high-quality masks given image and prompt embeddings.
+
+ Args:
+ image_embeddings (`torch.Tensor`):
+ The embeddings from the image encoder.
+ image_positional_embedding (`torch.Tensor`):
+ Positional encoding with the shape of image_embeddings.
+ sparse_prompt_embeddings (`torch.Tensor`):
+ The embeddings of the points and boxes.
+ dense_prompt_embeddings (`torch.Tensor`):
+ The embeddings of the mask inputs.
+ multimask_output (bool):
+ Whether to return multiple masks or a single mask.
+ hq_token_only (bool):
+ Whether to use only the high-quality token output or combine with SAM output.
+ intermediate_embeddings (`torch.Tensor`):
+ Intermediate embeddings from the vision encoder for feature fusion.
+ attention_similarity (`torch.Tensor`, *optional*):
+ Optional tensor for attention similarity computation.
+ target_embedding (`torch.Tensor`, *optional*):
+ Optional target embedding for transformer processing.
+
+ Returns:
+ `Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]]`: A tuple of tensors containing:
+ - A tensor of shape `(batch_size, num_prompts, num_masks, height, width)` containing the output masks.
+ - A tensor of shape `(batch_size, num_prompts, num_masks)` containing the iou predictions for each mask.
+ - (Optional) A tuple containing attention tensors if output_attentions is True.
+ """
+ batch_size, num_channels, height, width = image_embeddings.shape
+ point_batch_size = sparse_prompt_embeddings.shape[1] if sparse_prompt_embeddings is not None else 1
+
+ has_intermediate = intermediate_embeddings is not None and len(intermediate_embeddings) > 0
+
+ if has_intermediate:
+ vit_features = intermediate_embeddings[0].permute(0, 3, 1, 2).contiguous()
+
+ embed_encode = self.encoder_conv1(image_embeddings)
+ embed_encode = self.activation(self.encoder_norm(embed_encode))
+ embed_encode = self.encoder_conv2(embed_encode)
+
+ if has_intermediate:
+ compressed_vit_features = self.compress_vit_conv1(vit_features)
+ compressed_vit_features = self.activation(self.compress_vit_norm(compressed_vit_features))
+ compressed_vit_features = self.compress_vit_conv2(compressed_vit_features)
+
+ hq_features = embed_encode + compressed_vit_features
+ else:
+ hq_features = embed_encode
+
+ output_tokens = torch.cat([self.iou_token.weight, self.mask_tokens.weight, self.hq_token.weight], dim=0)
+ output_tokens = output_tokens.repeat(batch_size, point_batch_size, 1, 1)
+
+ if sparse_prompt_embeddings is not None:
+ tokens = torch.cat([output_tokens, sparse_prompt_embeddings], dim=2)
+ else:
+ tokens = output_tokens
+ point_embeddings = tokens.to(self.iou_token.weight.dtype)
+ image_embeddings = image_embeddings + dense_prompt_embeddings
+ image_embeddings = image_embeddings.repeat_interleave(point_batch_size, 0)
+ image_positional_embeddings = image_positional_embeddings.repeat_interleave(point_batch_size, 0)
+
+ point_embedding, iou_token_out = self.transformer(
+ point_embeddings=point_embeddings,
+ image_embeddings=image_embeddings,
+ image_positional_embeddings=image_positional_embeddings,
+ attention_similarity=attention_similarity,
+ target_embedding=target_embedding,
+ )
+ iou_token_out = point_embedding[:, :, 0, :]
+ mask_tokens_out = point_embedding[:, :, 1 : (1 + self.num_mask_tokens), :]
+
+ image_embeddings = image_embeddings.transpose(2, 3).reshape(
+ batch_size * point_batch_size, num_channels, height, width
+ )
+
+ upscaled_embedding = self.upscale_conv1(image_embeddings)
+ upscaled_embedding = self.activation(self.upscale_layer_norm(upscaled_embedding))
+ upscaled_embedding = self.activation(self.upscale_conv2(upscaled_embedding))
+
+ upscaled_embedding_hq = self.mask_conv1(upscaled_embedding)
+ upscaled_embedding_hq = self.activation(self.mask_norm(upscaled_embedding_hq))
+ upscaled_embedding_hq = self.mask_conv2(upscaled_embedding_hq)
+
+ if hq_features.shape[0] == 1:
+ hq_features = hq_features.repeat(batch_size * point_batch_size, 1, 1, 1)
+ elif hq_features.shape[0] == batch_size and batch_size * point_batch_size != batch_size:
+ hq_features = hq_features.repeat_interleave(point_batch_size, 0)
+ upscaled_embedding_hq = upscaled_embedding_hq + hq_features
+
+ hyper_in_list = []
+ for mask_token_index in range(self.num_mask_tokens):
+ if mask_token_index < self.num_mask_tokens - 1:
+ current_mlp = self.output_hypernetworks_mlps[mask_token_index]
+ else:
+ current_mlp = self.hq_mask_mlp
+ hyper_in_list += [current_mlp(mask_tokens_out[:, :, mask_token_index, :])]
+
+ hyper_in = torch.stack(hyper_in_list, dim=2)
+ _, num_channels, height, width = upscaled_embedding.shape
+ upscaled_embedding = upscaled_embedding.reshape(batch_size, point_batch_size, num_channels, height * width)
+ upscaled_embedding_hq = upscaled_embedding_hq.reshape(
+ batch_size, point_batch_size, num_channels, height * width
+ )
+
+ masks_sam = (hyper_in[:, :, : self.num_mask_tokens - 1] @ upscaled_embedding).reshape(
+ batch_size, point_batch_size, -1, height, width
+ )
+ masks_hq = (hyper_in[:, :, self.num_mask_tokens - 1 :] @ upscaled_embedding_hq).reshape(
+ batch_size, point_batch_size, -1, height, width
+ )
+ masks = torch.cat([masks_sam, masks_hq], dim=2)
+
+ iou_pred = self.iou_prediction_head(iou_token_out)
+
+ if multimask_output:
+ mask_slice = slice(1, self.num_mask_tokens - 1)
+ iou_pred = iou_pred[:, :, mask_slice]
+ # Sort the IoU scores in descending order and get indices
+ iou_pred_sorted, sort_indices = torch.sort(iou_pred, dim=2, descending=True)
+ # Reorder the masks according to sorted scores
+ masks_sam = masks[:, :, mask_slice, :, :]
+ masks_sam = torch.gather(
+ masks_sam,
+ 2,
+ sort_indices[..., None, None].expand(-1, -1, -1, masks_sam.shape[3], masks_sam.shape[4]),
+ )
+ # Update iou_pred with sorted scores
+ iou_pred = iou_pred_sorted
+ else:
+ mask_slice = slice(0, 1)
+ iou_pred = iou_pred[:, :, mask_slice]
+ masks_sam = masks[:, :, mask_slice, :, :]
+
+ masks_hq = masks[:, :, slice(self.num_mask_tokens - 1, self.num_mask_tokens), :, :]
+ if hq_token_only:
+ masks = masks_hq
+ else:
+ masks = masks_sam + masks_hq
+
+ return masks, iou_pred
+
+
+class SamHQVisionModel(SamVisionModel):
+ pass
+
+
+@auto_docstring(
+ custom_intro="""
+ Segment Anything Model HQ (SAM-HQ) for generating masks, given an input image and optional 2D location and bounding boxes.
+ """
+)
+class SamHQModel(SamModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.vision_encoder = SamHQVisionEncoder(config.vision_config)
+
+ self.mask_decoder = SamHQMaskDecoder(config.mask_decoder_config)
+
+ self.post_init()
+
+ @torch.no_grad()
+ def get_image_embeddings(
+ self,
+ pixel_values,
+ ):
+ r"""
+ Returns the image embeddings by passing the pixel values through the vision encoder.
+
+ Args:
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
+ Input pixel values
+ """
+ vision_output = self.vision_encoder(pixel_values=pixel_values)
+ image_embeddings = vision_output[0]
+ intermediate_embeddings = vision_output[1]
+ return image_embeddings, intermediate_embeddings
+
+ def forward(
+ self,
+ pixel_values: torch.FloatTensor | None = None,
+ input_points: torch.FloatTensor | None = None,
+ input_labels: torch.LongTensor | None = None,
+ input_boxes: torch.FloatTensor | None = None,
+ input_masks: torch.LongTensor | None = None,
+ image_embeddings: torch.FloatTensor | None = None,
+ multimask_output: bool = True,
+ hq_token_only: bool = False,
+ attention_similarity: torch.FloatTensor | None = None,
+ target_embedding: torch.FloatTensor | None = None,
+ intermediate_embeddings: list[torch.FloatTensor] | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> list[dict[str, torch.Tensor]]:
+ r"""
+ input_points (`torch.FloatTensor` of shape `(batch_size, num_points, 2)`):
+ Input 2D spatial points, this is used by the prompt encoder to encode the prompt. Generally yields to much
+ better results. The points can be obtained by passing a list of list of list to the processor that will
+ create corresponding `torch` tensors of dimension 4. The first dimension is the image batch size, the
+ second dimension is the point batch size (i.e. how many segmentation masks do we want the model to predict
+ per input point), the third dimension is the number of points per segmentation mask (it is possible to pass
+ multiple points for a single mask), and the last dimension is the x (vertical) and y (horizontal)
+ coordinates of the point. If a different number of points is passed either for each image, or for each
+ mask, the processor will create "PAD" points that will correspond to the (0, 0) coordinate, and the
+ computation of the embedding will be skipped for these points using the labels.
+ input_labels (`torch.LongTensor` of shape `(batch_size, point_batch_size, num_points)`):
+ Input labels for the points, this is used by the prompt encoder to encode the prompt. According to the
+ official implementation, there are 3 types of labels
+
+ - `1`: the point is a point that contains the object of interest
+ - `0`: the point is a point that does not contain the object of interest
+ - `-1`: the point corresponds to the background
+
+ We added the label:
+
+ - `-10`: the point is a padding point, thus should be ignored by the prompt encoder
+
+ The padding labels should be automatically done by the processor.
+ input_boxes (`torch.FloatTensor` of shape `(batch_size, num_boxes, 4)`):
+ Input boxes for the points, this is used by the prompt encoder to encode the prompt. Generally yields to
+ much better generated masks. The boxes can be obtained by passing a list of list of list to the processor,
+ that will generate a `torch` tensor, with each dimension corresponding respectively to the image batch
+ size, the number of boxes per image and the coordinates of the top left and bottom right point of the box.
+ In the order (`x1`, `y1`, `x2`, `y2`):
+
+ - `x1`: the x coordinate of the top left point of the input box
+ - `y1`: the y coordinate of the top left point of the input box
+ - `x2`: the x coordinate of the bottom right point of the input box
+ - `y2`: the y coordinate of the bottom right point of the input box
+ input_masks (`torch.FloatTensor` of shape `(batch_size, image_size, image_size)`):
+ SAM_HQ model also accepts segmentation masks as input. The mask will be embedded by the prompt encoder to
+ generate a corresponding embedding, that will be fed later on to the mask decoder. These masks needs to be
+ manually fed by the user, and they need to be of shape (`batch_size`, `image_size`, `image_size`).
+ image_embeddings (`torch.FloatTensor` of shape `(batch_size, output_channels, window_size, window_size)`):
+ Image embeddings, this is used by the mask decder to generate masks and iou scores. For more memory
+ efficient computation, users can first retrieve the image embeddings using the `get_image_embeddings`
+ method, and then feed them to the `forward` method instead of feeding the `pixel_values`.
+ multimask_output (`bool`, *optional*):
+ In the original implementation and paper, the model always outputs 3 masks per image (or per point / per
+ bounding box if relevant). However, it is possible to just output a single mask, that corresponds to the
+ "best" mask, by specifying `multimask_output=False`.
+ hq_token_only (`bool`, *optional*, defaults to `False`):
+ Whether to use only the HQ token path for mask generation. When False, combines both standard and HQ paths.
+ This is specific to SAM-HQ's architecture.
+ attention_similarity (`torch.FloatTensor`, *optional*):
+ Attention similarity tensor, to be provided to the mask decoder for target-guided attention in case the
+ model is used for personalization as introduced in [PerSAM](https://huggingface.co/papers/2305.03048).
+ target_embedding (`torch.FloatTensor`, *optional*):
+ Embedding of the target concept, to be provided to the mask decoder for target-semantic prompting in case
+ the model is used for personalization as introduced in [PerSAM](https://huggingface.co/papers/2305.03048).
+ intermediate_embeddings (`List[torch.FloatTensor]`, *optional*):
+ Intermediate embeddings from vision encoder's non-windowed blocks, used by SAM-HQ for enhanced mask quality.
+ Required when providing pre-computed image_embeddings instead of pixel_values.
+
+ Example:
+
+ ```python
+ >>> from PIL import Image
+ >>> import httpx
+ >>> from io import BytesIO
+ >>> from transformers import AutoModel, AutoProcessor
+
+ >>> model = AutoModel.from_pretrained("sushmanth/sam_hq_vit_b")
+ >>> processor = AutoProcessor.from_pretrained("sushmanth/sam_hq_vit_b")
+
+ >>> url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/sam-car.png"
+ >>> with httpx.stream("GET", url) as response:
+ ... image = Image.open(BytesIO(response.read())).convert("RGB")
+ >>> input_points = [[[400, 650]]] # 2D location of a window on the car
+ >>> inputs = processor(images=image, input_points=input_points, return_tensors="pt")
+
+ >>> # Get high-quality segmentation mask
+ >>> outputs = model(**inputs)
+
+ >>> # For high-quality mask only
+ >>> outputs = model(**inputs, hq_token_only=True)
+
+ >>> # Postprocess masks
+ >>> masks = processor.post_process_masks(
+ ... outputs.pred_masks, inputs["original_sizes"], inputs["reshaped_input_sizes"]
+ ... )
+ ```
+ """
+ if pixel_values is None and image_embeddings is None:
+ raise ValueError("Either pixel_values or image_embeddings must be provided.")
+
+ if pixel_values is not None and image_embeddings is not None:
+ raise ValueError("Only one of pixel_values and image_embeddings can be provided.")
+
+ if input_points is not None and len(input_points.shape) != 4:
+ raise ValueError(
+ "The input_points must be a 4D tensor. Of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`."
+ f" got {input_points.shape}."
+ )
+
+ if input_boxes is not None and len(input_boxes.shape) != 3:
+ raise ValueError(
+ "The input_boxes must be a 3D tensor. Of shape `batch_size`, `nb_boxes`, `4`."
+ f" got {input_boxes.shape}."
+ )
+
+ # Add validation for point and box batch sizes
+ if input_points is not None and input_boxes is not None:
+ point_batch_size = input_points.shape[1]
+ box_batch_size = input_boxes.shape[1]
+ if point_batch_size != box_batch_size:
+ raise ValueError(
+ f"You should provide as many bounding boxes as input points per box. Got {point_batch_size} and {box_batch_size}."
+ )
+
+ image_positional_embeddings = self.get_image_wide_positional_embeddings()
+ # repeat with batch size
+ batch_size = pixel_values.shape[0] if pixel_values is not None else image_embeddings.shape[0]
+ image_positional_embeddings = image_positional_embeddings.repeat(batch_size, 1, 1, 1)
+
+ if pixel_values is not None:
+ vision_outputs = self.vision_encoder(pixel_values, **kwargs)
+ image_embeddings = vision_outputs.last_hidden_state
+ intermediate_embeddings = vision_outputs.intermediate_embeddings
+ if input_points is not None and input_labels is None:
+ input_labels = torch.ones_like(input_points[:, :, :, 0], dtype=torch.int, device=input_points.device)
+
+ sparse_embeddings, dense_embeddings = self.prompt_encoder(
+ input_points=input_points,
+ input_labels=input_labels,
+ input_boxes=input_boxes,
+ input_masks=input_masks,
+ )
+
+ # Predict masks
+ mask_decoder_output = self.mask_decoder(
+ image_embeddings=image_embeddings,
+ image_positional_embeddings=image_positional_embeddings,
+ sparse_prompt_embeddings=sparse_embeddings,
+ dense_prompt_embeddings=dense_embeddings,
+ multimask_output=multimask_output,
+ hq_token_only=hq_token_only,
+ intermediate_embeddings=intermediate_embeddings,
+ attention_similarity=attention_similarity,
+ target_embedding=target_embedding,
+ )
+ return SamHQImageSegmentationOutput(
+ iou_scores=mask_decoder_output[1],
+ pred_masks=mask_decoder_output[0],
+ vision_hidden_states=vision_outputs.hidden_states if pixel_values is not None else None,
+ vision_attentions=vision_outputs.attentions if pixel_values is not None else None,
+ )
+
+
+__all__ = [
+ "SamHQVisionConfig",
+ "SamHQMaskDecoderConfig",
+ "SamHQPromptEncoderConfig",
+ "SamHQConfig",
+ "SamHQModel",
+ "SamHQPreTrainedModel",
+ "SamHQVisionModel",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/sam_hq/processing_sam_hq.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/sam_hq/processing_sam_hq.py
new file mode 100644
index 0000000000000000000000000000000000000000..8bd9d814a9759b731bc9fa23437ced568122b9b9
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/sam_hq/processing_sam_hq.py
@@ -0,0 +1,327 @@
+# Copyright 2025 The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""
+Processor class for SAMHQ.
+"""
+
+from copy import deepcopy
+from typing import Union
+
+import numpy as np
+
+from ...feature_extraction_utils import BatchFeature
+from ...image_utils import ImageInput
+from ...processing_utils import ImagesKwargs, ProcessingKwargs, ProcessorMixin, Unpack
+from ...utils import auto_docstring, is_torch_available
+
+
+if is_torch_available():
+ import torch
+
+NestedList = list[Union[float | int | None, "NestedList"]]
+
+
+class SamHQImagesKwargs(ImagesKwargs, total=False):
+ """
+ segmentation_maps (`ImageInput`, *optional*):
+ Ground truth segmentation maps to process alongside the input images. These maps are used for training
+ or evaluation purposes and are resized and normalized to match the processed image dimensions.
+ input_points (`NestedList`, *optional*):
+ Input points for prompt-based segmentation. Should be a nested list with structure
+ `[image_level, object_level, point_level, [x, y]]` where each point is specified as `[x, y]` coordinates
+ in the original image space. Points are normalized to the target image size before being passed to the model.
+ input_labels (`NestedList`, *optional*):
+ Labels for the input points, indicating whether each point is a foreground (1) or background (0) point.
+ Should be a nested list with structure `[image_level, object_level, point_level]`. Must have the same
+ structure as `input_points` (excluding the coordinate dimension).
+ input_boxes (`NestedList`, *optional*):
+ Bounding boxes for prompt-based segmentation. Should be a nested list with structure
+ `[image_level, box_level, [x1, y1, x2, y2]]` where each box is specified as `[x1, y1, x2, y2]` coordinates
+ in the original image space. Boxes are normalized to the target image size before being passed to the model.
+ point_pad_value (`int`, *optional*, defaults to `None`):
+ The value used for padding input points when batching sequences of different lengths. This value marks
+ padded positions and is preserved during coordinate normalization to distinguish real points from padding.
+ If `None`, the default pad value from the processor configuration is used.
+ mask_size (`dict[str, int]`, *optional*):
+ Dictionary specifying the target mask size with keys `"height"` and `"width"`. This determines the
+ resolution of the output segmentation masks generated by the model.
+ mask_pad_size (`dict[str, int]`, *optional*):
+ Dictionary specifying the padding size for masks with keys `"height"` and `"width"`. This is used when
+ batching masks of different sizes to ensure consistent dimensions.
+ """
+
+ segmentation_maps: ImageInput | None
+ input_points: "NestedList | torch.Tensor | None"
+ input_labels: "NestedList | int | torch.Tensor | None"
+ input_boxes: "NestedList | torch.Tensor | None"
+ point_pad_value: int | None
+ mask_size: dict[str, int]
+ mask_pad_size: dict[str, int]
+
+
+class SamHQProcessorKwargs(ProcessingKwargs, total=False):
+ images_kwargs: SamHQImagesKwargs
+ _defaults = {
+ "images_kwargs": {
+ "point_pad_value": None,
+ }
+ }
+
+
+@auto_docstring
+class SamHQProcessor(ProcessorMixin):
+ def __init__(self, image_processor):
+ super().__init__(image_processor)
+ # Ensure image_processor is properly initialized
+ if not hasattr(self, "image_processor"):
+ raise ValueError("image_processor was not properly initialized")
+ if not hasattr(self.image_processor, "size"):
+ raise ValueError("image_processor.size is not set")
+ self.target_size = self.image_processor.size["longest_edge"]
+
+ @auto_docstring
+ def __call__(
+ self,
+ images: ImageInput | None = None,
+ **kwargs: Unpack[SamHQProcessorKwargs],
+ ) -> BatchFeature:
+ output_kwargs = self._merge_kwargs(
+ SamHQProcessorKwargs,
+ tokenizer_init_kwargs={},
+ **kwargs,
+ )
+
+ input_points = output_kwargs["images_kwargs"].pop("input_points", None)
+ input_labels = output_kwargs["images_kwargs"].pop("input_labels", None)
+ input_boxes = output_kwargs["images_kwargs"].pop("input_boxes", None)
+ point_pad_value = output_kwargs["images_kwargs"].pop("point_pad_value", None)
+
+ encoding_image_processor = self.image_processor(
+ images,
+ **output_kwargs["images_kwargs"],
+ )
+
+ original_sizes = encoding_image_processor["original_sizes"]
+
+ if hasattr(original_sizes, "numpy"):
+ original_sizes = original_sizes.numpy()
+
+ input_points, input_labels, input_boxes = self._check_and_preprocess_points(
+ input_points=input_points,
+ input_labels=input_labels,
+ input_boxes=input_boxes,
+ )
+
+ encoding_image_processor = self._normalize_and_convert(
+ encoding_image_processor,
+ original_sizes,
+ input_points=input_points,
+ input_labels=input_labels,
+ input_boxes=input_boxes,
+ return_tensors=output_kwargs["images_kwargs"].get("return_tensors"),
+ point_pad_value=point_pad_value,
+ )
+
+ return encoding_image_processor
+
+ def _normalize_and_convert(
+ self,
+ encoding_image_processor,
+ original_sizes,
+ input_points=None,
+ input_labels=None,
+ input_boxes=None,
+ return_tensors="pt",
+ point_pad_value=-10,
+ ):
+ """
+ Normalize and convert the image processor output to the expected format.
+ """
+ # Process input points
+ if input_points is not None:
+ input_points = self._normalize_batch_coordinates(input_points, original_sizes)
+
+ if not all(point.shape == input_points[0].shape for point in input_points):
+ if input_labels is not None:
+ input_points, input_labels = self._pad_points_and_labels(
+ input_points, input_labels, point_pad_value
+ )
+
+ input_points = np.array(input_points)
+
+ # Process input labels
+ if input_labels is not None:
+ input_labels = np.array(input_labels)
+
+ # Process input boxes
+ if input_boxes is not None:
+ input_boxes = self._normalize_batch_coordinates(input_boxes, original_sizes, is_bounding_box=True)
+ input_boxes = np.array(input_boxes)
+
+ # Update processor with converted inputs
+ if input_boxes is not None:
+ encoding_image_processor["input_boxes"] = self._to_tensor(input_boxes, 3, return_tensors)
+ if input_points is not None:
+ encoding_image_processor["input_points"] = self._to_tensor(input_points, 4, return_tensors)
+ if input_labels is not None:
+ encoding_image_processor["input_labels"] = self._to_tensor(input_labels, 3, return_tensors)
+
+ return encoding_image_processor
+
+ def _pad_points_and_labels(self, input_points, input_labels, point_pad_value):
+ r"""
+ The method pads the 2D points and labels to the maximum number of points in the batch.
+ """
+ expected_nb_points = max(point.shape[0] for point in input_points)
+ processed_input_points = []
+ for i, point in enumerate(input_points):
+ if point.shape[0] != expected_nb_points:
+ point = np.concatenate(
+ [point, np.zeros((expected_nb_points - point.shape[0], 2)) + point_pad_value], axis=0
+ )
+ input_labels[i] = np.append(input_labels[i], [point_pad_value])
+ processed_input_points.append(point)
+ input_points = processed_input_points
+ return input_points, input_labels
+
+ def _normalize_coordinates(
+ self, target_size: int, coords: np.ndarray, original_size, is_bounding_box=False
+ ) -> np.ndarray:
+ """
+ Expects a numpy array of length 2 in the final dimension. Requires the original image size in (H,W) format.
+ """
+ old_h, old_w = original_size
+ new_h, new_w = self.image_processor._get_preprocess_shape(original_size, longest_edge=target_size)
+ coords = deepcopy(coords).astype(float)
+
+ if is_bounding_box:
+ coords = coords.reshape(-1, 2, 2)
+
+ coords[..., 0] = coords[..., 0] * (new_w / old_w)
+ coords[..., 1] = coords[..., 1] * (new_h / old_h)
+
+ if is_bounding_box:
+ coords = coords.reshape(-1, 4)
+
+ return coords
+
+ def _preprocess_input(self, inputs, error_message, expected_nesting=1, dtype=None):
+ """
+ Preprocess input by converting torch tensors to numpy arrays and validating structure.
+
+ Args:
+ inputs: The input to process
+ error_message: Error message if validation fails
+ expected_nesting: Expected nesting level (1 for points/labels, 2 for boxes)
+ dtype: Optional data type for numpy array conversion
+
+ Returns:
+ Processed input as list of numpy arrays or None
+ """
+ if inputs is None:
+ return None
+
+ # Convert torch tensor to list if applicable
+ if hasattr(inputs, "numpy"):
+ inputs = inputs.numpy().tolist()
+
+ # Validate structure based on expected nesting
+ valid = isinstance(inputs, list)
+ current = inputs
+
+ for _ in range(expected_nesting):
+ if not valid or not current:
+ break
+ valid = valid and isinstance(current[0], list)
+ current = current[0] if current else None
+
+ if not valid:
+ raise ValueError(error_message)
+
+ # Convert to numpy arrays
+ return [np.array(item, dtype=dtype) for item in inputs]
+
+ def _check_and_preprocess_points(
+ self,
+ input_points=None,
+ input_labels=None,
+ input_boxes=None,
+ ):
+ r"""
+ Check and preprocesses the 2D points, labels and bounding boxes. It checks if the input is valid and if they
+ are, it converts the coordinates of the points and bounding boxes. If a user passes directly a `torch.Tensor`,
+ it is converted to a `numpy.ndarray` and then to a `list`.
+ """
+ # Process each input type
+ input_points = self._preprocess_input(input_points, "Input points must be a list of list of floating points.")
+
+ input_labels = self._preprocess_input(input_labels, "Input labels must be a list of list integers.")
+
+ input_boxes = self._preprocess_input(
+ input_boxes,
+ "Input boxes must be a list of list of list of floating points.",
+ expected_nesting=2,
+ dtype=np.float32,
+ )
+
+ return input_points, input_labels, input_boxes
+
+ @property
+ def model_input_names(self):
+ image_processor_input_names = self.image_processor.model_input_names
+ return list(image_processor_input_names + ["original_sizes", "reshaped_input_sizes"])
+
+ def post_process_masks(self, *args, **kwargs):
+ return self.image_processor.post_process_masks(*args, **kwargs)
+
+ def _to_tensor(self, array, min_dim, return_tensors):
+ """
+ Convert numpy array to tensor and ensure proper dimensionality.
+ Args:
+ array: The numpy array to convert
+ min_dim: The minimum number of dimensions the result should have
+ return_tensors: The type of tensors to return (e.g., "pt" for PyTorch tensors)
+ Returns:
+ The converted array or tensor with proper dimensions
+ """
+ if return_tensors == "pt":
+ array = torch.from_numpy(array)
+ return array.unsqueeze(1) if array.ndim < min_dim else array
+ return array
+
+ def _normalize_batch_coordinates(self, inputs, original_sizes, is_bounding_box=False):
+ """
+ Normalize coordinates based on original sizes.
+ Args:
+ inputs: List of coordinate arrays
+ original_sizes: Original sizes of the images
+ is_bounding_box: Whether inputs are bounding boxes
+ Returns:
+ Normalized coordinates as list
+ """
+ if len(original_sizes) != len(inputs):
+ # Use first original size for all inputs
+ return [
+ self._normalize_coordinates(self.target_size, item, original_sizes[0], is_bounding_box=is_bounding_box)
+ for item in inputs
+ ]
+ else:
+ # Use paired original sizes for each input
+ return [
+ self._normalize_coordinates(self.target_size, item, size, is_bounding_box=is_bounding_box)
+ for item, size in zip(inputs, original_sizes)
+ ]
+
+
+__all__ = ["SamHQProcessor"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/seamless_m4t/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/seamless_m4t/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3415bb477eaec70161ceb18d0590bfa48bcd3768
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/seamless_m4t/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/seamless_m4t/__pycache__/configuration_seamless_m4t.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/seamless_m4t/__pycache__/configuration_seamless_m4t.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..df76df84d3dbdd0995bc145cf3da5d472afd55e1
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/seamless_m4t/__pycache__/configuration_seamless_m4t.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/seamless_m4t/__pycache__/feature_extraction_seamless_m4t.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/seamless_m4t/__pycache__/feature_extraction_seamless_m4t.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a2892a29f720cafe895b67b92c583d642ae82bed
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/seamless_m4t/__pycache__/feature_extraction_seamless_m4t.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/seamless_m4t/__pycache__/processing_seamless_m4t.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/seamless_m4t/__pycache__/processing_seamless_m4t.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3e73eb290495e11f7d1e67171682e6f7e023d0d6
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/seamless_m4t/__pycache__/processing_seamless_m4t.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/seamless_m4t/__pycache__/tokenization_seamless_m4t.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/seamless_m4t/__pycache__/tokenization_seamless_m4t.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ffa8cf26392e5527a6ebd36d387e069b8cef8482
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/seamless_m4t/__pycache__/tokenization_seamless_m4t.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/seed_oss/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/seed_oss/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4f0f0f8f1f68162459d5f640856cc46460aa9e26
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/seed_oss/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/seed_oss/__pycache__/configuration_seed_oss.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/seed_oss/__pycache__/configuration_seed_oss.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2ccd7f3b80868c51199ab9a0a2e7aae8f8f80d9a
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/seed_oss/__pycache__/configuration_seed_oss.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/seed_oss/__pycache__/modeling_seed_oss.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/seed_oss/__pycache__/modeling_seed_oss.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0ca228e793c744a0a8fd6f873e0e770e774ebafd
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/seed_oss/__pycache__/modeling_seed_oss.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/seed_oss/__pycache__/modular_seed_oss.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/seed_oss/__pycache__/modular_seed_oss.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9b921c63f81c82aac61ef1465a8c46070771ae97
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/seed_oss/__pycache__/modular_seed_oss.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/segformer/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/segformer/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..327d46cff948e9e52054a2c56532e3c44547d581
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/segformer/__init__.py
@@ -0,0 +1,29 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_segformer import *
+ from .image_processing_pil_segformer import *
+ from .image_processing_segformer import *
+ from .modeling_segformer import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/segformer/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/segformer/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..19dcaedadc8c495d7064edf1c43328dabaeb60c4
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/segformer/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/segformer/__pycache__/configuration_segformer.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/segformer/__pycache__/configuration_segformer.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..acf1abf27554c414d4a23f66f5ac8e37cf9ff2e3
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/segformer/__pycache__/configuration_segformer.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/segformer/__pycache__/image_processing_pil_segformer.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/segformer/__pycache__/image_processing_pil_segformer.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..99870aa5816193c0edc9a4b6fc67c4e3d826af5a
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/segformer/__pycache__/image_processing_pil_segformer.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/segformer/__pycache__/image_processing_segformer.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/segformer/__pycache__/image_processing_segformer.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..da7406e73cc6a40e2d2239ad943d2813300d1fa4
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/segformer/__pycache__/image_processing_segformer.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/segformer/__pycache__/modeling_segformer.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/segformer/__pycache__/modeling_segformer.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f9b4386ec1d3f7b553581578cf696cd528ecb1bc
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/segformer/__pycache__/modeling_segformer.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/segformer/__pycache__/modular_segformer.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/segformer/__pycache__/modular_segformer.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..975f308ae607970c1e4553eacb01916abc159b1a
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/segformer/__pycache__/modular_segformer.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/segformer/configuration_segformer.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/segformer/configuration_segformer.py
new file mode 100644
index 0000000000000000000000000000000000000000..c900ea2665e952e5def0f786c012fb36d282c6f8
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/segformer/configuration_segformer.py
@@ -0,0 +1,80 @@
+# Copyright 2021 NVIDIA and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""SegFormer model configuration"""
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring
+
+
+@auto_docstring(checkpoint="ByteDance-Seed/Seed-OSS-36B-Instruct")
+@strict
+class SegformerConfig(PreTrainedConfig):
+ r"""
+ num_encoder_blocks (`int`, *optional*, defaults to 4):
+ The number of encoder blocks (i.e. stages in the Mix Transformer encoder).
+ depths (`list[int]`, *optional*, defaults to `[2, 2, 2, 2]`):
+ The number of layers in each encoder block.
+ sr_ratios (`list[int]`, *optional*, defaults to `[8, 4, 2, 1]`):
+ Sequence reduction ratios in each encoder block.
+ patch_sizes (`list[int]`, *optional*, defaults to `[7, 3, 3, 3]`):
+ Patch size before each encoder block.
+ strides (`list[int]`, *optional*, defaults to `[4, 2, 2, 2]`):
+ Stride before each encoder block.
+ mlp_ratios (`list[int]`, *optional*, defaults to `[4, 4, 4, 4]`):
+ Ratio of the size of the hidden layer compared to the size of the input layer of the Mix FFNs in the
+ encoder blocks.
+ reshape_last_stage (`bool`, *optional*, defaults to True):
+ Whether to reshape the last stage outputs
+
+ Example:
+
+ ```python
+ >>> from transformers import SegformerModel, SegformerConfig
+
+ >>> # Initializing a SegFormer nvidia/segformer-b0-finetuned-ade-512-512 style configuration
+ >>> configuration = SegformerConfig()
+
+ >>> # Initializing a model from the nvidia/segformer-b0-finetuned-ade-512-512 style configuration
+ >>> model = SegformerModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "segformer"
+
+ num_channels: int = 3
+ num_encoder_blocks: int = 4
+ depths: list[int] | tuple[int, ...] = (2, 2, 2, 2)
+ sr_ratios: list[int] | tuple[int, ...] = (8, 4, 2, 1)
+ hidden_sizes: list[int] | tuple[int, ...] = (32, 64, 160, 256)
+ patch_sizes: list[int] | tuple[int, ...] = (7, 3, 3, 3)
+ strides: list[int] | tuple[int, ...] = (4, 2, 2, 2)
+ num_attention_heads: list[int] | tuple[int, ...] = (1, 2, 5, 8)
+ mlp_ratios: list[int] | tuple[int, ...] = (4, 4, 4, 4)
+ hidden_act: str = "gelu"
+ hidden_dropout_prob: float | int = 0.0
+ attention_probs_dropout_prob: float | int = 0.0
+ classifier_dropout_prob: float | int = 0.1
+ initializer_range: float = 0.02
+ drop_path_rate: float | int = 0.1
+ layer_norm_eps: float = 1e-6
+ decoder_hidden_size: int = 256
+ semantic_loss_ignore_index: int = 255
+ reshape_last_stage: bool = True
+
+
+__all__ = ["SegformerConfig"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/segformer/image_processing_pil_segformer.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/segformer/image_processing_pil_segformer.py
new file mode 100644
index 0000000000000000000000000000000000000000..f1d0bb0f627bf8d27df314dc6694325a8f39d100
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/segformer/image_processing_pil_segformer.py
@@ -0,0 +1,223 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/segformer/modular_segformer.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_segformer.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2025 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+import numpy as np
+
+from ...image_processing_backends import PilBackend
+from ...image_processing_utils import BatchFeature
+from ...image_utils import (
+ IMAGENET_DEFAULT_MEAN,
+ IMAGENET_DEFAULT_STD,
+ ChannelDimension,
+ ImageInput,
+ PILImageResampling,
+ SizeDict,
+)
+from ...processing_utils import ImagesKwargs, Unpack
+from ...utils import TensorType, auto_docstring, is_torch_available, is_torchvision_available
+from ...utils.import_utils import requires
+
+
+if is_torch_available():
+ pass
+if is_torchvision_available():
+ import torchvision.transforms.v2.functional as tvF
+
+
+class SegformerImageProcessorKwargs(ImagesKwargs, total=False):
+ r"""
+ do_reduce_labels (`bool`, *optional*, defaults to `self.do_reduce_labels`):
+ Whether or not to reduce all label values of segmentation maps by 1. Usually used for datasets where 0
+ is used for background, and background itself is not included in all classes of a dataset (e.g.
+ ADE20k). The background label will be replaced by 255.
+ """
+
+ do_reduce_labels: bool
+
+
+@requires(backends=("torch", "torchvision"))
+class SegformerImageProcessorPil(PilBackend):
+ """PIL backend for Segformer with reduce_label support."""
+
+ valid_kwargs = SegformerImageProcessorKwargs
+ resample = PILImageResampling.BILINEAR
+ image_mean = IMAGENET_DEFAULT_MEAN
+ image_std = IMAGENET_DEFAULT_STD
+ size = {"height": 512, "width": 512}
+ default_to_square = True
+ crop_size = None
+ do_resize = True
+ do_center_crop = None
+ do_rescale = True
+ do_normalize = True
+ do_reduce_labels = False
+ rescale_factor = 1 / 255
+
+ def __init__(self, **kwargs: Unpack[SegformerImageProcessorKwargs]):
+ super().__init__(**kwargs)
+
+ @auto_docstring
+ def preprocess(
+ self,
+ images: ImageInput,
+ segmentation_maps: ImageInput | None = None,
+ **kwargs: Unpack[SegformerImageProcessorKwargs],
+ ) -> BatchFeature:
+ r"""
+ segmentation_maps (`ImageInput`, *optional*):
+ The segmentation maps to preprocess.
+ """
+ return super().preprocess(images, segmentation_maps, **kwargs)
+
+ def _preprocess_image_like_inputs(
+ self,
+ images: ImageInput,
+ segmentation_maps: ImageInput | None,
+ do_convert_rgb: bool,
+ input_data_format: ChannelDimension,
+ return_tensors: str | TensorType | None,
+ **kwargs,
+ ) -> BatchFeature:
+ """Handle extra inputs beyond images."""
+ images = self._prepare_image_like_inputs(
+ images=images, do_convert_rgb=do_convert_rgb, input_data_format=input_data_format
+ )
+ images_kwargs = kwargs.copy()
+ images_kwargs["do_reduce_labels"] = False
+ data = {}
+ data["pixel_values"] = self._preprocess(images, **images_kwargs)
+
+ # Prepare segmentation maps if provided
+ if segmentation_maps is not None:
+ processed_segmentation_maps = self._prepare_image_like_inputs(
+ images=segmentation_maps,
+ expected_ndims=2,
+ do_convert_rgb=False,
+ input_data_format=ChannelDimension.FIRST,
+ )
+
+ segmentation_maps_kwargs = kwargs.copy()
+ segmentation_maps_kwargs.update(
+ {
+ "do_normalize": False,
+ "do_rescale": False,
+ # Nearest resample is used for segmentation maps instead of BILINEAR.
+ "resample": tvF.InterpolationMode.NEAREST_EXACT,
+ }
+ )
+ processed_segmentation_maps = self._preprocess(
+ images=processed_segmentation_maps, **segmentation_maps_kwargs
+ )
+
+ # Convert to int64 and squeeze channel dimension
+ processed_segmentation_maps = [
+ processed_segmentation_map.squeeze(0).astype(np.int64)
+ for processed_segmentation_map in processed_segmentation_maps
+ ]
+ data["labels"] = processed_segmentation_maps
+
+ return BatchFeature(data=data, tensor_type=return_tensors)
+
+ def reduce_label(self, image: np.ndarray) -> np.ndarray:
+ """Reduce label values by 1, replacing 0 with 255."""
+ # Avoid using underflow conversion
+ image[image == 0] = 255
+ image = image - 1
+ image[image == 254] = 255
+ return image
+
+ def _preprocess(
+ self,
+ images: list["np.ndarray"],
+ do_reduce_labels: bool,
+ resample: "PILImageResampling | None",
+ do_resize: bool,
+ do_rescale: bool,
+ do_normalize: bool,
+ size: SizeDict,
+ rescale_factor: float,
+ image_mean: float | list[float],
+ image_std: float | list[float],
+ **kwargs,
+ ) -> list["np.ndarray"]:
+ """Custom preprocessing for Segformer."""
+ processed_images = []
+ for image in images:
+ if do_reduce_labels:
+ image = self.reduce_label(image)
+ if do_resize:
+ image = self.resize(image, size, resample)
+ if do_rescale:
+ image = self.rescale(image, rescale_factor)
+ if do_normalize:
+ image = self.normalize(image, image_mean, image_std)
+ processed_images.append(image)
+
+ return processed_images
+
+ @requires(backends=("torch",))
+ def post_process_semantic_segmentation(self, outputs, target_sizes: list[tuple] | None = None):
+ """
+ Converts the output of [`SegformerForSemanticSegmentation`] into semantic segmentation maps.
+
+ Args:
+ outputs ([`SegformerForSemanticSegmentation`]):
+ Raw outputs of the model.
+ target_sizes (`list[Tuple]` of length `batch_size`, *optional*):
+ List of tuples corresponding to the requested final size (height, width) of each prediction. If unset,
+ predictions will not be resized.
+
+ Returns:
+ semantic_segmentation: `list[torch.Tensor]` of length `batch_size`, where each item is a semantic
+ segmentation map of shape (height, width) corresponding to the target_sizes entry (if `target_sizes` is
+ specified). Each entry of each `torch.Tensor` correspond to a semantic class id.
+ """
+ import torch
+ import torch.nn.functional as F
+
+ logits = outputs.logits
+
+ # Resize logits and compute semantic segmentation maps
+ if target_sizes is not None:
+ if len(logits) != len(target_sizes):
+ raise ValueError(
+ "Make sure that you pass in as many target sizes as the batch dimension of the logits"
+ )
+
+ if isinstance(target_sizes, torch.Tensor):
+ target_sizes = target_sizes.numpy()
+
+ semantic_segmentation = []
+
+ for idx in range(len(logits)):
+ resized_logits = F.interpolate(
+ logits[idx].unsqueeze(dim=0), size=target_sizes[idx], mode="bilinear", align_corners=False
+ )
+ semantic_map = resized_logits[0].argmax(dim=0)
+ semantic_segmentation.append(semantic_map)
+ else:
+ semantic_segmentation = logits.argmax(dim=1)
+ semantic_segmentation = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0])]
+
+ return semantic_segmentation
+
+
+__all__ = ["SegformerImageProcessorPil"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/segformer/image_processing_segformer.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/segformer/image_processing_segformer.py
new file mode 100644
index 0000000000000000000000000000000000000000..efc8c312953ef106bdb260ff3925194d20aaa34f
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/segformer/image_processing_segformer.py
@@ -0,0 +1,237 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/segformer/modular_segformer.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_segformer.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2025 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from typing import Union
+
+import torch
+import torch.nn.functional as F
+import torchvision.transforms.v2.functional as tvF
+
+from ...image_processing_backends import TorchvisionBackend
+from ...image_processing_utils import BatchFeature
+from ...image_transforms import group_images_by_shape, reorder_images
+from ...image_utils import (
+ IMAGENET_DEFAULT_MEAN,
+ IMAGENET_DEFAULT_STD,
+ ChannelDimension,
+ ImageInput,
+ PILImageResampling,
+ SizeDict,
+)
+from ...processing_utils import ImagesKwargs, Unpack
+from ...utils import TensorType, auto_docstring, is_torch_available
+
+
+class SegformerImageProcessorKwargs(ImagesKwargs, total=False):
+ r"""
+ do_reduce_labels (`bool`, *optional*, defaults to `self.do_reduce_labels`):
+ Whether or not to reduce all label values of segmentation maps by 1. Usually used for datasets where 0
+ is used for background, and background itself is not included in all classes of a dataset (e.g.
+ ADE20k). The background label will be replaced by 255.
+ """
+
+ do_reduce_labels: bool
+
+
+@auto_docstring
+class SegformerImageProcessor(TorchvisionBackend):
+ """PIL backend for Segformer with reduce_label support."""
+
+ valid_kwargs = SegformerImageProcessorKwargs
+ resample = PILImageResampling.BILINEAR
+ image_mean = IMAGENET_DEFAULT_MEAN
+ image_std = IMAGENET_DEFAULT_STD
+ size = {"height": 512, "width": 512}
+ default_to_square = True
+ crop_size = None
+ do_resize = True
+ do_center_crop = None
+ do_rescale = True
+ do_normalize = True
+ do_reduce_labels = False
+ rescale_factor = 1 / 255
+
+ def __init__(self, **kwargs: Unpack[SegformerImageProcessorKwargs]):
+ super().__init__(**kwargs)
+
+ @auto_docstring
+ def preprocess(
+ self,
+ images: ImageInput,
+ segmentation_maps: ImageInput | None = None,
+ **kwargs: Unpack[SegformerImageProcessorKwargs],
+ ) -> BatchFeature:
+ r"""
+ segmentation_maps (`ImageInput`, *optional*):
+ The segmentation maps to preprocess.
+ """
+ return super().preprocess(images, segmentation_maps, **kwargs)
+
+ def _preprocess_image_like_inputs(
+ self,
+ images: ImageInput,
+ segmentation_maps: ImageInput | None,
+ do_convert_rgb: bool,
+ input_data_format: ChannelDimension,
+ return_tensors: str | TensorType | None,
+ device: Union[str, "torch.device"] | None = None,
+ **kwargs,
+ ) -> BatchFeature:
+ """Handle extra inputs beyond images."""
+ images = self._prepare_image_like_inputs(
+ images=images, do_convert_rgb=do_convert_rgb, input_data_format=input_data_format, device=device
+ )
+ images_kwargs = kwargs.copy()
+ images_kwargs["do_reduce_labels"] = False
+ data = {}
+ data["pixel_values"] = self._preprocess(images, **images_kwargs)
+
+ # Prepare segmentation maps if provided
+ if segmentation_maps is not None:
+ processed_segmentation_maps = self._prepare_image_like_inputs(
+ images=segmentation_maps,
+ expected_ndims=2,
+ do_convert_rgb=False,
+ input_data_format=ChannelDimension.FIRST,
+ )
+
+ segmentation_maps_kwargs = kwargs.copy()
+ segmentation_maps_kwargs.update(
+ {
+ "do_normalize": False,
+ "do_rescale": False,
+ # Nearest resample is used for segmentation maps instead of BILINEAR.
+ "resample": tvF.InterpolationMode.NEAREST_EXACT,
+ }
+ )
+ processed_segmentation_maps = self._preprocess(
+ images=processed_segmentation_maps, **segmentation_maps_kwargs
+ )
+
+ # Convert to int64 and squeeze channel dimension
+ processed_segmentation_maps = [
+ processed_segmentation_map.squeeze(0).to(torch.int64)
+ for processed_segmentation_map in processed_segmentation_maps
+ ]
+ data["labels"] = processed_segmentation_maps
+
+ return BatchFeature(data=data, tensor_type=return_tensors)
+
+ def reduce_label(self, labels: list["torch.Tensor"]) -> list["torch.Tensor"]:
+ """Reduce label values by 1, replacing 0 with 255."""
+ for idx in range(len(labels)):
+ label = labels[idx]
+ label = torch.where(label == 0, torch.tensor(255, dtype=label.dtype, device=label.device), label)
+ label = label - 1
+ label = torch.where(label == 254, torch.tensor(255, dtype=label.dtype, device=label.device), label)
+ labels[idx] = label
+ return labels
+
+ def _preprocess(
+ self,
+ images: list["torch.Tensor"],
+ do_reduce_labels: bool,
+ resample: "PILImageResampling | None",
+ do_resize: bool,
+ do_rescale: bool,
+ do_normalize: bool,
+ size: SizeDict,
+ rescale_factor: float,
+ image_mean: float | list[float],
+ image_std: float | list[float],
+ disable_grouping: bool,
+ **kwargs,
+ ) -> BatchFeature: # Return type can be list if return_tensors=None
+ """Custom preprocessing for Segformer."""
+ if do_reduce_labels:
+ images = self.reduce_label(images) # Apply reduction if needed
+
+ # Group images by size for batched resizing
+ resized_images = images
+ if do_resize:
+ grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping)
+ resized_images_grouped = {}
+ for shape, stacked_images in grouped_images.items():
+ resized_stacked_images = self.resize(image=stacked_images, size=size, resample=resample)
+ resized_images_grouped[shape] = resized_stacked_images
+ resized_images = reorder_images(resized_images_grouped, grouped_images_index)
+
+ # Group images by size for further processing (rescale/normalize)
+ # Needed in case do_resize is False, or resize returns images with different sizes
+ grouped_images, grouped_images_index = group_images_by_shape(resized_images, disable_grouping=disable_grouping)
+ processed_images_grouped = {}
+ for shape, stacked_images in grouped_images.items():
+ # Fused rescale and normalize
+ stacked_images = self.rescale_and_normalize(
+ stacked_images, do_rescale, rescale_factor, do_normalize, image_mean, image_std
+ )
+ processed_images_grouped[shape] = stacked_images
+
+ processed_images = reorder_images(processed_images_grouped, grouped_images_index)
+
+ return processed_images
+
+ def post_process_semantic_segmentation(self, outputs, target_sizes: list[tuple] | None = None):
+ """
+ Converts the output of [`SegformerForSemanticSegmentation`] into semantic segmentation maps.
+
+ Args:
+ outputs ([`SegformerForSemanticSegmentation`]):
+ Raw outputs of the model.
+ target_sizes (`list[Tuple]` of length `batch_size`, *optional*):
+ List of tuples corresponding to the requested final size (height, width) of each prediction. If unset,
+ predictions will not be resized.
+
+ Returns:
+ semantic_segmentation: `list[torch.Tensor]` of length `batch_size`, where each item is a semantic
+ segmentation map of shape (height, width) corresponding to the target_sizes entry (if `target_sizes` is
+ specified). Each entry of each `torch.Tensor` correspond to a semantic class id.
+ """
+ if not is_torch_available():
+ raise ImportError("PyTorch is required for post_process_semantic_segmentation")
+
+ logits = outputs.logits
+
+ # Resize logits and compute semantic segmentation maps
+ if target_sizes is not None:
+ if len(logits) != len(target_sizes):
+ raise ValueError(
+ "Make sure that you pass in as many target sizes as the batch dimension of the logits"
+ )
+
+ if isinstance(target_sizes, torch.Tensor):
+ target_sizes = target_sizes.numpy()
+
+ semantic_segmentation = []
+
+ for idx in range(len(logits)):
+ resized_logits = F.interpolate(
+ logits[idx].unsqueeze(dim=0), size=target_sizes[idx], mode="bilinear", align_corners=False
+ )
+ semantic_map = resized_logits[0].argmax(dim=0)
+ semantic_segmentation.append(semantic_map)
+ else:
+ semantic_segmentation = logits.argmax(dim=1)
+ semantic_segmentation = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0])]
+
+ return semantic_segmentation
+
+
+__all__ = ["SegformerImageProcessor"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/segformer/modeling_segformer.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/segformer/modeling_segformer.py
new file mode 100644
index 0000000000000000000000000000000000000000..9ae5f91f3248c88c85f39bcc8385ed3befb820c7
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/segformer/modeling_segformer.py
@@ -0,0 +1,625 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/segformer/modular_segformer.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_segformer.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2025 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import math
+from collections.abc import Callable
+
+import torch
+from torch import nn
+from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss
+
+from ...activations import ACT2FN
+from ...backbone_utils import filter_output_hidden_states
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import BaseModelOutput, ImageClassifierOutput, SemanticSegmenterOutput
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import TransformersKwargs, auto_docstring
+from ...utils.generic import can_return_tuple, merge_with_config_defaults
+from ...utils.output_capturing import OutputRecorder, capture_outputs
+from .configuration_segformer import SegformerConfig
+
+
+@auto_docstring
+class SegFormerImageClassifierOutput(ImageClassifierOutput):
+ r"""
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
+ Classification (or regression if config.num_labels==1) loss.
+ logits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`):
+ Classification (or regression if config.num_labels==1) scores (before SoftMax).
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
+ one for the output of each stage) of shape `(batch_size, num_channels, height, width)`. Hidden-states (also
+ called feature maps) of the model at the output of each stage.
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, patch_size,
+ sequence_length)`.
+
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
+ heads.
+ """
+
+ loss: torch.FloatTensor | None = None
+ logits: torch.FloatTensor | None = None
+ hidden_states: tuple[torch.FloatTensor] | None = None
+ attentions: tuple[torch.FloatTensor] | None = None
+
+
+class SegformerOverlapPatchEmbeddings(nn.Module):
+ """Overlapping patch embeddings via strided convolution with symmetric padding."""
+
+ def __init__(self, patch_size, stride, num_channels, hidden_size):
+ super().__init__()
+ self.proj = nn.Conv2d(
+ num_channels,
+ hidden_size,
+ kernel_size=patch_size,
+ stride=stride,
+ padding=patch_size // 2,
+ )
+ self.layer_norm = nn.LayerNorm(hidden_size)
+
+ def forward(self, pixel_values):
+ embeddings = self.proj(pixel_values)
+ _, _, height, width = embeddings.shape
+ embeddings = embeddings.flatten(2).transpose(1, 2)
+ embeddings = self.layer_norm(embeddings)
+ return embeddings, height, width
+
+
+class SegformerSequenceReduction(nn.Module):
+ """Spatially reduces key/value tokens via a strided convolution.
+
+ Projects the sequence from (B, H*W, C) → (B, H'*W', C) where H' = H / sr_ratio.
+ This reduces the O(N²) attention cost of the original sequence.
+ """
+
+ def __init__(self, hidden_size: int, sequence_reduction_ratio: int):
+ super().__init__()
+ self.sequence_reduction = nn.Conv2d(
+ hidden_size, hidden_size, kernel_size=sequence_reduction_ratio, stride=sequence_reduction_ratio
+ )
+ self.layer_norm = nn.LayerNorm(hidden_size)
+
+ def forward(self, hidden_states: torch.Tensor, height: int, width: int) -> torch.Tensor:
+ batch_size, seq_len, num_channels = hidden_states.shape
+ # (B, N, C) → (B, C, H, W) → strided conv → (B, C, H', W') → (B, H'W', C)
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, num_channels, height, width)
+ hidden_states = self.sequence_reduction(hidden_states)
+ hidden_states = hidden_states.reshape(batch_size, num_channels, -1).transpose(1, 2)
+ hidden_states = self.layer_norm(hidden_states)
+ return hidden_states
+
+
+def eager_attention_forward(
+ module: nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: torch.Tensor | None,
+ scaling: float | None = None,
+ dropout: float = 0.0,
+ **kwargs: Unpack[TransformersKwargs],
+):
+ if scaling is None:
+ scaling = query.size(-1) ** -0.5
+
+ # Take the dot product between "query" and "key" to get the raw attention scores.
+ attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
+
+ if attention_mask is not None:
+ attn_weights = attn_weights + attention_mask
+
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
+
+ attn_output = torch.matmul(attn_weights, value)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+
+ return attn_output, attn_weights
+
+
+class SegformerAttention(nn.Module):
+ """Efficient self-attention where keys/values are spatially reduced via strided convolution.
+
+ Introduced in [PvT](https://huggingface.co/papers/2102.12122): queries attend to the full
+ sequence while key/value tokens are downsampled, reducing the O(N²) attention cost.
+ """
+
+ def __init__(self, config, hidden_size, num_attention_heads, sequence_reduction_ratio):
+ super().__init__()
+ self.config = config
+ # Override with per-stage dimensions: each Segformer stage has varying hidden sizes
+ self.num_attention_heads = num_attention_heads
+ self.head_dim = hidden_size // num_attention_heads
+ self.attention_dropout = config.attention_probs_dropout_prob
+ self.scaling = self.head_dim**-0.5
+ self.is_causal = False
+ # No qkv_bias in Segformer (unlike ViT)
+ self.q_proj = nn.Linear(hidden_size, num_attention_heads * self.head_dim)
+ self.k_proj = nn.Linear(hidden_size, num_attention_heads * self.head_dim)
+ self.v_proj = nn.Linear(hidden_size, num_attention_heads * self.head_dim)
+ self.o_proj = nn.Linear(num_attention_heads * self.head_dim, hidden_size)
+ self.sequence_reduction_ratio = sequence_reduction_ratio
+ if sequence_reduction_ratio > 1:
+ self.sequence_reduction = SegformerSequenceReduction(hidden_size, sequence_reduction_ratio)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ height: int,
+ width: int,
+ attention_mask: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor, torch.Tensor]:
+ input_shape = hidden_states.shape[:-1]
+ hidden_shape = (*input_shape, -1, self.head_dim)
+
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+
+ kv_hidden_states = hidden_states
+ if self.sequence_reduction_ratio > 1:
+ kv_hidden_states = self.sequence_reduction(hidden_states, height, width)
+
+ kv_hidden_shape = (*kv_hidden_states.shape[:-1], -1, self.head_dim)
+ key_states = self.k_proj(kv_hidden_states).view(kv_hidden_shape).transpose(1, 2)
+ value_states = self.v_proj(kv_hidden_states).view(kv_hidden_shape).transpose(1, 2)
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_states,
+ key_states,
+ value_states,
+ attention_mask,
+ dropout=0.0 if not self.training else self.attention_dropout,
+ scaling=self.scaling,
+ **kwargs,
+ )
+
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ attn_output = self.o_proj(attn_output)
+
+ return attn_output, attn_weights
+
+
+class SegformerDepthWiseConv(nn.Module):
+ """Depthwise convolution used in the Mix-FFN to implicitly encode positional information."""
+
+ def __init__(self, dim=768):
+ super().__init__()
+ self.dwconv = nn.Conv2d(dim, dim, 3, 1, 1, groups=dim)
+
+ def forward(self, hidden_states, height, width):
+ batch_size, seq_len, num_channels = hidden_states.shape
+ hidden_states = hidden_states.transpose(1, 2).view(batch_size, num_channels, height, width)
+ hidden_states = self.dwconv(hidden_states)
+ hidden_states = hidden_states.flatten(2).transpose(1, 2)
+ return hidden_states
+
+
+class SegformerMixMLP(nn.Module):
+ """Mix-FFN: fc1 → DWConv → activation → fc2.
+
+ The depthwise convolution implicitly encodes positional information, replacing the explicit
+ position embedding used in standard ViT/BeiT MLPs.
+ """
+
+ def __init__(self, config, in_features, hidden_features=None, out_features=None):
+ super().__init__()
+ out_features = out_features or in_features
+ self.fc1 = nn.Linear(in_features, hidden_features)
+ self.dwconv = SegformerDepthWiseConv(hidden_features)
+ self.activation_fn = ACT2FN[config.hidden_act] if isinstance(config.hidden_act, str) else config.hidden_act
+ self.fc2 = nn.Linear(hidden_features, out_features)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(self, hidden_states, height, width):
+ hidden_states = self.fc1(hidden_states)
+ hidden_states = self.dwconv(hidden_states, height, width)
+ hidden_states = self.activation_fn(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = self.fc2(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ return hidden_states
+
+
+class SegformerDropPath(nn.Module):
+ """Stochastic depth (DropPath) per sample, for residual blocks.
+
+ Identity when ``drop_prob`` is 0 or outside training. See `Deep Networks with Stochastic Depth
+ `_.
+ """
+
+ def __init__(self, drop_prob: float = 0.0) -> None:
+ super().__init__()
+ self.drop_prob = drop_prob
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ if self.drop_prob == 0.0 or not self.training:
+ return hidden_states
+ keep_prob = 1 - self.drop_prob
+ shape = (hidden_states.shape[0],) + (1,) * (hidden_states.ndim - 1)
+ random_tensor = torch.rand(shape, dtype=hidden_states.dtype, device=hidden_states.device)
+ random_tensor = torch.floor(random_tensor + keep_prob)
+ return hidden_states.div(keep_prob) * random_tensor
+
+ def extra_repr(self) -> str:
+ return f"p={self.drop_prob}"
+
+
+class SegformerLayer(GradientCheckpointingLayer):
+ """Transformer block with DropPath on both branches and a MixFFN instead of a plain MLP."""
+
+ def __init__(self, config, hidden_size, num_attention_heads, drop_path, sequence_reduction_ratio, mlp_ratio):
+ super().__init__()
+ self.layernorm_before = nn.LayerNorm(hidden_size)
+ self.attention = SegformerAttention(
+ config,
+ hidden_size=hidden_size,
+ num_attention_heads=num_attention_heads,
+ sequence_reduction_ratio=sequence_reduction_ratio,
+ )
+ self.drop_path = SegformerDropPath(drop_path) if drop_path > 0.0 else nn.Identity()
+ self.layernorm_after = nn.LayerNorm(hidden_size)
+ self.mlp = SegformerMixMLP(config, in_features=hidden_size, hidden_features=int(hidden_size * mlp_ratio))
+ self.hidden_dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ height: int,
+ width: int,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.Tensor:
+ residual = hidden_states
+ hidden_states = self.layernorm_before(hidden_states)
+ hidden_states, _ = self.attention(hidden_states, height, width, **kwargs)
+ hidden_states = self.hidden_dropout(hidden_states)
+ hidden_states = self.drop_path(hidden_states) + residual
+
+ residual = hidden_states
+ hidden_states = self.layernorm_after(hidden_states)
+ hidden_states = self.mlp(hidden_states, height, width)
+ hidden_states = self.drop_path(hidden_states) + residual
+
+ return hidden_states
+
+
+class SegformerStage(nn.Module):
+ """One encoder stage: OverlapPatchEmbeddings → SegformerLayer blocks → LayerNorm."""
+
+ def __init__(self, config, stage_idx: int, drop_path_decays: list[float]):
+ super().__init__()
+ depth_start = sum(config.depths[:stage_idx])
+ # All stages reshape to (B, C, H, W); only the last stage skips it when reshape_last_stage=False.
+ self.reshape = stage_idx < config.num_encoder_blocks - 1 or config.reshape_last_stage
+ self.patch_embeddings = SegformerOverlapPatchEmbeddings(
+ patch_size=config.patch_sizes[stage_idx],
+ stride=config.strides[stage_idx],
+ num_channels=config.num_channels if stage_idx == 0 else config.hidden_sizes[stage_idx - 1],
+ hidden_size=config.hidden_sizes[stage_idx],
+ )
+ self.blocks = nn.ModuleList(
+ [
+ SegformerLayer(
+ config,
+ hidden_size=config.hidden_sizes[stage_idx],
+ num_attention_heads=config.num_attention_heads[stage_idx],
+ drop_path=drop_path_decays[depth_start + layer_idx],
+ sequence_reduction_ratio=config.sr_ratios[stage_idx],
+ mlp_ratio=config.mlp_ratios[stage_idx],
+ )
+ for layer_idx in range(config.depths[stage_idx])
+ ]
+ )
+ self.layer_norm = nn.LayerNorm(config.hidden_sizes[stage_idx])
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.Tensor:
+ hidden_states, height, width = self.patch_embeddings(hidden_states)
+ for block in self.blocks:
+ hidden_states = block(hidden_states, height, width, **kwargs)
+ hidden_states = self.layer_norm(hidden_states)
+ if self.reshape:
+ batch_size = hidden_states.shape[0]
+ hidden_states = hidden_states.reshape(batch_size, height, width, -1).permute(0, 3, 1, 2).contiguous()
+
+ return hidden_states
+
+
+@auto_docstring
+class SegformerPreTrainedModel(PreTrainedModel):
+ config: SegformerConfig
+ base_model_prefix = "segformer"
+ main_input_name = "pixel_values"
+ input_modalities = ("image",)
+ supports_gradient_checkpointing = True
+ _no_split_modules = ["SegformerStage"]
+ _supports_sdpa = True
+ _supports_flash_attn = True
+ _supports_flex_attn = True
+ _supports_attention_backend = True
+ _can_compile_fullgraph = True
+ _can_record_outputs = {
+ # capture_initial_hidden_state=False: stage 0's input is raw pixel values, not a meaningful embedding.
+ "hidden_states": OutputRecorder(SegformerStage, capture_initial_hidden_state=False),
+ "attentions": SegformerAttention,
+ }
+ _input_embed_layer = "patch_embeddings"
+
+
+@auto_docstring
+class SegformerModel(SegformerPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.config = config
+
+ drop_path_decays = [
+ config.drop_path_rate * i / max(sum(config.depths) - 1, 1) for i in range(sum(config.depths))
+ ]
+ self.stages = nn.ModuleList(
+ [SegformerStage(config, stage_idx, drop_path_decays) for stage_idx in range(config.num_encoder_blocks)]
+ )
+
+ self.post_init()
+
+ @merge_with_config_defaults
+ @capture_outputs
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: torch.FloatTensor,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> BaseModelOutput:
+ hidden_states = pixel_values
+ for stage in self.stages:
+ hidden_states = stage(hidden_states, **kwargs)
+ return BaseModelOutput(last_hidden_state=hidden_states)
+
+
+@auto_docstring(
+ custom_intro="""
+ SegFormer Model transformer with an image classification head on top (a linear layer on top of the final hidden
+ states) e.g. for ImageNet.
+ """
+)
+class SegformerForImageClassification(SegformerPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.num_labels = config.num_labels
+ self.segformer = SegformerModel(config)
+
+ # Classifier head
+ self.classifier = nn.Linear(config.hidden_sizes[-1], config.num_labels)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> SegFormerImageClassifierOutput:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+ outputs = self.segformer(pixel_values, **kwargs)
+
+ sequence_output = outputs.last_hidden_state
+
+ # convert last hidden states to (batch_size, height*width, hidden_size)
+ batch_size = sequence_output.shape[0]
+ if self.config.reshape_last_stage:
+ # (batch_size, num_channels, height, width) -> (batch_size, height, width, num_channels)
+ sequence_output = sequence_output.permute(0, 2, 3, 1)
+ sequence_output = sequence_output.reshape(batch_size, -1, self.config.hidden_sizes[-1])
+
+ # global average pooling
+ sequence_output = sequence_output.mean(dim=1)
+
+ logits = self.classifier(sequence_output)
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(labels, logits, self.config, **kwargs)
+
+ return SegFormerImageClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+class SegformerMLP(nn.Module):
+ """Projects each encoder stage's feature map to a common `decoder_hidden_size`."""
+
+ def __init__(self, config: SegformerConfig, input_dim):
+ super().__init__()
+ self.proj = nn.Linear(input_dim, config.decoder_hidden_size)
+
+ def forward(self, hidden_states: torch.Tensor):
+ hidden_states = hidden_states.flatten(2).transpose(1, 2)
+ hidden_states = self.proj(hidden_states)
+ return hidden_states
+
+
+class SegformerDecodeHead(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ # linear layers which will unify the channel dimension of each of the encoder blocks to the same config.decoder_hidden_size
+ linear_projections = []
+ for stage_idx in range(config.num_encoder_blocks):
+ linear_projections.append(SegformerMLP(config, input_dim=config.hidden_sizes[stage_idx]))
+ self.linear_projections = nn.ModuleList(linear_projections)
+
+ # the following 3 layers implement the ConvModule of the original implementation
+ self.linear_fuse = nn.Conv2d(
+ in_channels=config.decoder_hidden_size * config.num_encoder_blocks,
+ out_channels=config.decoder_hidden_size,
+ kernel_size=1,
+ bias=False,
+ )
+ self.batch_norm = nn.BatchNorm2d(config.decoder_hidden_size)
+ self.activation = nn.ReLU()
+
+ self.dropout = nn.Dropout(config.classifier_dropout_prob)
+ self.classifier = nn.Conv2d(config.decoder_hidden_size, config.num_labels, kernel_size=1)
+
+ self.config = config
+
+ def forward(self, encoder_hidden_states: torch.FloatTensor, **kwargs) -> torch.Tensor:
+ batch_size = encoder_hidden_states[-1].shape[0]
+
+ all_hidden_states = ()
+ for encoder_hidden_state, linear_proj in zip(encoder_hidden_states, self.linear_projections):
+ if self.config.reshape_last_stage is False and encoder_hidden_state.ndim == 3:
+ height = width = int(math.sqrt(encoder_hidden_state.shape[-1]))
+ encoder_hidden_state = (
+ encoder_hidden_state.reshape(batch_size, height, width, -1).permute(0, 3, 1, 2).contiguous()
+ )
+
+ # unify channel dimension
+ height, width = encoder_hidden_state.shape[2], encoder_hidden_state.shape[3]
+ encoder_hidden_state = linear_proj(encoder_hidden_state)
+ encoder_hidden_state = encoder_hidden_state.transpose(1, 2)
+ encoder_hidden_state = encoder_hidden_state.reshape(batch_size, -1, height, width)
+ # upsample
+ encoder_hidden_state = nn.functional.interpolate(
+ encoder_hidden_state, size=encoder_hidden_states[0].size()[2:], mode="bilinear", align_corners=False
+ )
+ all_hidden_states += (encoder_hidden_state,)
+
+ hidden_states = self.linear_fuse(torch.cat(all_hidden_states[::-1], dim=1))
+ hidden_states = self.batch_norm(hidden_states)
+ hidden_states = self.activation(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+
+ # logits are of shape (batch_size, num_labels, height/4, width/4)
+ logits = self.classifier(hidden_states)
+
+ return logits
+
+
+@auto_docstring(
+ custom_intro="""
+ SegFormer Model transformer with an all-MLP decode head on top e.g. for ADE20k, CityScapes.
+ """
+)
+class SegformerForSemanticSegmentation(SegformerPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.segformer = SegformerModel(config)
+ self.decode_head = SegformerDecodeHead(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @filter_output_hidden_states
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: torch.FloatTensor,
+ labels: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> SemanticSegmenterOutput:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, height, width)`, *optional*):
+ Ground truth semantic segmentation maps for computing the loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels > 1`, a classification loss is computed (Cross-Entropy).
+
+ Examples:
+
+ ```python
+ >>> from transformers import AutoImageProcessor, SegformerForSemanticSegmentation
+ >>> from PIL import Image
+ >>> import httpx
+ >>> from io import BytesIO
+
+ >>> image_processor = AutoImageProcessor.from_pretrained("nvidia/segformer-b0-finetuned-ade-512-512")
+ >>> model = SegformerForSemanticSegmentation.from_pretrained("nvidia/segformer-b0-finetuned-ade-512-512")
+
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
+ >>> with httpx.stream("GET", url) as response:
+ ... image = Image.open(BytesIO(response.read()))
+
+ >>> inputs = image_processor(images=image, return_tensors="pt")
+ >>> outputs = model(**inputs)
+ >>> logits = outputs.logits # shape (batch_size, num_labels, height/4, width/4)
+ >>> list(logits.shape)
+ [1, 150, 128, 128]
+ ```"""
+ if labels is not None and self.config.num_labels < 1:
+ raise ValueError(f"Number of labels should be >=0: {self.config.num_labels}")
+
+ # The decode head always needs all stage outputs, so force hidden_states on internally.
+ kwargs["output_hidden_states"] = True
+ outputs = self.segformer(pixel_values, **kwargs)
+
+ encoder_hidden_states = outputs.hidden_states
+
+ logits = self.decode_head(encoder_hidden_states)
+
+ loss = None
+ if labels is not None:
+ # upsample logits to the images' original size
+ upsampled_logits = nn.functional.interpolate(
+ logits, size=labels.shape[-2:], mode="bilinear", align_corners=False
+ )
+ if self.config.num_labels > 1:
+ loss_fct = CrossEntropyLoss(ignore_index=self.config.semantic_loss_ignore_index)
+ loss = loss_fct(upsampled_logits, labels)
+ elif self.config.num_labels == 1:
+ valid_mask = ((labels >= 0) & (labels != self.config.semantic_loss_ignore_index)).float()
+ loss_fct = BCEWithLogitsLoss(reduction="none")
+ loss = loss_fct(upsampled_logits.squeeze(1), labels.float())
+ loss = (loss * valid_mask).mean()
+
+ return SemanticSegmenterOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+__all__ = [
+ "SegformerDecodeHead",
+ "SegformerForImageClassification",
+ "SegformerForSemanticSegmentation",
+ "SegformerLayer",
+ "SegformerModel",
+ "SegformerPreTrainedModel",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/segformer/modular_segformer.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/segformer/modular_segformer.py
new file mode 100644
index 0000000000000000000000000000000000000000..47aae8cc6b0127923a2bcfc963eb7e383291aa4d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/segformer/modular_segformer.py
@@ -0,0 +1,780 @@
+# Copyright 2025 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import math
+from collections.abc import Callable
+from typing import Union
+
+import numpy as np
+import torch
+import torchvision.transforms.v2.functional as tvF
+from torch import nn
+from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss
+
+from transformers.models.beit.image_processing_beit import BeitImageProcessor
+from transformers.models.beit.image_processing_pil_beit import BeitImageProcessorPil
+
+from ...activations import ACT2FN
+from ...backbone_utils import filter_output_hidden_states
+from ...image_processing_utils import BatchFeature
+from ...image_transforms import group_images_by_shape, reorder_images
+from ...image_utils import (
+ IMAGENET_DEFAULT_MEAN,
+ IMAGENET_DEFAULT_STD,
+ ChannelDimension,
+ ImageInput,
+ PILImageResampling,
+ SizeDict,
+)
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import BaseModelOutput, ImageClassifierOutput, SemanticSegmenterOutput
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS
+from ...processing_utils import Unpack
+from ...utils import TensorType, TransformersKwargs, auto_docstring
+from ...utils.generic import can_return_tuple, merge_with_config_defaults
+from ...utils.import_utils import requires
+from ...utils.output_capturing import OutputRecorder, capture_outputs
+from ..swin.modeling_swin import SwinDropPath
+from ..vit.modeling_vit import ViTAttention, ViTPreTrainedModel, eager_attention_forward
+from .configuration_segformer import SegformerConfig
+
+
+class SegformerImageProcessor(BeitImageProcessor):
+ resample = PILImageResampling.BILINEAR
+ image_mean = IMAGENET_DEFAULT_MEAN
+ image_std = IMAGENET_DEFAULT_STD
+ size = {"height": 512, "width": 512}
+ do_resize = True
+ do_rescale = True
+ rescale_factor = 1 / 255
+ do_normalize = True
+ do_reduce_labels = False
+ do_center_crop = None
+ crop_size = None
+
+ def _preprocess_image_like_inputs(
+ self,
+ images: ImageInput,
+ segmentation_maps: ImageInput | None,
+ do_convert_rgb: bool,
+ input_data_format: ChannelDimension,
+ return_tensors: str | TensorType | None,
+ device: Union[str, "torch.device"] | None = None,
+ **kwargs,
+ ) -> BatchFeature:
+ """Handle extra inputs beyond images."""
+ images = self._prepare_image_like_inputs(
+ images=images, do_convert_rgb=do_convert_rgb, input_data_format=input_data_format, device=device
+ )
+ images_kwargs = kwargs.copy()
+ images_kwargs["do_reduce_labels"] = False
+ data = {}
+ data["pixel_values"] = self._preprocess(images, **images_kwargs)
+
+ # Prepare segmentation maps if provided
+ if segmentation_maps is not None:
+ processed_segmentation_maps = self._prepare_image_like_inputs(
+ images=segmentation_maps,
+ expected_ndims=2,
+ do_convert_rgb=False,
+ input_data_format=ChannelDimension.FIRST,
+ )
+
+ segmentation_maps_kwargs = kwargs.copy()
+ segmentation_maps_kwargs.update(
+ {
+ "do_normalize": False,
+ "do_rescale": False,
+ # Nearest resample is used for segmentation maps instead of BILINEAR.
+ "resample": tvF.InterpolationMode.NEAREST_EXACT,
+ }
+ )
+ processed_segmentation_maps = self._preprocess(
+ images=processed_segmentation_maps, **segmentation_maps_kwargs
+ )
+
+ # Convert to int64 and squeeze channel dimension
+ processed_segmentation_maps = [
+ processed_segmentation_map.squeeze(0).to(torch.int64)
+ for processed_segmentation_map in processed_segmentation_maps
+ ]
+ data["labels"] = processed_segmentation_maps
+
+ return BatchFeature(data=data, tensor_type=return_tensors)
+
+ def _preprocess(
+ self,
+ images: list["torch.Tensor"],
+ do_reduce_labels: bool,
+ resample: "PILImageResampling | None",
+ do_resize: bool,
+ do_rescale: bool,
+ do_normalize: bool,
+ size: SizeDict,
+ rescale_factor: float,
+ image_mean: float | list[float],
+ image_std: float | list[float],
+ disable_grouping: bool,
+ **kwargs,
+ ) -> BatchFeature: # Return type can be list if return_tensors=None
+ if do_reduce_labels:
+ images = self.reduce_label(images) # Apply reduction if needed
+
+ # Group images by size for batched resizing
+ resized_images = images
+ if do_resize:
+ grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping)
+ resized_images_grouped = {}
+ for shape, stacked_images in grouped_images.items():
+ resized_stacked_images = self.resize(image=stacked_images, size=size, resample=resample)
+ resized_images_grouped[shape] = resized_stacked_images
+ resized_images = reorder_images(resized_images_grouped, grouped_images_index)
+
+ # Group images by size for further processing (rescale/normalize)
+ # Needed in case do_resize is False, or resize returns images with different sizes
+ grouped_images, grouped_images_index = group_images_by_shape(resized_images, disable_grouping=disable_grouping)
+ processed_images_grouped = {}
+ for shape, stacked_images in grouped_images.items():
+ # Fused rescale and normalize
+ stacked_images = self.rescale_and_normalize(
+ stacked_images, do_rescale, rescale_factor, do_normalize, image_mean, image_std
+ )
+ processed_images_grouped[shape] = stacked_images
+
+ processed_images = reorder_images(processed_images_grouped, grouped_images_index)
+
+ return processed_images
+
+
+@requires(backends=("torch", "torchvision"))
+class SegformerImageProcessorPil(BeitImageProcessorPil):
+ resample = PILImageResampling.BILINEAR
+ image_mean = IMAGENET_DEFAULT_MEAN
+ image_std = IMAGENET_DEFAULT_STD
+ size = {"height": 512, "width": 512}
+ do_resize = True
+ do_rescale = True
+ rescale_factor = 1 / 255
+ do_normalize = True
+ do_reduce_labels = False
+ do_center_crop = None
+ crop_size = None
+
+ def _preprocess_image_like_inputs(
+ self,
+ images: ImageInput,
+ segmentation_maps: ImageInput | None,
+ do_convert_rgb: bool,
+ input_data_format: ChannelDimension,
+ return_tensors: str | TensorType | None,
+ **kwargs,
+ ) -> BatchFeature:
+ """Handle extra inputs beyond images."""
+ images = self._prepare_image_like_inputs(
+ images=images, do_convert_rgb=do_convert_rgb, input_data_format=input_data_format
+ )
+ images_kwargs = kwargs.copy()
+ images_kwargs["do_reduce_labels"] = False
+ data = {}
+ data["pixel_values"] = self._preprocess(images, **images_kwargs)
+
+ # Prepare segmentation maps if provided
+ if segmentation_maps is not None:
+ processed_segmentation_maps = self._prepare_image_like_inputs(
+ images=segmentation_maps,
+ expected_ndims=2,
+ do_convert_rgb=False,
+ input_data_format=ChannelDimension.FIRST,
+ )
+
+ segmentation_maps_kwargs = kwargs.copy()
+ segmentation_maps_kwargs.update(
+ {
+ "do_normalize": False,
+ "do_rescale": False,
+ # Nearest resample is used for segmentation maps instead of BILINEAR.
+ "resample": tvF.InterpolationMode.NEAREST_EXACT,
+ }
+ )
+ processed_segmentation_maps = self._preprocess(
+ images=processed_segmentation_maps, **segmentation_maps_kwargs
+ )
+
+ # Convert to int64 and squeeze channel dimension
+ processed_segmentation_maps = [
+ processed_segmentation_map.squeeze(0).astype(np.int64)
+ for processed_segmentation_map in processed_segmentation_maps
+ ]
+ data["labels"] = processed_segmentation_maps
+
+ return BatchFeature(data=data, tensor_type=return_tensors)
+
+ def _preprocess(
+ self,
+ images: list["np.ndarray"],
+ do_reduce_labels: bool,
+ resample: "PILImageResampling | None",
+ do_resize: bool,
+ do_rescale: bool,
+ do_normalize: bool,
+ size: SizeDict,
+ rescale_factor: float,
+ image_mean: float | list[float],
+ image_std: float | list[float],
+ **kwargs,
+ ) -> list["np.ndarray"]:
+ """Custom preprocessing for Segformer."""
+ processed_images = []
+ for image in images:
+ if do_reduce_labels:
+ image = self.reduce_label(image)
+ if do_resize:
+ image = self.resize(image, size, resample)
+ if do_rescale:
+ image = self.rescale(image, rescale_factor)
+ if do_normalize:
+ image = self.normalize(image, image_mean, image_std)
+ processed_images.append(image)
+
+ return processed_images
+
+
+@auto_docstring
+class SegFormerImageClassifierOutput(ImageClassifierOutput):
+ r"""
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
+ Classification (or regression if config.num_labels==1) loss.
+ logits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`):
+ Classification (or regression if config.num_labels==1) scores (before SoftMax).
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
+ one for the output of each stage) of shape `(batch_size, num_channels, height, width)`. Hidden-states (also
+ called feature maps) of the model at the output of each stage.
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, patch_size,
+ sequence_length)`.
+
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
+ heads.
+ """
+
+ loss: torch.FloatTensor | None = None
+ logits: torch.FloatTensor | None = None
+ hidden_states: tuple[torch.FloatTensor] | None = None
+ attentions: tuple[torch.FloatTensor] | None = None
+
+
+class SegformerOverlapPatchEmbeddings(nn.Module):
+ """Overlapping patch embeddings via strided convolution with symmetric padding."""
+
+ def __init__(self, patch_size, stride, num_channels, hidden_size):
+ super().__init__()
+ self.proj = nn.Conv2d(
+ num_channels,
+ hidden_size,
+ kernel_size=patch_size,
+ stride=stride,
+ padding=patch_size // 2,
+ )
+ self.layer_norm = nn.LayerNorm(hidden_size)
+
+ def forward(self, pixel_values):
+ embeddings = self.proj(pixel_values)
+ _, _, height, width = embeddings.shape
+ embeddings = embeddings.flatten(2).transpose(1, 2)
+ embeddings = self.layer_norm(embeddings)
+ return embeddings, height, width
+
+
+class SegformerSequenceReduction(nn.Module):
+ """Spatially reduces key/value tokens via a strided convolution.
+
+ Projects the sequence from (B, H*W, C) → (B, H'*W', C) where H' = H / sr_ratio.
+ This reduces the O(N²) attention cost of the original sequence.
+ """
+
+ def __init__(self, hidden_size: int, sequence_reduction_ratio: int):
+ super().__init__()
+ self.sequence_reduction = nn.Conv2d(
+ hidden_size, hidden_size, kernel_size=sequence_reduction_ratio, stride=sequence_reduction_ratio
+ )
+ self.layer_norm = nn.LayerNorm(hidden_size)
+
+ def forward(self, hidden_states: torch.Tensor, height: int, width: int) -> torch.Tensor:
+ batch_size, seq_len, num_channels = hidden_states.shape
+ # (B, N, C) → (B, C, H, W) → strided conv → (B, C, H', W') → (B, H'W', C)
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, num_channels, height, width)
+ hidden_states = self.sequence_reduction(hidden_states)
+ hidden_states = hidden_states.reshape(batch_size, num_channels, -1).transpose(1, 2)
+ hidden_states = self.layer_norm(hidden_states)
+ return hidden_states
+
+
+class SegformerAttention(ViTAttention):
+ """Efficient self-attention where keys/values are spatially reduced via strided convolution.
+
+ Introduced in [PvT](https://huggingface.co/papers/2102.12122): queries attend to the full
+ sequence while key/value tokens are downsampled, reducing the O(N²) attention cost.
+ """
+
+ def __init__(self, config, hidden_size, num_attention_heads, sequence_reduction_ratio):
+ super().__init__(config)
+ # Override with per-stage dimensions: each Segformer stage has varying hidden sizes
+ self.num_attention_heads = num_attention_heads
+ self.head_dim = hidden_size // num_attention_heads
+ # No qkv_bias in Segformer (unlike ViT)
+ self.q_proj = nn.Linear(hidden_size, num_attention_heads * self.head_dim)
+ self.k_proj = nn.Linear(hidden_size, num_attention_heads * self.head_dim)
+ self.v_proj = nn.Linear(hidden_size, num_attention_heads * self.head_dim)
+ self.o_proj = nn.Linear(num_attention_heads * self.head_dim, hidden_size)
+ self.sequence_reduction_ratio = sequence_reduction_ratio
+ if sequence_reduction_ratio > 1:
+ self.sequence_reduction = SegformerSequenceReduction(hidden_size, sequence_reduction_ratio)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ height: int,
+ width: int,
+ attention_mask: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor, torch.Tensor]:
+ input_shape = hidden_states.shape[:-1]
+ hidden_shape = (*input_shape, -1, self.head_dim)
+
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+
+ kv_hidden_states = hidden_states
+ if self.sequence_reduction_ratio > 1:
+ kv_hidden_states = self.sequence_reduction(hidden_states, height, width)
+
+ kv_hidden_shape = (*kv_hidden_states.shape[:-1], -1, self.head_dim)
+ key_states = self.k_proj(kv_hidden_states).view(kv_hidden_shape).transpose(1, 2)
+ value_states = self.v_proj(kv_hidden_states).view(kv_hidden_shape).transpose(1, 2)
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_states,
+ key_states,
+ value_states,
+ attention_mask,
+ dropout=0.0 if not self.training else self.attention_dropout,
+ scaling=self.scaling,
+ **kwargs,
+ )
+
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ attn_output = self.o_proj(attn_output)
+
+ return attn_output, attn_weights
+
+
+class SegformerDepthWiseConv(nn.Module):
+ """Depthwise convolution used in the Mix-FFN to implicitly encode positional information."""
+
+ def __init__(self, dim=768):
+ super().__init__()
+ self.dwconv = nn.Conv2d(dim, dim, 3, 1, 1, groups=dim)
+
+ def forward(self, hidden_states, height, width):
+ batch_size, seq_len, num_channels = hidden_states.shape
+ hidden_states = hidden_states.transpose(1, 2).view(batch_size, num_channels, height, width)
+ hidden_states = self.dwconv(hidden_states)
+ hidden_states = hidden_states.flatten(2).transpose(1, 2)
+ return hidden_states
+
+
+class SegformerMixMLP(nn.Module):
+ """Mix-FFN: fc1 → DWConv → activation → fc2.
+
+ The depthwise convolution implicitly encodes positional information, replacing the explicit
+ position embedding used in standard ViT/BeiT MLPs.
+ """
+
+ def __init__(self, config, in_features, hidden_features=None, out_features=None):
+ super().__init__()
+ out_features = out_features or in_features
+ self.fc1 = nn.Linear(in_features, hidden_features)
+ self.dwconv = SegformerDepthWiseConv(hidden_features)
+ self.activation_fn = ACT2FN[config.hidden_act] if isinstance(config.hidden_act, str) else config.hidden_act
+ self.fc2 = nn.Linear(hidden_features, out_features)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(self, hidden_states, height, width):
+ hidden_states = self.fc1(hidden_states)
+ hidden_states = self.dwconv(hidden_states, height, width)
+ hidden_states = self.activation_fn(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = self.fc2(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ return hidden_states
+
+
+class SegformerDropPath(SwinDropPath):
+ pass
+
+
+class SegformerLayer(GradientCheckpointingLayer):
+ """Transformer block with DropPath on both branches and a MixFFN instead of a plain MLP."""
+
+ def __init__(self, config, hidden_size, num_attention_heads, drop_path, sequence_reduction_ratio, mlp_ratio):
+ super().__init__()
+ self.layernorm_before = nn.LayerNorm(hidden_size)
+ self.attention = SegformerAttention(
+ config,
+ hidden_size=hidden_size,
+ num_attention_heads=num_attention_heads,
+ sequence_reduction_ratio=sequence_reduction_ratio,
+ )
+ self.drop_path = SegformerDropPath(drop_path) if drop_path > 0.0 else nn.Identity()
+ self.layernorm_after = nn.LayerNorm(hidden_size)
+ self.mlp = SegformerMixMLP(config, in_features=hidden_size, hidden_features=int(hidden_size * mlp_ratio))
+ self.hidden_dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ height: int,
+ width: int,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.Tensor:
+ residual = hidden_states
+ hidden_states = self.layernorm_before(hidden_states)
+ hidden_states, _ = self.attention(hidden_states, height, width, **kwargs)
+ hidden_states = self.hidden_dropout(hidden_states)
+ hidden_states = self.drop_path(hidden_states) + residual
+
+ residual = hidden_states
+ hidden_states = self.layernorm_after(hidden_states)
+ hidden_states = self.mlp(hidden_states, height, width)
+ hidden_states = self.drop_path(hidden_states) + residual
+
+ return hidden_states
+
+
+class SegformerStage(nn.Module):
+ """One encoder stage: OverlapPatchEmbeddings → SegformerLayer blocks → LayerNorm."""
+
+ def __init__(self, config, stage_idx: int, drop_path_decays: list[float]):
+ super().__init__()
+ depth_start = sum(config.depths[:stage_idx])
+ # All stages reshape to (B, C, H, W); only the last stage skips it when reshape_last_stage=False.
+ self.reshape = stage_idx < config.num_encoder_blocks - 1 or config.reshape_last_stage
+ self.patch_embeddings = SegformerOverlapPatchEmbeddings(
+ patch_size=config.patch_sizes[stage_idx],
+ stride=config.strides[stage_idx],
+ num_channels=config.num_channels if stage_idx == 0 else config.hidden_sizes[stage_idx - 1],
+ hidden_size=config.hidden_sizes[stage_idx],
+ )
+ self.blocks = nn.ModuleList(
+ [
+ SegformerLayer(
+ config,
+ hidden_size=config.hidden_sizes[stage_idx],
+ num_attention_heads=config.num_attention_heads[stage_idx],
+ drop_path=drop_path_decays[depth_start + layer_idx],
+ sequence_reduction_ratio=config.sr_ratios[stage_idx],
+ mlp_ratio=config.mlp_ratios[stage_idx],
+ )
+ for layer_idx in range(config.depths[stage_idx])
+ ]
+ )
+ self.layer_norm = nn.LayerNorm(config.hidden_sizes[stage_idx])
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.Tensor:
+ hidden_states, height, width = self.patch_embeddings(hidden_states)
+ for block in self.blocks:
+ hidden_states = block(hidden_states, height, width, **kwargs)
+ hidden_states = self.layer_norm(hidden_states)
+ if self.reshape:
+ batch_size = hidden_states.shape[0]
+ hidden_states = hidden_states.reshape(batch_size, height, width, -1).permute(0, 3, 1, 2).contiguous()
+
+ return hidden_states
+
+
+@auto_docstring
+class SegformerPreTrainedModel(ViTPreTrainedModel):
+ _no_split_modules = ["SegformerStage"]
+ _can_record_outputs = {
+ # capture_initial_hidden_state=False: stage 0's input is raw pixel values, not a meaningful embedding.
+ "hidden_states": OutputRecorder(SegformerStage, capture_initial_hidden_state=False),
+ "attentions": SegformerAttention,
+ }
+
+ def _init_weights(self, module):
+ raise NotImplementedError("No need to override this method")
+
+
+@auto_docstring
+class SegformerModel(SegformerPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.config = config
+
+ drop_path_decays = [
+ config.drop_path_rate * i / max(sum(config.depths) - 1, 1) for i in range(sum(config.depths))
+ ]
+ self.stages = nn.ModuleList(
+ [SegformerStage(config, stage_idx, drop_path_decays) for stage_idx in range(config.num_encoder_blocks)]
+ )
+
+ self.post_init()
+
+ @merge_with_config_defaults
+ @capture_outputs
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: torch.FloatTensor,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> BaseModelOutput:
+ hidden_states = pixel_values
+ for stage in self.stages:
+ hidden_states = stage(hidden_states, **kwargs)
+ return BaseModelOutput(last_hidden_state=hidden_states)
+
+
+@auto_docstring(
+ custom_intro="""
+ SegFormer Model transformer with an image classification head on top (a linear layer on top of the final hidden
+ states) e.g. for ImageNet.
+ """
+)
+class SegformerForImageClassification(SegformerPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.num_labels = config.num_labels
+ self.segformer = SegformerModel(config)
+
+ # Classifier head
+ self.classifier = nn.Linear(config.hidden_sizes[-1], config.num_labels)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> SegFormerImageClassifierOutput:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+ outputs = self.segformer(pixel_values, **kwargs)
+
+ sequence_output = outputs.last_hidden_state
+
+ # convert last hidden states to (batch_size, height*width, hidden_size)
+ batch_size = sequence_output.shape[0]
+ if self.config.reshape_last_stage:
+ # (batch_size, num_channels, height, width) -> (batch_size, height, width, num_channels)
+ sequence_output = sequence_output.permute(0, 2, 3, 1)
+ sequence_output = sequence_output.reshape(batch_size, -1, self.config.hidden_sizes[-1])
+
+ # global average pooling
+ sequence_output = sequence_output.mean(dim=1)
+
+ logits = self.classifier(sequence_output)
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(labels, logits, self.config, **kwargs)
+
+ return SegFormerImageClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+class SegformerMLP(nn.Module):
+ """Projects each encoder stage's feature map to a common `decoder_hidden_size`."""
+
+ def __init__(self, config: SegformerConfig, input_dim):
+ super().__init__()
+ self.proj = nn.Linear(input_dim, config.decoder_hidden_size)
+
+ def forward(self, hidden_states: torch.Tensor):
+ hidden_states = hidden_states.flatten(2).transpose(1, 2)
+ hidden_states = self.proj(hidden_states)
+ return hidden_states
+
+
+class SegformerDecodeHead(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ # linear layers which will unify the channel dimension of each of the encoder blocks to the same config.decoder_hidden_size
+ linear_projections = []
+ for stage_idx in range(config.num_encoder_blocks):
+ linear_projections.append(SegformerMLP(config, input_dim=config.hidden_sizes[stage_idx]))
+ self.linear_projections = nn.ModuleList(linear_projections)
+
+ # the following 3 layers implement the ConvModule of the original implementation
+ self.linear_fuse = nn.Conv2d(
+ in_channels=config.decoder_hidden_size * config.num_encoder_blocks,
+ out_channels=config.decoder_hidden_size,
+ kernel_size=1,
+ bias=False,
+ )
+ self.batch_norm = nn.BatchNorm2d(config.decoder_hidden_size)
+ self.activation = nn.ReLU()
+
+ self.dropout = nn.Dropout(config.classifier_dropout_prob)
+ self.classifier = nn.Conv2d(config.decoder_hidden_size, config.num_labels, kernel_size=1)
+
+ self.config = config
+
+ def forward(self, encoder_hidden_states: torch.FloatTensor, **kwargs) -> torch.Tensor:
+ batch_size = encoder_hidden_states[-1].shape[0]
+
+ all_hidden_states = ()
+ for encoder_hidden_state, linear_proj in zip(encoder_hidden_states, self.linear_projections):
+ if self.config.reshape_last_stage is False and encoder_hidden_state.ndim == 3:
+ height = width = int(math.sqrt(encoder_hidden_state.shape[-1]))
+ encoder_hidden_state = (
+ encoder_hidden_state.reshape(batch_size, height, width, -1).permute(0, 3, 1, 2).contiguous()
+ )
+
+ # unify channel dimension
+ height, width = encoder_hidden_state.shape[2], encoder_hidden_state.shape[3]
+ encoder_hidden_state = linear_proj(encoder_hidden_state)
+ encoder_hidden_state = encoder_hidden_state.transpose(1, 2)
+ encoder_hidden_state = encoder_hidden_state.reshape(batch_size, -1, height, width)
+ # upsample
+ encoder_hidden_state = nn.functional.interpolate(
+ encoder_hidden_state, size=encoder_hidden_states[0].size()[2:], mode="bilinear", align_corners=False
+ )
+ all_hidden_states += (encoder_hidden_state,)
+
+ hidden_states = self.linear_fuse(torch.cat(all_hidden_states[::-1], dim=1))
+ hidden_states = self.batch_norm(hidden_states)
+ hidden_states = self.activation(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+
+ # logits are of shape (batch_size, num_labels, height/4, width/4)
+ logits = self.classifier(hidden_states)
+
+ return logits
+
+
+@auto_docstring(
+ custom_intro="""
+ SegFormer Model transformer with an all-MLP decode head on top e.g. for ADE20k, CityScapes.
+ """
+)
+class SegformerForSemanticSegmentation(SegformerPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.segformer = SegformerModel(config)
+ self.decode_head = SegformerDecodeHead(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @filter_output_hidden_states
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: torch.FloatTensor,
+ labels: torch.LongTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> SemanticSegmenterOutput:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, height, width)`, *optional*):
+ Ground truth semantic segmentation maps for computing the loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels > 1`, a classification loss is computed (Cross-Entropy).
+
+ Examples:
+
+ ```python
+ >>> from transformers import AutoImageProcessor, SegformerForSemanticSegmentation
+ >>> from PIL import Image
+ >>> import httpx
+ >>> from io import BytesIO
+
+ >>> image_processor = AutoImageProcessor.from_pretrained("nvidia/segformer-b0-finetuned-ade-512-512")
+ >>> model = SegformerForSemanticSegmentation.from_pretrained("nvidia/segformer-b0-finetuned-ade-512-512")
+
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
+ >>> with httpx.stream("GET", url) as response:
+ ... image = Image.open(BytesIO(response.read()))
+
+ >>> inputs = image_processor(images=image, return_tensors="pt")
+ >>> outputs = model(**inputs)
+ >>> logits = outputs.logits # shape (batch_size, num_labels, height/4, width/4)
+ >>> list(logits.shape)
+ [1, 150, 128, 128]
+ ```"""
+ if labels is not None and self.config.num_labels < 1:
+ raise ValueError(f"Number of labels should be >=0: {self.config.num_labels}")
+
+ # The decode head always needs all stage outputs, so force hidden_states on internally.
+ kwargs["output_hidden_states"] = True
+ outputs = self.segformer(pixel_values, **kwargs)
+
+ encoder_hidden_states = outputs.hidden_states
+
+ logits = self.decode_head(encoder_hidden_states)
+
+ loss = None
+ if labels is not None:
+ # upsample logits to the images' original size
+ upsampled_logits = nn.functional.interpolate(
+ logits, size=labels.shape[-2:], mode="bilinear", align_corners=False
+ )
+ if self.config.num_labels > 1:
+ loss_fct = CrossEntropyLoss(ignore_index=self.config.semantic_loss_ignore_index)
+ loss = loss_fct(upsampled_logits, labels)
+ elif self.config.num_labels == 1:
+ valid_mask = ((labels >= 0) & (labels != self.config.semantic_loss_ignore_index)).float()
+ loss_fct = BCEWithLogitsLoss(reduction="none")
+ loss = loss_fct(upsampled_logits.squeeze(1), labels.float())
+ loss = (loss * valid_mask).mean()
+
+ return SemanticSegmenterOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+__all__ = [
+ "SegformerImageProcessor",
+ "SegformerImageProcessorPil",
+ "SegformerDecodeHead",
+ "SegformerForImageClassification",
+ "SegformerForSemanticSegmentation",
+ "SegformerLayer",
+ "SegformerModel",
+ "SegformerPreTrainedModel",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/seggpt/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/seggpt/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ac1320313233bb511a4da800f8be5f2b72a95f72
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/seggpt/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/seggpt/__pycache__/configuration_seggpt.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/seggpt/__pycache__/configuration_seggpt.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0c7b6bc0bd14c1cd73b642040130d17700256c83
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/seggpt/__pycache__/configuration_seggpt.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/seggpt/__pycache__/image_processing_pil_seggpt.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/seggpt/__pycache__/image_processing_pil_seggpt.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..464f2ca8d040cb3b013433f0a619b4c17696991b
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/seggpt/__pycache__/image_processing_pil_seggpt.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/seggpt/__pycache__/image_processing_seggpt.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/seggpt/__pycache__/image_processing_seggpt.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5c1b968d5066e83cf64016b9e450fbc10388704f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/seggpt/__pycache__/image_processing_seggpt.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/seggpt/__pycache__/modeling_seggpt.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/seggpt/__pycache__/modeling_seggpt.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5bfed926399513382469816a9a5ed9ef1fb9f086
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/seggpt/__pycache__/modeling_seggpt.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/sew/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/sew/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..0bd614f74a68062d842548bdcba4a65ce19fd62c
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/sew/__init__.py
@@ -0,0 +1,27 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_sew import *
+ from .modeling_sew import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/sew/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/sew/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2b4c2d9e0bb8c602950c3b6aa749fc08bf8e54b7
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/sew/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/sew/__pycache__/configuration_sew.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/sew/__pycache__/configuration_sew.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e1e1581812383adebade54d849150268139a1a42
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/sew/__pycache__/configuration_sew.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/sew/__pycache__/modeling_sew.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/sew/__pycache__/modeling_sew.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..be8de29f46d3d14289b417dc5d251847380ab6fe
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/sew/__pycache__/modeling_sew.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/sew/__pycache__/modular_sew.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/sew/__pycache__/modular_sew.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9fe1bec98b9912f2d7f19b8f643b0e7219dd9235
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/sew/__pycache__/modular_sew.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/sew/configuration_sew.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/sew/configuration_sew.py
new file mode 100644
index 0000000000000000000000000000000000000000..acb7be58a454ae8c36d820dfac5118951e1fa7b0
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/sew/configuration_sew.py
@@ -0,0 +1,176 @@
+# Copyright 2021 ASAPP Inc. and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""SEW model configuration"""
+
+import functools
+import operator
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring
+
+
+@auto_docstring(checkpoint="BAAI/seggpt-vit-large")
+@strict
+class SEWConfig(PreTrainedConfig):
+ r"""
+ squeeze_factor (`int`, *optional*, defaults to 2):
+ Sequence length downsampling factor after the encoder and upsampling factor after the transformer.
+ feat_proj_dropout (`float`, *optional*, defaults to 0.0):
+ The dropout probability for output of the feature encoder.
+ final_dropout (`float`, *optional*, defaults to 0.1):
+ The dropout probability for the final projection layer of [`SEWForCTC`].
+ feat_extract_norm (`str`, *optional*, defaults to `"group"`):
+ The norm to be applied to 1D convolutional layers in feature encoder. One of `"group"` for group
+ normalization of only the first 1D convolutional layer or `"layer"` for layer normalization of all 1D
+ convolutional layers.
+ feat_extract_activation (`str, `optional`, defaults to `"gelu"`):
+ The non-linear activation function (function or string) in the 1D convolutional layers of the feature
+ extractor. If string, `"gelu"`, `"relu"`, `"selu"` and `"gelu_new"` are supported.
+ conv_dim (`tuple[int]` or `list[int]`, *optional*, defaults to `(64, 128, 128, 128, 128, 256, 256, 256, 256, 512, 512, 512, 512)`):
+ A tuple of integers defining the number of input and output channels of each 1D convolutional layer in the
+ feature encoder. The length of *conv_dim* defines the number of 1D convolutional layers.
+ conv_stride (`tuple[int]` or `list[int]`, *optional*, defaults to `(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1)`):
+ A tuple of integers defining the stride of each 1D convolutional layer in the feature encoder. The length
+ of *conv_stride* defines the number of convolutional layers and has to match the length of *conv_dim*.
+ conv_kernel (`tuple[int]` or `list[int]`, *optional*, defaults to `(10, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1)`):
+ A tuple of integers defining the kernel size of each 1D convolutional layer in the feature encoder. The
+ length of *conv_kernel* defines the number of convolutional layers and has to match the length of
+ *conv_dim*.
+ conv_bias (`bool`, *optional*, defaults to `False`):
+ Whether the 1D convolutional layers have a bias.
+ num_conv_pos_embeddings (`int`, *optional*, defaults to 128):
+ Number of convolutional positional embeddings. Defines the kernel size of 1D convolutional positional
+ embeddings layer.
+ num_conv_pos_embedding_groups (`int`, *optional*, defaults to 16):
+ Number of groups of 1D convolutional positional embeddings layer.
+ apply_spec_augment (`bool`, *optional*, defaults to `True`):
+ Whether to apply *SpecAugment* data augmentation to the outputs of the feature encoder. For reference see
+ [SpecAugment: A Simple Data Augmentation Method for Automatic Speech
+ Recognition](https://huggingface.co/papers/1904.08779).
+ mask_time_prob (`float`, *optional*, defaults to 0.05):
+ Percentage (between 0 and 1) of all feature vectors along the time axis which will be masked. The masking
+ procedure generates ''mask_time_prob*len(time_axis)/mask_time_length'' independent masks over the axis. If
+ reasoning from the probability of each feature vector to be chosen as the start of the vector span to be
+ masked, *mask_time_prob* should be `prob_vector_start*mask_time_length`. Note that overlap may decrease the
+ actual percentage of masked vectors. This is only relevant if `apply_spec_augment is True`.
+ mask_time_length (`int`, *optional*, defaults to 10):
+ Length of vector span along the time axis.
+ mask_time_min_masks (`int`, *optional*, defaults to 2),:
+ The minimum number of masks of length `mask_feature_length` generated along the time axis, each time step,
+ irrespectively of `mask_feature_prob`. Only relevant if ''mask_time_prob*len(time_axis)/mask_time_length <
+ mask_time_min_masks''
+ mask_feature_prob (`float`, *optional*, defaults to 0.0):
+ Percentage (between 0 and 1) of all feature vectors along the feature axis which will be masked. The
+ masking procedure generates ''mask_feature_prob*len(feature_axis)/mask_time_length'' independent masks over
+ the axis. If reasoning from the probability of each feature vector to be chosen as the start of the vector
+ span to be masked, *mask_feature_prob* should be `prob_vector_start*mask_feature_length`. Note that overlap
+ may decrease the actual percentage of masked vectors. This is only relevant if `apply_spec_augment is
+ True`.
+ mask_feature_length (`int`, *optional*, defaults to 10):
+ Length of vector span along the feature axis.
+ mask_feature_min_masks (`int`, *optional*, defaults to 0):
+ The minimum number of masks of length `mask_feature_length` generated along the feature axis, each time
+ step, irrespectively of `mask_feature_prob`. Only relevant if
+ ''mask_feature_prob*len(feature_axis)/mask_feature_length < mask_feature_min_masks''
+ ctc_zero_infinity (`bool`, *optional*, defaults to `False`):
+ Whether to zero infinite losses and the associated gradients of `torch.nn.CTCLoss`. Infinite losses mainly
+ occur when the inputs are too short to be aligned to the targets. Only relevant when training an instance
+ of [`SEWForCTC`].
+ use_weighted_layer_sum (`bool`, *optional*, defaults to `False`):
+ Whether to use a weighted average of layer outputs with learned weights. Only relevant when using an
+ instance of [`Wav2Vec2ForSequenceClassification`].
+ classifier_proj_size (`int`, *optional*, defaults to 256):
+ Dimensionality of the projection before token mean-pooling for classification.
+
+ Example:
+
+ ```python
+ >>> from transformers import SEWConfig, SEWModel
+
+ >>> # Initializing a SEW asapp/sew-tiny-100k style configuration
+ >>> configuration = SEWConfig()
+
+ >>> # Initializing a model (with random weights) from the asapp/sew-tiny-100k style configuration
+ >>> model = SEWModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "sew"
+
+ vocab_size: int = 32
+ hidden_size: int = 768
+ num_hidden_layers: int = 12
+ num_attention_heads: int = 12
+ intermediate_size: int = 3072
+ squeeze_factor: int = 2
+ hidden_act: str = "gelu"
+ hidden_dropout: float | int = 0.1
+ activation_dropout: float | int = 0.1
+ attention_dropout: float | int = 0.1
+ feat_proj_dropout: float | int = 0.0
+ final_dropout: float | int = 0.1
+ layerdrop: float | int = 0.1
+ initializer_range: float = 0.02
+ layer_norm_eps: float = 1e-5
+ feat_extract_norm: str = "group"
+ feat_extract_activation: str = "gelu"
+ conv_dim: list[int] | tuple[int, ...] = (64, 128, 128, 128, 128, 256, 256, 256, 256, 512, 512, 512, 512)
+ conv_stride: list[int] | tuple[int, ...] = (5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1)
+ conv_kernel: list[int] | tuple[int, ...] = (10, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1)
+ conv_bias: bool = False
+ num_conv_pos_embeddings: int = 128
+ num_conv_pos_embedding_groups: int = 16
+ apply_spec_augment: bool = True
+ mask_time_prob: float | int = 0.05
+ mask_time_length: int = 10
+ mask_time_min_masks: int = 2
+ mask_feature_prob: float | int = 0.0
+ mask_feature_length: int = 10
+ mask_feature_min_masks: int = 0
+ ctc_loss_reduction: str = "mean"
+ ctc_zero_infinity: bool = False
+ use_weighted_layer_sum: bool = False
+ classifier_proj_size: int = 256
+ pad_token_id: int | None = 0
+ bos_token_id: int | None = 1
+ eos_token_id: int | list[int] | None = 2
+
+ def __post_init__(self, **kwargs):
+ self.num_feat_extract_layers = len(self.conv_dim)
+ super().__post_init__(**kwargs)
+
+ def validate_architecture(self):
+ """Part of `@strict`-powered validation. Validates the architecture of the config."""
+ if (
+ (len(self.conv_stride) != self.num_feat_extract_layers)
+ or (len(self.conv_kernel) != self.num_feat_extract_layers)
+ or (len(self.conv_dim) != self.num_feat_extract_layers)
+ ):
+ raise ValueError(
+ "Configuration for convolutional layers is incorrect. "
+ "It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`, "
+ f"but is `len(config.conv_dim) = {len(self.conv_dim)}`, `len(config.conv_stride) "
+ f"= {len(self.conv_stride)}`, `len(config.conv_kernel) = {len(self.conv_kernel)}`."
+ )
+
+ @property
+ def inputs_to_logits_ratio(self):
+ return functools.reduce(operator.mul, self.conv_stride, 1)
+
+
+__all__ = ["SEWConfig"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/sew/modeling_sew.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/sew/modeling_sew.py
new file mode 100644
index 0000000000000000000000000000000000000000..ea499e63289aa5590d3e43eadb8e58f003bcdbb3
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/sew/modeling_sew.py
@@ -0,0 +1,1080 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/sew/modular_sew.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_sew.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2021 ASAPP Inc. and the HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import math
+from collections.abc import Callable
+
+import numpy as np
+import torch
+from torch import nn
+from torch.nn import CrossEntropyLoss
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...integrations.deepspeed import is_deepspeed_zero3_enabled
+from ...integrations.fsdp import is_fsdp_managed_module
+from ...modeling_flash_attention_utils import FlashAttentionKwargs
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import BaseModelOutput, CausalLMOutput, SequenceClassifierOutput
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel, get_torch_context_manager_or_global_device
+from ...processing_utils import Unpack
+from ...utils import TransformersKwargs, auto_docstring, logging
+from ...utils.generic import is_flash_attention_requested
+from .configuration_sew import SEWConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+class SEWNoLayerNormConvLayer(GradientCheckpointingLayer):
+ def __init__(self, config, layer_id=0):
+ super().__init__()
+ self.in_conv_dim = config.conv_dim[layer_id - 1] if layer_id > 0 else 1
+ self.out_conv_dim = config.conv_dim[layer_id]
+
+ self.conv = nn.Conv1d(
+ self.in_conv_dim,
+ self.out_conv_dim,
+ kernel_size=config.conv_kernel[layer_id],
+ stride=config.conv_stride[layer_id],
+ bias=config.conv_bias,
+ )
+ self.activation = ACT2FN[config.feat_extract_activation]
+
+ def forward(self, hidden_states):
+ hidden_states = self.conv(hidden_states)
+ hidden_states = self.activation(hidden_states)
+ return hidden_states
+
+
+class SEWLayerNormConvLayer(GradientCheckpointingLayer):
+ def __init__(self, config, layer_id=0):
+ super().__init__()
+ self.in_conv_dim = config.conv_dim[layer_id - 1] if layer_id > 0 else 1
+ self.out_conv_dim = config.conv_dim[layer_id]
+
+ self.conv = nn.Conv1d(
+ self.in_conv_dim,
+ self.out_conv_dim,
+ kernel_size=config.conv_kernel[layer_id],
+ stride=config.conv_stride[layer_id],
+ bias=config.conv_bias,
+ )
+ self.layer_norm = nn.LayerNorm(self.out_conv_dim, elementwise_affine=True)
+ self.activation = ACT2FN[config.feat_extract_activation]
+
+ def forward(self, hidden_states):
+ hidden_states = self.conv(hidden_states)
+
+ hidden_states = hidden_states.transpose(-2, -1)
+ hidden_states = self.layer_norm(hidden_states)
+ hidden_states = hidden_states.transpose(-2, -1)
+
+ hidden_states = self.activation(hidden_states)
+ return hidden_states
+
+
+class SEWGroupNormConvLayer(GradientCheckpointingLayer):
+ def __init__(self, config, layer_id=0):
+ super().__init__()
+ self.in_conv_dim = config.conv_dim[layer_id - 1] if layer_id > 0 else 1
+ self.out_conv_dim = config.conv_dim[layer_id]
+
+ self.conv = nn.Conv1d(
+ self.in_conv_dim,
+ self.out_conv_dim,
+ kernel_size=config.conv_kernel[layer_id],
+ stride=config.conv_stride[layer_id],
+ bias=config.conv_bias,
+ )
+ self.activation = ACT2FN[config.feat_extract_activation]
+
+ self.layer_norm = nn.GroupNorm(num_groups=self.out_conv_dim, num_channels=self.out_conv_dim, affine=True)
+
+ def forward(self, hidden_states):
+ hidden_states = self.conv(hidden_states)
+ hidden_states = self.layer_norm(hidden_states)
+ hidden_states = self.activation(hidden_states)
+ return hidden_states
+
+
+class SEWPositionalConvEmbedding(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.conv = nn.Conv1d(
+ config.hidden_size,
+ config.hidden_size,
+ kernel_size=config.num_conv_pos_embeddings,
+ padding=config.num_conv_pos_embeddings // 2,
+ groups=config.num_conv_pos_embedding_groups,
+ stride=config.squeeze_factor,
+ )
+
+ weight_norm = nn.utils.weight_norm
+ if hasattr(nn.utils.parametrizations, "weight_norm"):
+ weight_norm = nn.utils.parametrizations.weight_norm
+
+ if is_deepspeed_zero3_enabled():
+ import deepspeed
+
+ with deepspeed.zero.GatheredParameters(self.conv.weight, modifier_rank=0):
+ self.conv = weight_norm(self.conv, name="weight", dim=2)
+ if hasattr(self.conv, "parametrizations"):
+ weight_g = self.conv.parametrizations.weight.original0
+ weight_v = self.conv.parametrizations.weight.original1
+ else:
+ weight_g = self.conv.weight_g
+ weight_v = self.conv.weight_v
+ deepspeed.zero.register_external_parameter(self, weight_v)
+ deepspeed.zero.register_external_parameter(self, weight_g)
+ else:
+ self.conv = weight_norm(self.conv, name="weight", dim=2)
+
+ self.padding = SEWSamePadLayer(config.num_conv_pos_embeddings)
+ self.activation = ACT2FN[config.feat_extract_activation]
+
+ def forward(self, hidden_states):
+ hidden_states = self.conv(hidden_states)
+ hidden_states = self.padding(hidden_states)
+ hidden_states = self.activation(hidden_states)
+
+ return hidden_states
+
+
+class SEWSamePadLayer(nn.Module):
+ def __init__(self, num_conv_pos_embeddings):
+ super().__init__()
+ self.num_pad_remove = 1 if num_conv_pos_embeddings % 2 == 0 else 0
+
+ def forward(self, hidden_states):
+ if self.num_pad_remove > 0:
+ hidden_states = hidden_states[:, :, : -self.num_pad_remove]
+ return hidden_states
+
+
+class SEWUpsampling(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.projection = nn.Linear(config.hidden_size, config.hidden_size * config.squeeze_factor)
+ self.activation = ACT2FN[config.feat_extract_activation]
+ self.squeeze_factor = config.squeeze_factor
+
+ def forward(self, hidden_states):
+ hidden_states = self.projection(hidden_states)
+ hidden_states = self.activation(hidden_states)
+
+ if self.squeeze_factor > 1:
+ # transform embedding channels to sequence length
+ bsz, src_len, src_embed_dim = hidden_states.size()
+ tgt_len = src_len * self.squeeze_factor
+ tgt_embed_dim = src_embed_dim // self.squeeze_factor
+ hidden_states = hidden_states.reshape(bsz, src_len, self.squeeze_factor, tgt_embed_dim)
+ hidden_states = hidden_states.reshape(bsz, tgt_len, tgt_embed_dim)
+
+ return hidden_states
+
+
+class SEWFeatureEncoder(nn.Module):
+ """Construct the features from raw audio waveform"""
+
+ def __init__(self, config):
+ super().__init__()
+
+ if config.feat_extract_norm == "group":
+ conv_layers = [SEWGroupNormConvLayer(config, layer_id=0)] + [
+ SEWNoLayerNormConvLayer(config, layer_id=i + 1) for i in range(config.num_feat_extract_layers - 1)
+ ]
+ elif config.feat_extract_norm == "layer":
+ conv_layers = [SEWLayerNormConvLayer(config, layer_id=i) for i in range(config.num_feat_extract_layers)]
+ else:
+ raise ValueError(
+ f"`config.feat_extract_norm` is {config.feat_extract_norm}, but has to be one of ['group', 'layer']"
+ )
+ self.conv_layers = nn.ModuleList(conv_layers)
+ self.gradient_checkpointing = False
+ self._requires_grad = True
+
+ def _freeze_parameters(self):
+ for param in self.parameters():
+ param.requires_grad = False
+ self._requires_grad = False
+
+ def forward(self, input_values):
+ hidden_states = input_values[:, None]
+
+ # make sure hidden_states require grad for gradient_checkpointing
+ if self._requires_grad and self.training:
+ hidden_states.requires_grad = True
+
+ for conv_layer in self.conv_layers:
+ hidden_states = conv_layer(hidden_states)
+
+ return hidden_states
+
+
+def eager_attention_forward(
+ module: nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: torch.Tensor | None,
+ scaling: float | None = None,
+ dropout: float = 0.0,
+ **kwargs: Unpack[TransformersKwargs],
+):
+ if scaling is None:
+ scaling = query.size(-1) ** -0.5
+
+ # Take the dot product between "query" and "key" to get the raw attention scores.
+ attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
+
+ if attention_mask is not None:
+ attn_weights = attn_weights + attention_mask
+
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
+
+ attn_output = torch.matmul(attn_weights, value)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+
+ return attn_output, attn_weights
+
+
+class SEWAttention(nn.Module):
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
+
+ def __init__(
+ self,
+ embed_dim: int,
+ num_heads: int,
+ dropout: float = 0.0,
+ is_decoder: bool = False,
+ bias: bool = True,
+ is_causal: bool = False,
+ config: SEWConfig | None = None,
+ ):
+ super().__init__()
+ self.embed_dim = embed_dim
+ self.num_heads = num_heads
+ self.dropout = dropout
+ self.head_dim = embed_dim // num_heads
+ self.config = config
+
+ if (self.head_dim * num_heads) != self.embed_dim:
+ raise ValueError(
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
+ f" and `num_heads`: {num_heads})."
+ )
+ self.scaling = self.head_dim**-0.5
+ self.is_decoder = is_decoder
+ self.is_causal = is_causal
+
+ self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
+ self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ key_value_states: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ output_attentions: bool | None = False,
+ # TODO: we need a refactor so that the different attention modules can get their specific kwargs
+ # ATM, we have mixed things encoder, decoder, and encoder-decoder attn
+ **kwargs: Unpack[FlashAttentionKwargs],
+ ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
+ """Input shape: Batch x Time x Channel"""
+
+ # if key_value_states are provided this layer is used as a cross-attention layer
+ # for the decoder
+ is_cross_attention = key_value_states is not None
+
+ # determine input shapes
+ input_shape = hidden_states.shape[:-1]
+
+ hidden_shape = (*input_shape, -1, self.head_dim)
+
+ # get query proj
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+
+ current_states = key_value_states if is_cross_attention else hidden_states
+ kv_shape = (*current_states.shape[:-1], -1, self.head_dim)
+ key_states = self.k_proj(current_states).view(kv_shape).transpose(1, 2)
+ value_states = self.v_proj(current_states).view(kv_shape).transpose(1, 2)
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_states,
+ key_states,
+ value_states,
+ attention_mask,
+ dropout=0.0 if not self.training else self.dropout,
+ scaling=self.scaling,
+ output_attentions=output_attentions,
+ **kwargs,
+ )
+
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ attn_output = self.out_proj(attn_output)
+
+ return attn_output, attn_weights, None
+
+
+class SEWFeedForward(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.intermediate_dropout = nn.Dropout(config.activation_dropout)
+
+ self.intermediate_dense = nn.Linear(config.hidden_size, config.intermediate_size)
+ if isinstance(config.hidden_act, str):
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
+ else:
+ self.intermediate_act_fn = config.hidden_act
+
+ self.output_dense = nn.Linear(config.intermediate_size, config.hidden_size)
+ self.output_dropout = nn.Dropout(config.hidden_dropout)
+
+ def forward(self, hidden_states):
+ hidden_states = self.intermediate_dense(hidden_states)
+ hidden_states = self.intermediate_act_fn(hidden_states)
+ hidden_states = self.intermediate_dropout(hidden_states)
+
+ hidden_states = self.output_dense(hidden_states)
+ hidden_states = self.output_dropout(hidden_states)
+ return hidden_states
+
+
+class SEWEncoderLayer(GradientCheckpointingLayer):
+ def __init__(self, config):
+ super().__init__()
+ self.attention = SEWAttention(
+ embed_dim=config.hidden_size,
+ num_heads=config.num_attention_heads,
+ dropout=config.attention_dropout,
+ is_decoder=False,
+ config=config,
+ )
+
+ self.dropout = nn.Dropout(config.hidden_dropout)
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.feed_forward = SEWFeedForward(config)
+ self.final_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+
+ def forward(self, hidden_states, attention_mask=None, output_attentions=False):
+ attn_residual = hidden_states
+ hidden_states, attn_weights, _ = self.attention(
+ hidden_states, attention_mask=attention_mask, output_attentions=output_attentions
+ )
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = attn_residual + hidden_states
+
+ hidden_states = self.layer_norm(hidden_states)
+ hidden_states = hidden_states + self.feed_forward(hidden_states)
+ hidden_states = self.final_layer_norm(hidden_states)
+
+ outputs = (hidden_states,)
+
+ if output_attentions:
+ outputs += (attn_weights,)
+
+ return outputs
+
+
+class SEWEncoder(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.pos_conv_embed = SEWPositionalConvEmbedding(config)
+ self.pool = nn.AvgPool1d(config.squeeze_factor, config.squeeze_factor)
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout)
+ self.layers = nn.ModuleList([SEWEncoderLayer(config) for _ in range(config.num_hidden_layers)])
+ self.upsample = SEWUpsampling(config)
+ self.gradient_checkpointing = False
+
+ def forward(
+ self,
+ hidden_states,
+ attention_mask=None,
+ output_attentions=False,
+ output_hidden_states=False,
+ return_dict=True,
+ ):
+ all_hidden_states = () if output_hidden_states else None
+ all_self_attentions = () if output_attentions else None
+
+ if attention_mask is not None:
+ expand_attention_mask = attention_mask.unsqueeze(-1).repeat(1, 1, hidden_states.shape[2])
+ if is_flash_attention_requested(self.config):
+ # make sure padded tokens output 0
+ hidden_states[~expand_attention_mask] = 0.0
+ # 2d mask is passed through the layers
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
+ else:
+ # make sure padded tokens output 0
+ hidden_states[~expand_attention_mask] = 0.0
+ input_lengths = (attention_mask.long()).sum(-1)
+ # apply pooling formula to get real output_lengths
+ output_lengths = input_lengths // self.config.squeeze_factor
+ max_encoder_length = hidden_states.shape[1] // self.config.squeeze_factor
+ attention_ids = (
+ torch.arange(0, max_encoder_length, device=output_lengths.device)
+ .view(1, -1)
+ .expand(output_lengths.shape[0], -1)
+ )
+ attention_mask = (attention_ids < output_lengths.view(-1, 1)).long()
+
+ # extend attention_mask
+ attention_mask = 1.0 - attention_mask[:, None, None, :].to(dtype=hidden_states.dtype)
+ attention_mask = attention_mask * torch.finfo(hidden_states.dtype).min
+ attention_mask = attention_mask.expand(
+ attention_mask.shape[0], 1, attention_mask.shape[-1], attention_mask.shape[-1]
+ )
+
+ n_input_timesteps = hidden_states.shape[1]
+
+ hidden_states = hidden_states.transpose(1, 2)
+ position_embeddings = self.pos_conv_embed(hidden_states)
+ pooled_hidden_states = self.pool(hidden_states)
+ min_length = min(position_embeddings.size(-1), pooled_hidden_states.size(-1))
+ hidden_states = pooled_hidden_states[..., :min_length] + position_embeddings[..., :min_length]
+ hidden_states = hidden_states.transpose(1, 2)
+
+ hidden_states = self.layer_norm(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+
+ synced_gpus = is_deepspeed_zero3_enabled() or is_fsdp_managed_module(self)
+
+ for layer in self.layers:
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ # add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
+ dropout_probability = torch.rand([])
+
+ skip_the_layer = self.training and dropout_probability < self.config.layerdrop
+ if not skip_the_layer or synced_gpus:
+ # under fsdp or deepspeed zero3 all gpus must run in sync
+ layer_outputs = layer(
+ hidden_states, attention_mask=attention_mask, output_attentions=output_attentions
+ )
+ hidden_states = layer_outputs[0]
+
+ if skip_the_layer:
+ layer_outputs = (None, None)
+
+ if output_attentions:
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
+
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ hidden_states = self.upsample(hidden_states)
+ if hidden_states.shape[1] < n_input_timesteps:
+ hidden_states = nn.functional.pad(hidden_states, (0, 0, 0, n_input_timesteps - hidden_states.shape[1]))
+
+ if not return_dict:
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
+ return BaseModelOutput(
+ last_hidden_state=hidden_states,
+ hidden_states=all_hidden_states,
+ attentions=all_self_attentions,
+ )
+
+
+@auto_docstring
+class SEWPreTrainedModel(PreTrainedModel):
+ config: SEWConfig
+ base_model_prefix = "sew"
+ main_input_name = "input_values"
+ input_modalities = "audio"
+ supports_gradient_checkpointing = True
+ _supports_flash_attn = True
+ _supports_sdpa = True
+ _supports_flex_attn = False # needs a proper look into the mask creation
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ """Initialize the weights"""
+ if isinstance(module, SEWPositionalConvEmbedding):
+ init.normal_(
+ module.conv.weight,
+ mean=0,
+ std=2 * math.sqrt(1 / (module.conv.kernel_size[0] * module.conv.in_channels)),
+ )
+ init.constant_(module.conv.bias, 0)
+ elif isinstance(module, nn.Linear):
+ init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
+ elif isinstance(module, (nn.LayerNorm, nn.GroupNorm)):
+ init.zeros_(module.bias)
+ init.ones_(module.weight)
+ elif isinstance(module, nn.Conv1d):
+ if is_deepspeed_zero3_enabled():
+ import deepspeed
+
+ if hasattr(module, "weight_v") and hasattr(module, "weight_g"):
+ with deepspeed.zero.GatheredParameters([module.weight_v, module.weight_g], modifier_rank=0):
+ init.kaiming_normal_(module.weight)
+ else:
+ with deepspeed.zero.GatheredParameters(module.weight, modifier_rank=0):
+ init.kaiming_normal_(module.weight)
+ else:
+ init.kaiming_normal_(module.weight)
+
+ if isinstance(module, (nn.Linear, nn.Conv1d)) and module.bias is not None:
+ init.zeros_(module.bias)
+
+ def _get_feat_extract_output_lengths(self, input_lengths: torch.LongTensor | int):
+ """
+ Computes the output length of the convolutional layers
+ """
+
+ def _conv_out_length(input_length, kernel_size, stride):
+ # 1D convolutional layer output length formula taken
+ # from https://pytorch.org/docs/stable/generated/torch.nn.Conv1d.html
+ return torch.div(input_length - kernel_size, stride, rounding_mode="floor") + 1
+
+ for kernel_size, stride in zip(self.config.conv_kernel, self.config.conv_stride):
+ input_lengths = _conv_out_length(input_lengths, kernel_size, stride)
+
+ return input_lengths
+
+ def _get_feature_vector_attention_mask(self, feature_vector_length: int, attention_mask: torch.LongTensor):
+ output_lengths = self._get_feat_extract_output_lengths(attention_mask.sum(-1)).to(torch.long)
+ batch_size = attention_mask.shape[0]
+
+ attention_mask = torch.zeros(
+ (batch_size, feature_vector_length), dtype=attention_mask.dtype, device=attention_mask.device
+ )
+ # these two operations makes sure that all values before the output lengths idxs are attended to
+ attention_mask[(torch.arange(attention_mask.shape[0], device=attention_mask.device), output_lengths - 1)] = 1
+ attention_mask = attention_mask.flip([-1]).cumsum(-1).flip([-1]).bool()
+ return attention_mask
+
+
+def _compute_mask_indices(
+ shape: tuple[int, int],
+ mask_prob: float,
+ mask_length: int,
+ attention_mask: torch.LongTensor | None = None,
+ min_masks: int = 0,
+) -> np.ndarray:
+ """
+ Computes random mask spans for a given shape. Used to implement [SpecAugment: A Simple Data Augmentation Method for
+ ASR](https://huggingface.co/papers/1904.08779). Note that this method is not optimized to run on TPU and should be run on
+ CPU as part of the preprocessing during training.
+
+ Args:
+ shape: The shape for which to compute masks. This should be of a tuple of size 2 where
+ the first element is the batch size and the second element is the length of the axis to span.
+ mask_prob: The percentage of the whole axis (between 0 and 1) which will be masked. The number of
+ independently generated mask spans of length `mask_length` is computed by
+ `mask_prob*shape[1]/mask_length`. Note that due to overlaps, `mask_prob` is an upper bound and the
+ actual percentage will be smaller.
+ mask_length: size of the mask
+ min_masks: minimum number of masked spans
+ attention_mask: A (right-padded) attention mask which independently shortens the feature axis of
+ each batch dimension.
+ """
+ batch_size, sequence_length = shape
+
+ if mask_length < 1:
+ raise ValueError("`mask_length` has to be bigger than 0.")
+
+ if mask_length > sequence_length:
+ raise ValueError(
+ f"`mask_length` has to be smaller than `sequence_length`, but got `mask_length`: {mask_length}"
+ f" and `sequence_length`: {sequence_length}`"
+ )
+
+ # epsilon is used for probabilistic rounding
+ epsilon = np.random.rand(1).item()
+
+ def compute_num_masked_span(input_length):
+ """Given input length, compute how many spans should be masked"""
+ num_masked_span = int(mask_prob * input_length / mask_length + epsilon)
+ num_masked_span = max(num_masked_span, min_masks)
+
+ # make sure num masked span <= sequence_length
+ if num_masked_span * mask_length > sequence_length:
+ num_masked_span = sequence_length // mask_length
+
+ # make sure num_masked span is also <= input_length - (mask_length - 1)
+ if input_length - (mask_length - 1) < num_masked_span:
+ num_masked_span = max(input_length - (mask_length - 1), 0)
+
+ return num_masked_span
+
+ # compute number of masked spans in batch
+ input_lengths = (
+ attention_mask.detach().sum(-1).tolist()
+ if attention_mask is not None
+ else [sequence_length for _ in range(batch_size)]
+ )
+
+ # SpecAugment mask to fill
+ spec_aug_mask = np.zeros((batch_size, sequence_length), dtype=bool)
+ spec_aug_mask_idxs = []
+
+ max_num_masked_span = compute_num_masked_span(sequence_length)
+
+ if max_num_masked_span == 0:
+ return spec_aug_mask
+
+ for input_length in input_lengths:
+ # compute num of masked spans for this input
+ num_masked_span = compute_num_masked_span(input_length)
+
+ # get random indices to mask
+ spec_aug_mask_idx = np.random.choice(
+ np.arange(input_length - (mask_length - 1)), num_masked_span, replace=False
+ )
+
+ # pick first sampled index that will serve as a dummy index to pad vector
+ # to ensure same dimension for all batches due to probabilistic rounding
+ # Picking first sample just pads those vectors twice.
+ if len(spec_aug_mask_idx) == 0:
+ # this case can only happen if `input_length` is strictly smaller then
+ # `sequence_length` in which case the last token has to be a padding
+ # token which we can use as a dummy mask id
+ dummy_mask_idx = sequence_length - 1
+ else:
+ dummy_mask_idx = spec_aug_mask_idx[0]
+
+ spec_aug_mask_idx = np.concatenate(
+ [spec_aug_mask_idx, np.ones(max_num_masked_span - num_masked_span, dtype=np.int32) * dummy_mask_idx]
+ )
+ spec_aug_mask_idxs.append(spec_aug_mask_idx)
+
+ spec_aug_mask_idxs = np.array(spec_aug_mask_idxs)
+
+ # expand masked indices to masked spans
+ spec_aug_mask_idxs = np.broadcast_to(
+ spec_aug_mask_idxs[:, :, None], (batch_size, max_num_masked_span, mask_length)
+ )
+ spec_aug_mask_idxs = spec_aug_mask_idxs.reshape(batch_size, max_num_masked_span * mask_length)
+
+ # add offset to the starting indexes so that indexes now create a span
+ offsets = np.arange(mask_length)[None, None, :]
+ offsets = np.broadcast_to(offsets, (batch_size, max_num_masked_span, mask_length)).reshape(
+ batch_size, max_num_masked_span * mask_length
+ )
+ spec_aug_mask_idxs = spec_aug_mask_idxs + offsets
+
+ # ensure that we cannot have indices larger than sequence_length
+ if spec_aug_mask_idxs.max() > sequence_length - 1:
+ spec_aug_mask_idxs[spec_aug_mask_idxs > sequence_length - 1] = sequence_length - 1
+
+ # scatter indices to mask
+ np.put_along_axis(spec_aug_mask, spec_aug_mask_idxs, 1, -1)
+
+ return spec_aug_mask
+
+
+@auto_docstring
+class SEWModel(SEWPreTrainedModel):
+ def __init__(self, config: SEWConfig):
+ super().__init__(config)
+ self.config = config
+ self.feature_extractor = SEWFeatureEncoder(config)
+ self.layer_norm = nn.LayerNorm(config.conv_dim[-1], eps=config.layer_norm_eps)
+
+ self.project_features = config.conv_dim[-1] != config.hidden_size
+ if self.project_features:
+ self.feature_projection = nn.Linear(config.conv_dim[-1], config.hidden_size)
+ self.feature_dropout = nn.Dropout(config.feat_proj_dropout)
+
+ if config.mask_time_prob > 0.0 or config.mask_feature_prob > 0.0:
+ self.masked_spec_embed = nn.Parameter(torch.Tensor(config.hidden_size).uniform_())
+
+ self.encoder = SEWEncoder(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2Model._mask_hidden_states
+ def _mask_hidden_states(
+ self,
+ hidden_states: torch.FloatTensor,
+ mask_time_indices: torch.FloatTensor | None = None,
+ attention_mask: torch.LongTensor | None = None,
+ ):
+ """
+ Masks extracted features along time axis and/or along feature axis according to
+ [SpecAugment](https://huggingface.co/papers/1904.08779).
+ """
+
+ # `config.apply_spec_augment` can set masking to False
+ if not getattr(self.config, "apply_spec_augment", True):
+ return hidden_states
+
+ # generate indices & apply SpecAugment along time axis
+ batch_size, sequence_length, hidden_size = hidden_states.size()
+
+ if mask_time_indices is not None:
+ # apply SpecAugment along time axis with given mask_time_indices
+ hidden_states[mask_time_indices] = self.masked_spec_embed.to(hidden_states.dtype)
+ elif self.config.mask_time_prob > 0 and self.training:
+ mask_time_indices = _compute_mask_indices(
+ (batch_size, sequence_length),
+ mask_prob=self.config.mask_time_prob,
+ mask_length=self.config.mask_time_length,
+ attention_mask=attention_mask,
+ min_masks=self.config.mask_time_min_masks,
+ )
+ mask_time_indices = torch.tensor(mask_time_indices, device=hidden_states.device, dtype=torch.bool)
+ hidden_states[mask_time_indices] = self.masked_spec_embed.to(hidden_states.dtype)
+
+ if self.config.mask_feature_prob > 0 and self.training:
+ # generate indices & apply SpecAugment along feature axis
+ mask_feature_indices = _compute_mask_indices(
+ (batch_size, hidden_size),
+ mask_prob=self.config.mask_feature_prob,
+ mask_length=self.config.mask_feature_length,
+ min_masks=self.config.mask_feature_min_masks,
+ )
+ mask_feature_indices = torch.tensor(mask_feature_indices, device=hidden_states.device, dtype=torch.bool)
+ mask_feature_indices = mask_feature_indices[:, None].expand(-1, sequence_length, -1)
+ hidden_states[mask_feature_indices] = 0
+
+ return hidden_states
+
+ @auto_docstring
+ def forward(
+ self,
+ input_values: torch.Tensor | None,
+ attention_mask: torch.Tensor | None = None,
+ mask_time_indices: torch.FloatTensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple | BaseModelOutput:
+ r"""
+ mask_time_indices (`torch.BoolTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Indices to mask extracted features for contrastive loss. When in training mode, model learns to predict
+ masked extracted features in *config.proj_codevector_dim* space.
+ """
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ extract_features = self.feature_extractor(input_values)
+ extract_features = extract_features.transpose(1, 2)
+ extract_features = self.layer_norm(extract_features)
+
+ if self.project_features:
+ extract_features = self.feature_projection(extract_features)
+ hidden_states = self.feature_dropout(extract_features)
+
+ if attention_mask is not None:
+ # compute reduced attention_mask corresponding to feature vectors
+ attention_mask = self._get_feature_vector_attention_mask(hidden_states.shape[1], attention_mask)
+
+ hidden_states = self._mask_hidden_states(hidden_states, mask_time_indices=mask_time_indices)
+
+ encoder_outputs = self.encoder(
+ hidden_states,
+ attention_mask=attention_mask,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ hidden_states = encoder_outputs[0]
+
+ if not return_dict:
+ return (hidden_states,) + encoder_outputs[1:]
+
+ return BaseModelOutput(
+ last_hidden_state=hidden_states,
+ hidden_states=encoder_outputs.hidden_states,
+ attentions=encoder_outputs.attentions,
+ )
+
+
+_HIDDEN_STATES_START_POSITION = 1
+
+
+@auto_docstring(
+ custom_intro="""
+ SEW Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC).
+ """
+)
+class SEWForCTC(SEWPreTrainedModel):
+ def __init__(self, config, target_lang: str | None = None):
+ r"""
+ target_lang (`str`, *optional*):
+ Language id of adapter weights. Adapter weights are stored in the format adapter..safetensors or
+ adapter..bin. Only relevant when using an instance of [`SEWForCTC`] with adapters. Uses 'eng' by
+ default.
+ """
+ super().__init__(config)
+
+ self.sew = SEWModel(config)
+ self.dropout = nn.Dropout(config.final_dropout)
+
+ self.target_lang = target_lang
+
+ if config.vocab_size is None:
+ raise ValueError(
+ f"You are trying to instantiate {self.__class__} with a configuration that "
+ "does not define the vocabulary size of the language model head. Please "
+ "instantiate the model as follows: `SEWForCTC.from_pretrained(..., vocab_size=vocab_size)`. "
+ "or define `vocab_size` of your model's configuration."
+ )
+ output_hidden_size = (
+ config.output_hidden_size if hasattr(config, "add_adapter") and config.add_adapter else config.hidden_size
+ )
+ self.lm_head = nn.Linear(output_hidden_size, config.vocab_size)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def tie_weights(self, **kwargs):
+ """
+ This method overwrites [`~PreTrainedModel.tie_weights`] so that adapter weights can be correctly loaded when
+ passing `target_lang=...` to `from_pretrained(...)`.
+
+ This method is **not** supposed to be called by the user and is prone to be changed in the future.
+ """
+
+ if get_torch_context_manager_or_global_device() == torch.device("meta"):
+ return
+
+ # Note that `tie_weights` is usually used to tie input and output embedding weights. The method is re-purposed to
+ # correctly load adapter layers for SEW so that we do not have to introduce a new API to
+ # [`PreTrainedModel`]. While slightly hacky, SEW never has to tie input and output embeddings, so that it is
+ # ok to repurpose this function here.
+ target_lang = self.target_lang
+
+ if target_lang is not None and getattr(self.config, "adapter_attn_dim", None) is None:
+ raise ValueError(f"Cannot pass `target_lang`: {target_lang} if `config.adapter_attn_dim` is not defined.")
+ elif target_lang is None and getattr(self.config, "adapter_attn_dim", None) is not None:
+ logger.info("By default `target_lang` is set to 'eng'.")
+ elif target_lang is not None:
+ self.load_adapter(target_lang, force_load=True)
+
+ def freeze_feature_encoder(self):
+ """
+ Calling this function will disable the gradient computation for the feature encoder so that its parameter will
+ not be updated during training.
+ """
+ self.sew.feature_extractor._freeze_parameters()
+
+ def freeze_base_model(self):
+ """
+ Calling this function will disable the gradient computation for the base model so that its parameters will not
+ be updated during training. Only the classification head will be updated.
+ """
+ for param in self.sew.parameters():
+ param.requires_grad = False
+
+ @auto_docstring
+ def forward(
+ self,
+ input_values: torch.Tensor | None,
+ attention_mask: torch.Tensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ labels: torch.Tensor | None = None,
+ **kwargs,
+ ) -> tuple | CausalLMOutput:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, target_length)`, *optional*):
+ Labels for connectionist temporal classification. Note that `target_length` has to be smaller or equal to
+ the sequence length of the output logits. Indices are selected in `[-100, 0, ..., config.vocab_size - 1]`.
+ All labels set to `-100` are ignored (masked), the loss is only computed for labels in `[0, ...,
+ config.vocab_size - 1]`.
+ """
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ if labels is not None and labels.max() >= self.config.vocab_size:
+ raise ValueError(f"Label values must be <= vocab_size: {self.config.vocab_size}")
+
+ outputs = self.sew(
+ input_values,
+ attention_mask=attention_mask,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ hidden_states = outputs[0]
+ hidden_states = self.dropout(hidden_states)
+
+ logits = self.lm_head(hidden_states)
+
+ loss = None
+ if labels is not None:
+ # retrieve loss input_lengths from attention_mask
+ attention_mask = (
+ attention_mask if attention_mask is not None else torch.ones_like(input_values, dtype=torch.long)
+ )
+ input_lengths = self._get_feat_extract_output_lengths(attention_mask.sum(-1)).to(torch.long)
+
+ # assuming that padded tokens are filled with -100
+ # when not being attended to
+ labels_mask = labels >= 0
+ target_lengths = labels_mask.sum(-1)
+ flattened_targets = labels.masked_select(labels_mask)
+
+ # ctc_loss doesn't support fp16
+ log_probs = nn.functional.log_softmax(logits, dim=-1, dtype=torch.float32).transpose(0, 1)
+
+ with torch.backends.cudnn.flags(enabled=False):
+ loss = nn.functional.ctc_loss(
+ log_probs,
+ flattened_targets,
+ input_lengths,
+ target_lengths,
+ blank=self.config.pad_token_id,
+ reduction=self.config.ctc_loss_reduction,
+ zero_infinity=self.config.ctc_zero_infinity,
+ )
+
+ if not return_dict:
+ output = (logits,) + outputs[_HIDDEN_STATES_START_POSITION:]
+ return ((loss,) + output) if loss is not None else output
+
+ return CausalLMOutput(
+ loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ SEW Model with a sequence classification head on top (a linear layer over the pooled output) for tasks like
+ SUPERB Keyword Spotting.
+ """
+)
+class SEWForSequenceClassification(SEWPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ if hasattr(config, "add_adapter") and config.add_adapter:
+ raise ValueError(
+ "Sequence classification does not support the use of SEW adapters (config.add_adapter=True)"
+ )
+ self.sew = SEWModel(config)
+ num_layers = config.num_hidden_layers + 1 # transformer layers + input embeddings
+ if config.use_weighted_layer_sum:
+ self.layer_weights = nn.Parameter(torch.ones(num_layers) / num_layers)
+ self.projector = nn.Linear(config.hidden_size, config.classifier_proj_size)
+ self.classifier = nn.Linear(config.classifier_proj_size, config.num_labels)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def freeze_feature_encoder(self):
+ """
+ Calling this function will disable the gradient computation for the feature encoder so that its parameter will
+ not be updated during training.
+ """
+ self.sew.feature_extractor._freeze_parameters()
+
+ def freeze_base_model(self):
+ """
+ Calling this function will disable the gradient computation for the base model so that its parameters will not
+ be updated during training. Only the classification head will be updated.
+ """
+ for param in self.sew.parameters():
+ param.requires_grad = False
+
+ @auto_docstring
+ def forward(
+ self,
+ input_values: torch.Tensor | None,
+ attention_mask: torch.Tensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ labels: torch.Tensor | None = None,
+ **kwargs,
+ ) -> tuple | SequenceClassifierOutput:
+ r"""
+ input_values (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
+ Float values of input raw speech waveform. Values can be obtained by loading a `.flac` or `.wav` audio file
+ into an array of type `list[float]`, a `numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library
+ (`pip install torchcodec`) or the soundfile library (`pip install soundfile`).
+ To prepare the array into `input_values`, the [`AutoProcessor`] should be used for padding and conversion
+ into a tensor of type `torch.FloatTensor`. See [`SEWProcessor.__call__`] for details.
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+ output_hidden_states = True if self.config.use_weighted_layer_sum else output_hidden_states
+
+ outputs = self.sew(
+ input_values,
+ attention_mask=attention_mask,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ if self.config.use_weighted_layer_sum:
+ hidden_states = outputs[_HIDDEN_STATES_START_POSITION]
+ hidden_states = torch.stack(hidden_states, dim=1)
+ norm_weights = nn.functional.softmax(self.layer_weights, dim=-1)
+ hidden_states = (hidden_states * norm_weights.view(-1, 1, 1)).sum(dim=1)
+ else:
+ hidden_states = outputs[0]
+
+ hidden_states = self.projector(hidden_states)
+ if attention_mask is None:
+ pooled_output = hidden_states.mean(dim=1)
+ else:
+ padding_mask = self._get_feature_vector_attention_mask(hidden_states.shape[1], attention_mask)
+ expand_padding_mask = padding_mask.unsqueeze(-1).repeat(1, 1, hidden_states.shape[2])
+ hidden_states[~expand_padding_mask] = 0.0
+ pooled_output = hidden_states.sum(dim=1) / padding_mask.sum(dim=1).view(-1, 1)
+
+ logits = self.classifier(pooled_output)
+
+ loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.config.num_labels), labels.view(-1))
+
+ if not return_dict:
+ output = (logits,) + outputs[_HIDDEN_STATES_START_POSITION:]
+ return ((loss,) + output) if loss is not None else output
+
+ return SequenceClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+__all__ = ["SEWForCTC", "SEWForSequenceClassification", "SEWModel", "SEWPreTrainedModel"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/sew/modular_sew.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/sew/modular_sew.py
new file mode 100644
index 0000000000000000000000000000000000000000..312419793a3461f00dc5c9d16d83b106294f403d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/sew/modular_sew.py
@@ -0,0 +1,449 @@
+# Copyright 2021 ASAPP Inc. and the HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch SEW model."""
+
+import math
+
+import torch
+from torch import nn
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...integrations.deepspeed import is_deepspeed_zero3_enabled
+from ...integrations.fsdp import is_fsdp_managed_module
+from ...modeling_outputs import BaseModelOutput
+from ...modeling_utils import PreTrainedModel
+from ...utils import auto_docstring
+from ...utils.generic import is_flash_attention_requested
+from ..wav2vec2.modeling_wav2vec2 import (
+ Wav2Vec2Attention,
+ Wav2Vec2EncoderLayer,
+ Wav2Vec2FeatureEncoder,
+ Wav2Vec2FeedForward,
+ Wav2Vec2ForCTC,
+ Wav2Vec2ForSequenceClassification,
+ Wav2Vec2GroupNormConvLayer,
+ Wav2Vec2LayerNormConvLayer,
+ Wav2Vec2NoLayerNormConvLayer,
+ Wav2Vec2SamePadLayer,
+ _compute_mask_indices,
+)
+from .configuration_sew import SEWConfig
+
+
+_HIDDEN_STATES_START_POSITION = 1
+
+
+class SEWNoLayerNormConvLayer(Wav2Vec2NoLayerNormConvLayer):
+ pass
+
+
+class SEWLayerNormConvLayer(Wav2Vec2LayerNormConvLayer):
+ pass
+
+
+class SEWGroupNormConvLayer(Wav2Vec2GroupNormConvLayer):
+ pass
+
+
+class SEWPositionalConvEmbedding(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.conv = nn.Conv1d(
+ config.hidden_size,
+ config.hidden_size,
+ kernel_size=config.num_conv_pos_embeddings,
+ padding=config.num_conv_pos_embeddings // 2,
+ groups=config.num_conv_pos_embedding_groups,
+ stride=config.squeeze_factor,
+ )
+
+ weight_norm = nn.utils.weight_norm
+ if hasattr(nn.utils.parametrizations, "weight_norm"):
+ weight_norm = nn.utils.parametrizations.weight_norm
+
+ if is_deepspeed_zero3_enabled():
+ import deepspeed
+
+ with deepspeed.zero.GatheredParameters(self.conv.weight, modifier_rank=0):
+ self.conv = weight_norm(self.conv, name="weight", dim=2)
+ if hasattr(self.conv, "parametrizations"):
+ weight_g = self.conv.parametrizations.weight.original0
+ weight_v = self.conv.parametrizations.weight.original1
+ else:
+ weight_g = self.conv.weight_g
+ weight_v = self.conv.weight_v
+ deepspeed.zero.register_external_parameter(self, weight_v)
+ deepspeed.zero.register_external_parameter(self, weight_g)
+ else:
+ self.conv = weight_norm(self.conv, name="weight", dim=2)
+
+ self.padding = SEWSamePadLayer(config.num_conv_pos_embeddings)
+ self.activation = ACT2FN[config.feat_extract_activation]
+
+ def forward(self, hidden_states):
+ hidden_states = self.conv(hidden_states)
+ hidden_states = self.padding(hidden_states)
+ hidden_states = self.activation(hidden_states)
+
+ return hidden_states
+
+
+class SEWSamePadLayer(Wav2Vec2SamePadLayer):
+ pass
+
+
+class SEWUpsampling(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.projection = nn.Linear(config.hidden_size, config.hidden_size * config.squeeze_factor)
+ self.activation = ACT2FN[config.feat_extract_activation]
+ self.squeeze_factor = config.squeeze_factor
+
+ def forward(self, hidden_states):
+ hidden_states = self.projection(hidden_states)
+ hidden_states = self.activation(hidden_states)
+
+ if self.squeeze_factor > 1:
+ # transform embedding channels to sequence length
+ bsz, src_len, src_embed_dim = hidden_states.size()
+ tgt_len = src_len * self.squeeze_factor
+ tgt_embed_dim = src_embed_dim // self.squeeze_factor
+ hidden_states = hidden_states.reshape(bsz, src_len, self.squeeze_factor, tgt_embed_dim)
+ hidden_states = hidden_states.reshape(bsz, tgt_len, tgt_embed_dim)
+
+ return hidden_states
+
+
+class SEWFeatureEncoder(Wav2Vec2FeatureEncoder):
+ pass
+
+
+class SEWAttention(Wav2Vec2Attention):
+ pass
+
+
+class SEWFeedForward(Wav2Vec2FeedForward):
+ pass
+
+
+class SEWEncoderLayer(Wav2Vec2EncoderLayer):
+ pass
+
+
+class SEWEncoder(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.pos_conv_embed = SEWPositionalConvEmbedding(config)
+ self.pool = nn.AvgPool1d(config.squeeze_factor, config.squeeze_factor)
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout)
+ self.layers = nn.ModuleList([SEWEncoderLayer(config) for _ in range(config.num_hidden_layers)])
+ self.upsample = SEWUpsampling(config)
+ self.gradient_checkpointing = False
+
+ def forward(
+ self,
+ hidden_states,
+ attention_mask=None,
+ output_attentions=False,
+ output_hidden_states=False,
+ return_dict=True,
+ ):
+ all_hidden_states = () if output_hidden_states else None
+ all_self_attentions = () if output_attentions else None
+
+ if attention_mask is not None:
+ expand_attention_mask = attention_mask.unsqueeze(-1).repeat(1, 1, hidden_states.shape[2])
+ if is_flash_attention_requested(self.config):
+ # make sure padded tokens output 0
+ hidden_states[~expand_attention_mask] = 0.0
+ # 2d mask is passed through the layers
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
+ else:
+ # make sure padded tokens output 0
+ hidden_states[~expand_attention_mask] = 0.0
+ input_lengths = (attention_mask.long()).sum(-1)
+ # apply pooling formula to get real output_lengths
+ output_lengths = input_lengths // self.config.squeeze_factor
+ max_encoder_length = hidden_states.shape[1] // self.config.squeeze_factor
+ attention_ids = (
+ torch.arange(0, max_encoder_length, device=output_lengths.device)
+ .view(1, -1)
+ .expand(output_lengths.shape[0], -1)
+ )
+ attention_mask = (attention_ids < output_lengths.view(-1, 1)).long()
+
+ # extend attention_mask
+ attention_mask = 1.0 - attention_mask[:, None, None, :].to(dtype=hidden_states.dtype)
+ attention_mask = attention_mask * torch.finfo(hidden_states.dtype).min
+ attention_mask = attention_mask.expand(
+ attention_mask.shape[0], 1, attention_mask.shape[-1], attention_mask.shape[-1]
+ )
+
+ n_input_timesteps = hidden_states.shape[1]
+
+ hidden_states = hidden_states.transpose(1, 2)
+ position_embeddings = self.pos_conv_embed(hidden_states)
+ pooled_hidden_states = self.pool(hidden_states)
+ min_length = min(position_embeddings.size(-1), pooled_hidden_states.size(-1))
+ hidden_states = pooled_hidden_states[..., :min_length] + position_embeddings[..., :min_length]
+ hidden_states = hidden_states.transpose(1, 2)
+
+ hidden_states = self.layer_norm(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+
+ synced_gpus = is_deepspeed_zero3_enabled() or is_fsdp_managed_module(self)
+
+ for layer in self.layers:
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ # add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
+ dropout_probability = torch.rand([])
+
+ skip_the_layer = self.training and dropout_probability < self.config.layerdrop
+ if not skip_the_layer or synced_gpus:
+ # under fsdp or deepspeed zero3 all gpus must run in sync
+ layer_outputs = layer(
+ hidden_states, attention_mask=attention_mask, output_attentions=output_attentions
+ )
+ hidden_states = layer_outputs[0]
+
+ if skip_the_layer:
+ layer_outputs = (None, None)
+
+ if output_attentions:
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
+
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ hidden_states = self.upsample(hidden_states)
+ if hidden_states.shape[1] < n_input_timesteps:
+ hidden_states = nn.functional.pad(hidden_states, (0, 0, 0, n_input_timesteps - hidden_states.shape[1]))
+
+ if not return_dict:
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
+ return BaseModelOutput(
+ last_hidden_state=hidden_states,
+ hidden_states=all_hidden_states,
+ attentions=all_self_attentions,
+ )
+
+
+@auto_docstring
+class SEWPreTrainedModel(PreTrainedModel):
+ config: SEWConfig
+ base_model_prefix = "sew"
+ main_input_name = "input_values"
+ input_modalities = "audio"
+ supports_gradient_checkpointing = True
+ _supports_flash_attn = True
+ _supports_sdpa = True
+ _supports_flex_attn = False # needs a proper look into the mask creation
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ """Initialize the weights"""
+ if isinstance(module, SEWPositionalConvEmbedding):
+ init.normal_(
+ module.conv.weight,
+ mean=0,
+ std=2 * math.sqrt(1 / (module.conv.kernel_size[0] * module.conv.in_channels)),
+ )
+ init.constant_(module.conv.bias, 0)
+ elif isinstance(module, nn.Linear):
+ init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
+ elif isinstance(module, (nn.LayerNorm, nn.GroupNorm)):
+ init.zeros_(module.bias)
+ init.ones_(module.weight)
+ elif isinstance(module, nn.Conv1d):
+ if is_deepspeed_zero3_enabled():
+ import deepspeed
+
+ if hasattr(module, "weight_v") and hasattr(module, "weight_g"):
+ with deepspeed.zero.GatheredParameters([module.weight_v, module.weight_g], modifier_rank=0):
+ init.kaiming_normal_(module.weight)
+ else:
+ with deepspeed.zero.GatheredParameters(module.weight, modifier_rank=0):
+ init.kaiming_normal_(module.weight)
+ else:
+ init.kaiming_normal_(module.weight)
+
+ if isinstance(module, (nn.Linear, nn.Conv1d)) and module.bias is not None:
+ init.zeros_(module.bias)
+
+ def _get_feat_extract_output_lengths(self, input_lengths: torch.LongTensor | int):
+ """
+ Computes the output length of the convolutional layers
+ """
+
+ def _conv_out_length(input_length, kernel_size, stride):
+ # 1D convolutional layer output length formula taken
+ # from https://pytorch.org/docs/stable/generated/torch.nn.Conv1d.html
+ return torch.div(input_length - kernel_size, stride, rounding_mode="floor") + 1
+
+ for kernel_size, stride in zip(self.config.conv_kernel, self.config.conv_stride):
+ input_lengths = _conv_out_length(input_lengths, kernel_size, stride)
+
+ return input_lengths
+
+ def _get_feature_vector_attention_mask(self, feature_vector_length: int, attention_mask: torch.LongTensor):
+ output_lengths = self._get_feat_extract_output_lengths(attention_mask.sum(-1)).to(torch.long)
+ batch_size = attention_mask.shape[0]
+
+ attention_mask = torch.zeros(
+ (batch_size, feature_vector_length), dtype=attention_mask.dtype, device=attention_mask.device
+ )
+ # these two operations makes sure that all values before the output lengths idxs are attended to
+ attention_mask[(torch.arange(attention_mask.shape[0], device=attention_mask.device), output_lengths - 1)] = 1
+ attention_mask = attention_mask.flip([-1]).cumsum(-1).flip([-1]).bool()
+ return attention_mask
+
+
+@auto_docstring
+class SEWModel(SEWPreTrainedModel):
+ def __init__(self, config: SEWConfig):
+ super().__init__(config)
+ self.config = config
+ self.feature_extractor = SEWFeatureEncoder(config)
+ self.layer_norm = nn.LayerNorm(config.conv_dim[-1], eps=config.layer_norm_eps)
+
+ self.project_features = config.conv_dim[-1] != config.hidden_size
+ if self.project_features:
+ self.feature_projection = nn.Linear(config.conv_dim[-1], config.hidden_size)
+ self.feature_dropout = nn.Dropout(config.feat_proj_dropout)
+
+ if config.mask_time_prob > 0.0 or config.mask_feature_prob > 0.0:
+ self.masked_spec_embed = nn.Parameter(torch.Tensor(config.hidden_size).uniform_())
+
+ self.encoder = SEWEncoder(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2Model._mask_hidden_states
+ def _mask_hidden_states(
+ self,
+ hidden_states: torch.FloatTensor,
+ mask_time_indices: torch.FloatTensor | None = None,
+ attention_mask: torch.LongTensor | None = None,
+ ):
+ """
+ Masks extracted features along time axis and/or along feature axis according to
+ [SpecAugment](https://huggingface.co/papers/1904.08779).
+ """
+
+ # `config.apply_spec_augment` can set masking to False
+ if not getattr(self.config, "apply_spec_augment", True):
+ return hidden_states
+
+ # generate indices & apply SpecAugment along time axis
+ batch_size, sequence_length, hidden_size = hidden_states.size()
+
+ if mask_time_indices is not None:
+ # apply SpecAugment along time axis with given mask_time_indices
+ hidden_states[mask_time_indices] = self.masked_spec_embed.to(hidden_states.dtype)
+ elif self.config.mask_time_prob > 0 and self.training:
+ mask_time_indices = _compute_mask_indices(
+ (batch_size, sequence_length),
+ mask_prob=self.config.mask_time_prob,
+ mask_length=self.config.mask_time_length,
+ attention_mask=attention_mask,
+ min_masks=self.config.mask_time_min_masks,
+ )
+ mask_time_indices = torch.tensor(mask_time_indices, device=hidden_states.device, dtype=torch.bool)
+ hidden_states[mask_time_indices] = self.masked_spec_embed.to(hidden_states.dtype)
+
+ if self.config.mask_feature_prob > 0 and self.training:
+ # generate indices & apply SpecAugment along feature axis
+ mask_feature_indices = _compute_mask_indices(
+ (batch_size, hidden_size),
+ mask_prob=self.config.mask_feature_prob,
+ mask_length=self.config.mask_feature_length,
+ min_masks=self.config.mask_feature_min_masks,
+ )
+ mask_feature_indices = torch.tensor(mask_feature_indices, device=hidden_states.device, dtype=torch.bool)
+ mask_feature_indices = mask_feature_indices[:, None].expand(-1, sequence_length, -1)
+ hidden_states[mask_feature_indices] = 0
+
+ return hidden_states
+
+ @auto_docstring
+ def forward(
+ self,
+ input_values: torch.Tensor | None,
+ attention_mask: torch.Tensor | None = None,
+ mask_time_indices: torch.FloatTensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple | BaseModelOutput:
+ r"""
+ mask_time_indices (`torch.BoolTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Indices to mask extracted features for contrastive loss. When in training mode, model learns to predict
+ masked extracted features in *config.proj_codevector_dim* space.
+ """
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ extract_features = self.feature_extractor(input_values)
+ extract_features = extract_features.transpose(1, 2)
+ extract_features = self.layer_norm(extract_features)
+
+ if self.project_features:
+ extract_features = self.feature_projection(extract_features)
+ hidden_states = self.feature_dropout(extract_features)
+
+ if attention_mask is not None:
+ # compute reduced attention_mask corresponding to feature vectors
+ attention_mask = self._get_feature_vector_attention_mask(hidden_states.shape[1], attention_mask)
+
+ hidden_states = self._mask_hidden_states(hidden_states, mask_time_indices=mask_time_indices)
+
+ encoder_outputs = self.encoder(
+ hidden_states,
+ attention_mask=attention_mask,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ hidden_states = encoder_outputs[0]
+
+ if not return_dict:
+ return (hidden_states,) + encoder_outputs[1:]
+
+ return BaseModelOutput(
+ last_hidden_state=hidden_states,
+ hidden_states=encoder_outputs.hidden_states,
+ attentions=encoder_outputs.attentions,
+ )
+
+
+class SEWForCTC(Wav2Vec2ForCTC):
+ pass
+
+
+class SEWForSequenceClassification(Wav2Vec2ForSequenceClassification):
+ pass
+
+
+__all__ = ["SEWForCTC", "SEWForSequenceClassification", "SEWModel", "SEWPreTrainedModel"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/solar_open/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/solar_open/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..52ca7575697a58c9ed27fef2b214a70380d4a7cb
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/solar_open/__init__.py
@@ -0,0 +1,27 @@
+# Copyright 2026 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_solar_open import *
+ from .modeling_solar_open import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/solar_open/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/solar_open/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..eb754c910cf95ec6c878dc79b4cdb7a6527f233f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/solar_open/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/solar_open/__pycache__/configuration_solar_open.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/solar_open/__pycache__/configuration_solar_open.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f06aa1b9484aa62e1b27c3b14a6c31aac667dbfc
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/solar_open/__pycache__/configuration_solar_open.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/solar_open/__pycache__/modeling_solar_open.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/solar_open/__pycache__/modeling_solar_open.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5858e2aaea66a962b46abab5ad44a8bd7d89675b
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/solar_open/__pycache__/modeling_solar_open.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/solar_open/__pycache__/modular_solar_open.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/solar_open/__pycache__/modular_solar_open.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ec369aa51dfa0e43416dc6fc8ace436d86b0a340
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/solar_open/__pycache__/modular_solar_open.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/solar_open/configuration_solar_open.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/solar_open/configuration_solar_open.py
new file mode 100644
index 0000000000000000000000000000000000000000..ac0016aa77910ea448db537a3a1c076c5f27406c
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/solar_open/configuration_solar_open.py
@@ -0,0 +1,92 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/solar_open/modular_solar_open.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_solar_open.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2026 Upstage and HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...modeling_rope_utils import RopeParameters
+from ...utils import auto_docstring
+
+
+@auto_docstring(checkpoint="upstage/Solar-Open-100B")
+@strict
+class SolarOpenConfig(PreTrainedConfig):
+ r"""
+ n_group (`int`, *optional*, defaults to 1):
+ Number of groups for routed experts.
+ """
+
+ model_type = "solar_open"
+ keys_to_ignore_at_inference = ["past_key_values"]
+
+ # Default tensor parallel plan for base model `SolarOpenModel`
+ base_model_tp_plan = {
+ "layers.*.self_attn.q_proj": "colwise",
+ "layers.*.self_attn.k_proj": "colwise",
+ "layers.*.self_attn.v_proj": "colwise",
+ "layers.*.self_attn.o_proj": "rowwise",
+ "layers.*.mlp.experts.gate_up_proj": "packed_colwise",
+ "layers.*.mlp.experts.down_proj": "rowwise",
+ "layers.*.mlp.experts": "moe_tp_experts",
+ }
+ base_model_pp_plan = {
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
+ "norm": (["hidden_states"], ["hidden_states"]),
+ }
+ attribute_map = {
+ "num_local_experts": "n_routed_experts",
+ }
+
+ vocab_size: int = 196608
+ hidden_size: int = 4096
+ num_hidden_layers: int = 48
+ num_attention_heads: int = 64
+ num_key_value_heads: int = 8
+ hidden_act: str = "silu"
+ max_position_embeddings: int = 131072
+ initializer_range: float = 0.02
+ rms_norm_eps: float = 1e-5
+ use_cache: bool = True
+ tie_word_embeddings: bool = False
+ rope_parameters: RopeParameters | dict | None = None
+ attention_bias: bool = False
+ attention_dropout: float | int = 0.0
+ moe_intermediate_size: int = 1280
+ num_experts_per_tok: int = 8
+ n_shared_experts: int = 1
+ n_routed_experts: int = 128
+ routed_scaling_factor: float = 1.0
+ n_group: int = 1
+ topk_group: int = 1
+ norm_topk_prob: bool = True
+ bos_token_id: int | None = None
+ eos_token_id: int | list[int] | None = None
+ pad_token_id: int | None = None
+ default_theta = 1_000_000.0
+ head_dim: int = 128
+
+ def __post_init__(self, **kwargs):
+ kwargs.setdefault("partial_rotary_factor", 1.0)
+ kwargs.setdefault("partial_rotary_factor", 0.5) # assign default for BC
+ super().__post_init__(**kwargs)
+
+
+__all__ = ["SolarOpenConfig"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/solar_open/modeling_solar_open.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/solar_open/modeling_solar_open.py
new file mode 100644
index 0000000000000000000000000000000000000000..0eb50021ecd63a9a515c67d65728f13a4eb07eac
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/solar_open/modeling_solar_open.py
@@ -0,0 +1,626 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/solar_open/modular_solar_open.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_solar_open.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2026 Upstage and HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from collections.abc import Callable
+from typing import Optional
+
+import torch
+import torch.nn.functional as F
+from torch import nn
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...cache_utils import Cache, DynamicCache
+from ...generation import GenerationMixin
+from ...integrations import (
+ use_experts_implementation,
+ use_kernel_forward_from_hub,
+ use_kernel_func_from_hub,
+ use_kernelized_func,
+)
+from ...masking_utils import create_causal_mask
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
+from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import TransformersKwargs, auto_docstring, can_return_tuple
+from ...utils.generic import maybe_autocast, merge_with_config_defaults
+from ...utils.output_capturing import capture_outputs
+from .configuration_solar_open import SolarOpenConfig
+
+
+class SolarOpenDecoderLayer(GradientCheckpointingLayer):
+ def __init__(self, config: SolarOpenConfig, layer_idx: int):
+ super().__init__()
+ self.hidden_size = config.hidden_size
+
+ self.self_attn = SolarOpenAttention(config=config, layer_idx=layer_idx)
+ self.mlp = SolarOpenMoE(config)
+ self.input_layernorm = SolarOpenRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.post_attention_layernorm = SolarOpenRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ use_cache: bool | None = False,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.Tensor:
+ residual = hidden_states
+ hidden_states = self.input_layernorm(hidden_states)
+ # Self Attention
+ hidden_states, _ = self.self_attn(
+ hidden_states=hidden_states,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ position_embeddings=position_embeddings,
+ **kwargs,
+ )
+ hidden_states = residual + hidden_states
+
+ # Fully Connected
+ residual = hidden_states
+ hidden_states = self.post_attention_layernorm(hidden_states)
+ hidden_states = self.mlp(hidden_states)
+ hidden_states = residual + hidden_states
+ return hidden_states
+
+
+class SolarOpenMLP(nn.Module):
+ def __init__(self, config, intermediate_size=None):
+ super().__init__()
+ self.config = config
+ self.hidden_size = config.hidden_size
+ self.intermediate_size = config.intermediate_size if intermediate_size is None else intermediate_size
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
+ self.act_fn = ACT2FN[config.hidden_act]
+
+ def forward(self, x):
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
+ return down_proj
+
+
+class SolarOpenTopkRouter(nn.Module):
+ def __init__(self, config: SolarOpenConfig):
+ super().__init__()
+ self.config = config
+ self.top_k = config.num_experts_per_tok
+ self.n_routed_experts = config.n_routed_experts
+ self.routed_scaling_factor = config.routed_scaling_factor
+ self.n_group = config.n_group
+ self.topk_group = config.topk_group
+ self.norm_topk_prob = config.norm_topk_prob
+
+ self.weight = nn.Parameter(torch.empty((self.n_routed_experts, config.hidden_size)))
+ self.register_buffer("e_score_correction_bias", torch.zeros((self.n_routed_experts), dtype=torch.float32))
+
+ def forward(self, hidden_states):
+ hidden_states = hidden_states.view(-1, self.config.hidden_size)
+ router_logits = F.linear(hidden_states.type(torch.float32), self.weight.type(torch.float32))
+ return router_logits
+
+
+@use_experts_implementation
+class SolarOpenNaiveMoe(nn.Module):
+ """Collection of expert weights stored as 3D tensors."""
+
+ def __init__(self, config):
+ super().__init__()
+ self.num_experts = config.num_local_experts
+ self.hidden_dim = config.hidden_size
+ self.intermediate_dim = config.moe_intermediate_size
+ self.gate_up_proj = nn.Parameter(torch.empty(self.num_experts, 2 * self.intermediate_dim, self.hidden_dim))
+ self.down_proj = nn.Parameter(torch.empty(self.num_experts, self.hidden_dim, self.intermediate_dim))
+ self.act_fn = ACT2FN[config.hidden_act]
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ top_k_index: torch.Tensor,
+ top_k_weights: torch.Tensor,
+ ) -> torch.Tensor:
+ final_hidden_states = torch.zeros_like(hidden_states)
+ with torch.no_grad():
+ expert_mask = torch.nn.functional.one_hot(top_k_index, num_classes=self.num_experts)
+ expert_mask = expert_mask.permute(2, 1, 0)
+ expert_hit = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero()
+
+ for expert_idx in expert_hit:
+ expert_idx = expert_idx[0]
+ if expert_idx == self.num_experts:
+ continue
+ top_k_pos, token_idx = torch.where(expert_mask[expert_idx])
+ current_state = hidden_states[token_idx]
+ gate, up = nn.functional.linear(current_state, self.gate_up_proj[expert_idx]).chunk(2, dim=-1)
+ current_hidden_states = self.act_fn(gate) * up
+ current_hidden_states = nn.functional.linear(current_hidden_states, self.down_proj[expert_idx])
+ current_hidden_states = current_hidden_states * top_k_weights[token_idx, top_k_pos, None]
+ final_hidden_states.index_add_(0, token_idx, current_hidden_states.to(final_hidden_states.dtype))
+
+ return final_hidden_states
+
+
+class SolarOpenMoE(nn.Module):
+ """
+ A mixed expert module containing shared experts.
+ """
+
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.experts = SolarOpenNaiveMoe(config)
+ self.gate = SolarOpenTopkRouter(config)
+ self.shared_experts = SolarOpenMLP(
+ config=config, intermediate_size=config.moe_intermediate_size * config.n_shared_experts
+ )
+ self.n_routed_experts = config.n_routed_experts
+ self.n_group = config.n_group
+ self.topk_group = config.topk_group
+ self.norm_topk_prob = config.norm_topk_prob
+ self.routed_scaling_factor = config.routed_scaling_factor
+ self.top_k = config.num_experts_per_tok
+
+ def route_tokens_to_experts(self, router_logits):
+ router_logits = router_logits.sigmoid()
+ router_logits_for_choice = router_logits + self.gate.e_score_correction_bias
+ group_scores = (
+ router_logits_for_choice.view(-1, self.n_group, self.n_routed_experts // self.n_group)
+ .topk(2, dim=-1)[0]
+ .sum(dim=-1)
+ )
+ group_idx = torch.topk(group_scores, k=self.topk_group, dim=-1, sorted=False)[1]
+ group_mask = torch.zeros_like(group_scores)
+ group_mask.scatter_(1, group_idx, 1)
+ score_mask = (
+ group_mask.unsqueeze(-1)
+ .expand(-1, self.n_group, self.n_routed_experts // self.n_group)
+ .reshape(-1, self.n_routed_experts)
+ )
+ scores_for_choice = router_logits_for_choice.masked_fill(~score_mask.bool(), float("-inf"))
+ topk_indices = torch.topk(scores_for_choice, k=self.top_k, dim=-1, sorted=False)[1]
+ topk_weights = router_logits.gather(1, topk_indices)
+ if self.norm_topk_prob:
+ denominator = topk_weights.sum(dim=-1, keepdim=True) + 1e-20
+ topk_weights /= denominator
+ topk_weights = topk_weights * self.routed_scaling_factor
+ return topk_indices, topk_weights
+
+ def forward(self, hidden_states):
+ residuals = hidden_states
+ orig_shape = hidden_states.shape
+ router_logits = self.gate(hidden_states)
+ topk_indices, topk_weights = self.route_tokens_to_experts(router_logits)
+ hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
+ hidden_states = self.experts(hidden_states, topk_indices, topk_weights).view(*orig_shape)
+ hidden_states = hidden_states + self.shared_experts(residuals)
+ return hidden_states
+
+
+def rotate_half(x):
+ """Rotates half the hidden dims of the input."""
+ x1 = x[..., : x.shape[-1] // 2]
+ x2 = x[..., x.shape[-1] // 2 :]
+ return torch.cat((-x2, x1), dim=-1)
+
+
+@use_kernel_func_from_hub("rotary_pos_emb")
+def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
+ """Applies Rotary Position Embedding to the query and key tensors.
+
+ Args:
+ q (`torch.Tensor`): The query tensor.
+ k (`torch.Tensor`): The key tensor.
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
+ Returns:
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
+ """
+ cos = cos.unsqueeze(unsqueeze_dim)
+ sin = sin.unsqueeze(unsqueeze_dim)
+ q_embed = (q * cos) + (rotate_half(q) * sin)
+ k_embed = (k * cos) + (rotate_half(k) * sin)
+ return q_embed, k_embed
+
+
+def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
+ """
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
+ """
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
+ if n_rep == 1:
+ return hidden_states
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
+
+
+def eager_attention_forward(
+ module: nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: torch.Tensor | None,
+ scaling: float,
+ dropout: float = 0.0,
+ **kwargs: Unpack[TransformersKwargs],
+):
+ key_states = repeat_kv(key, module.num_key_value_groups)
+ value_states = repeat_kv(value, module.num_key_value_groups)
+
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
+ if attention_mask is not None:
+ attn_weights = attn_weights + attention_mask
+
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
+ attn_output = torch.matmul(attn_weights, value_states)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+
+ return attn_output, attn_weights
+
+
+@use_kernelized_func(apply_rotary_pos_emb)
+class SolarOpenAttention(nn.Module):
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
+
+ def __init__(self, config: SolarOpenConfig, layer_idx: int):
+ super().__init__()
+ self.config = config
+ self.layer_idx = layer_idx
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
+ self.scaling = self.head_dim**-0.5
+ self.attention_dropout = config.attention_dropout
+ self.is_causal = True
+
+ self.q_proj = nn.Linear(
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
+ )
+ self.k_proj = nn.Linear(
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
+ )
+ self.v_proj = nn.Linear(
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
+ )
+ self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
+ attention_mask: torch.Tensor | None = None,
+ past_key_values: Cache | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor, torch.Tensor]:
+ input_shape = hidden_states.shape[:-1]
+ hidden_shape = (*input_shape, -1, self.head_dim)
+
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+
+ cos, sin = position_embeddings
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
+
+ if past_key_values is not None:
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_states,
+ key_states,
+ value_states,
+ attention_mask,
+ dropout=0.0 if not self.training else self.attention_dropout,
+ scaling=self.scaling,
+ **kwargs,
+ )
+
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ attn_output = self.o_proj(attn_output)
+ return attn_output, attn_weights
+
+
+@use_kernel_forward_from_hub("RMSNorm")
+class SolarOpenRMSNorm(nn.Module):
+ def __init__(self, hidden_size, eps: float = 1e-6) -> None:
+ """
+ SolarOpenRMSNorm is equivalent to T5LayerNorm
+ """
+ super().__init__()
+ self.weight = nn.Parameter(torch.ones(hidden_size))
+ self.variance_epsilon = eps
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ input_dtype = hidden_states.dtype
+ hidden_states = hidden_states.to(torch.float32)
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
+ return self.weight * hidden_states.to(input_dtype)
+
+ def extra_repr(self):
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
+
+
+@auto_docstring
+class SolarOpenPreTrainedModel(PreTrainedModel):
+ config: SolarOpenConfig
+ base_model_prefix = "model"
+ supports_gradient_checkpointing = True
+ _no_split_modules = ["SolarOpenDecoderLayer"]
+ _skip_keys_device_placement = ["past_key_values"]
+ _supports_flash_attn = True
+ _supports_sdpa = True
+ _supports_flex_attn = True
+
+ _can_compile_fullgraph = True
+ _supports_attention_backend = True
+ _can_record_outputs = {
+ "hidden_states": SolarOpenDecoderLayer,
+ "attentions": SolarOpenAttention,
+ }
+ _keep_in_fp32_modules_strict = ["e_score_correction_bias"]
+ _keys_to_ignore_on_load_unexpected = None
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ super()._init_weights(module)
+ if isinstance(module, SolarOpenTopkRouter):
+ init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
+ init.zeros_(module.e_score_correction_bias)
+ elif isinstance(module, SolarOpenNaiveMoe):
+ init.normal_(module.gate_up_proj, mean=0.0, std=self.config.initializer_range)
+ init.normal_(module.down_proj, mean=0.0, std=self.config.initializer_range)
+
+
+class SolarOpenRotaryEmbedding(nn.Module):
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
+
+ def __init__(self, config: SolarOpenConfig, device=None):
+ super().__init__()
+ self.max_seq_len_cached = config.max_position_embeddings
+ self.original_max_seq_len = config.max_position_embeddings
+
+ self.config = config
+
+ self.rope_type = self.config.rope_parameters["rope_type"]
+ rope_init_fn: Callable = self.compute_default_rope_parameters
+ if self.rope_type != "default":
+ rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
+ inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
+
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
+ self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
+
+ @staticmethod
+ def compute_default_rope_parameters(
+ config: SolarOpenConfig | None = None,
+ device: Optional["torch.device"] = None,
+ seq_len: int | None = None,
+ ) -> tuple["torch.Tensor", float]:
+ """
+ Computes the inverse frequencies according to the original RoPE implementation
+ Args:
+ config ([`~transformers.PreTrainedConfig`]):
+ The model configuration.
+ device (`torch.device`):
+ The device to use for initialization of the inverse frequencies.
+ seq_len (`int`, *optional*):
+ The current sequence length. Unused for this type of RoPE.
+ Returns:
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
+ """
+ base = config.rope_parameters["rope_theta"]
+ partial_rotary_factor = config.rope_parameters.get("partial_rotary_factor", 1.0)
+ head_dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
+ dim = int(head_dim * partial_rotary_factor)
+
+ attention_factor = 1.0 # Unused in this type of RoPE
+
+ # Compute the inverse frequencies
+ inv_freq = 1.0 / (
+ base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
+ )
+ return inv_freq, attention_factor
+
+ @torch.no_grad()
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
+ def forward(self, x, position_ids):
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
+ position_ids_expanded = position_ids[:, None, :].float()
+
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
+ with maybe_autocast(device_type=device_type, enabled=False): # Force float32
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
+ emb = torch.cat((freqs, freqs), dim=-1)
+ cos = emb.cos() * self.attention_scaling
+ sin = emb.sin() * self.attention_scaling
+
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
+
+
+@auto_docstring
+class SolarOpenModel(SolarOpenPreTrainedModel):
+ def __init__(self, config: SolarOpenConfig):
+ super().__init__(config)
+ self.padding_idx = config.pad_token_id
+ self.vocab_size = config.vocab_size
+
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
+ self.layers = nn.ModuleList(
+ [SolarOpenDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
+ )
+ self.norm = SolarOpenRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.rotary_emb = SolarOpenRotaryEmbedding(config=config)
+ self.gradient_checkpointing = False
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @merge_with_config_defaults
+ @capture_outputs
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ use_cache: bool | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> BaseModelOutputWithPast:
+ if (input_ids is None) ^ (inputs_embeds is not None):
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
+
+ if inputs_embeds is None:
+ inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)
+
+ if use_cache and past_key_values is None:
+ past_key_values = DynamicCache(config=self.config)
+
+ if position_ids is None:
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
+ position_ids = position_ids.unsqueeze(0)
+
+ causal_mask = create_causal_mask(
+ config=self.config,
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ position_ids=position_ids,
+ )
+
+ hidden_states = inputs_embeds
+ position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
+
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
+ hidden_states = decoder_layer(
+ hidden_states,
+ attention_mask=causal_mask,
+ position_embeddings=position_embeddings,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ **kwargs,
+ )
+
+ hidden_states = self.norm(hidden_states)
+ return BaseModelOutputWithPast(
+ last_hidden_state=hidden_states,
+ past_key_values=past_key_values,
+ )
+
+
+@auto_docstring
+class SolarOpenForCausalLM(SolarOpenPreTrainedModel, GenerationMixin):
+ _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
+ _tp_plan = {"lm_head": "colwise_gather_output"}
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
+
+ def __init__(self, config):
+ super().__init__(config)
+ self.model = SolarOpenModel(config)
+ self.vocab_size = config.vocab_size
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ use_cache: bool | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> CausalLMOutputWithPast:
+ r"""
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, SolarOpenForCausalLM
+
+ >>> model = SolarOpenForCausalLM.from_pretrained("meta-solar_open/SolarOpen-2-7b-hf")
+ >>> tokenizer = AutoTokenizer.from_pretrained("meta-solar_open/SolarOpen-2-7b-hf")
+
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
+
+ >>> # Generate
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
+ ```"""
+ outputs: BaseModelOutputWithPast = self.model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ **kwargs,
+ )
+
+ hidden_states = outputs.last_hidden_state
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
+
+ return CausalLMOutputWithPast(
+ loss=loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+__all__ = ["SolarOpenPreTrainedModel", "SolarOpenModel", "SolarOpenForCausalLM"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/solar_open/modular_solar_open.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/solar_open/modular_solar_open.py
new file mode 100644
index 0000000000000000000000000000000000000000..90d4f0c389c086743e75cde217627ea839a001a5
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/solar_open/modular_solar_open.py
@@ -0,0 +1,108 @@
+# Copyright 2026 Upstage and HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch SolarOpen model."""
+
+from huggingface_hub.dataclasses import strict
+from torch import nn
+
+from ...utils import auto_docstring, logging
+from ..glm4_moe.configuration_glm4_moe import Glm4MoeConfig
+from ..glm4_moe.modeling_glm4_moe import (
+ Glm4MoeForCausalLM,
+ Glm4MoeModel,
+ Glm4MoeMoE,
+ Glm4MoePreTrainedModel,
+ Glm4MoeRMSNorm,
+)
+from ..llama.modeling_llama import LlamaAttention, LlamaDecoderLayer
+
+
+logger = logging.get_logger(__name__)
+
+
+@auto_docstring(checkpoint="upstage/Solar-Open-100B")
+@strict
+class SolarOpenConfig(Glm4MoeConfig):
+ r"""
+ n_group (`int`, *optional*, defaults to 1):
+ Number of groups for routed experts.
+ """
+
+ model_type = "solar_open"
+ default_theta = 1_000_000.0
+
+ # Default tensor parallel plan for base model `SolarOpenModel`
+ base_model_tp_plan = {
+ "layers.*.self_attn.q_proj": "colwise",
+ "layers.*.self_attn.k_proj": "colwise",
+ "layers.*.self_attn.v_proj": "colwise",
+ "layers.*.self_attn.o_proj": "rowwise",
+ "layers.*.mlp.experts.gate_up_proj": "packed_colwise",
+ "layers.*.mlp.experts.down_proj": "rowwise",
+ "layers.*.mlp.experts": "moe_tp_experts",
+ }
+
+ vocab_size: int = 196608
+ moe_intermediate_size: int = 1280
+ num_hidden_layers: int = 48
+ num_attention_heads: int = 64
+ head_dim: int = 128
+ num_experts_per_tok: int = 8
+ intermediate_size = AttributeError()
+ first_k_dense_replace = AttributeError()
+ use_qk_norm = AttributeError()
+
+ def __post_init__(self, **kwargs):
+ kwargs.setdefault("partial_rotary_factor", 1.0)
+ super().__post_init__(**kwargs)
+
+
+class SolarOpenDecoderLayer(LlamaDecoderLayer):
+ def __init__(self, config: SolarOpenConfig, layer_idx: int):
+ super().__init__(config, layer_idx)
+ self.mlp = SolarOpenMoE(config)
+
+
+class SolarOpenMoE(Glm4MoeMoE):
+ pass
+
+
+class SolarOpenAttention(LlamaAttention):
+ def __init__(self, config: SolarOpenConfig, layer_idx: int):
+ super().__init__(config, layer_idx)
+ self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
+
+
+class SolarOpenRMSNorm(Glm4MoeRMSNorm):
+ pass
+
+
+class SolarOpenPreTrainedModel(Glm4MoePreTrainedModel):
+ _keys_to_ignore_on_load_unexpected = None
+
+
+class SolarOpenModel(Glm4MoeModel):
+ pass
+
+
+class SolarOpenForCausalLM(Glm4MoeForCausalLM):
+ pass
+
+
+__all__ = [
+ "SolarOpenConfig",
+ "SolarOpenPreTrainedModel",
+ "SolarOpenModel",
+ "SolarOpenForCausalLM",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/squeezebert/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/squeezebert/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..9008fbeae8b089a2dffddacbc2d6995cb56407bc
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/squeezebert/__init__.py
@@ -0,0 +1,28 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_squeezebert import *
+ from .modeling_squeezebert import *
+ from .tokenization_squeezebert import SqueezeBertTokenizer, SqueezeBertTokenizerFast
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/squeezebert/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/squeezebert/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6bf4cd607faf693355c11c36e34cb9bdf962a41f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/squeezebert/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/squeezebert/__pycache__/configuration_squeezebert.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/squeezebert/__pycache__/configuration_squeezebert.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9be8d970d793653c168b3c3f72e9baa07b27312f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/squeezebert/__pycache__/configuration_squeezebert.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/squeezebert/__pycache__/modeling_squeezebert.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/squeezebert/__pycache__/modeling_squeezebert.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e6664be724f5839a88ee85417a55c0a3a0e07ef5
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/squeezebert/__pycache__/modeling_squeezebert.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/squeezebert/__pycache__/tokenization_squeezebert.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/squeezebert/__pycache__/tokenization_squeezebert.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ef59cf19df6169a38f9be6a837b1f272108f3884
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/squeezebert/__pycache__/tokenization_squeezebert.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/squeezebert/configuration_squeezebert.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/squeezebert/configuration_squeezebert.py
new file mode 100644
index 0000000000000000000000000000000000000000..a6e5bbd0816574ba0b3b24ff617ac9aa19191753
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/squeezebert/configuration_squeezebert.py
@@ -0,0 +1,82 @@
+# Copyright 2020 The SqueezeBert authors and The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""SqueezeBERT model configuration"""
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring
+
+
+@auto_docstring(checkpoint="squeezebert/squeezebert-uncased")
+@strict
+class SqueezeBertConfig(PreTrainedConfig):
+ r"""
+ q_groups (`int`, *optional*, defaults to 4):
+ The number of groups in Q layer.
+ k_groups (`int`, *optional*, defaults to 4):
+ The number of groups in K layer.
+ v_groups (`int`, *optional*, defaults to 4):
+ The number of groups in V layer.
+ post_attention_groups (`int`, *optional*, defaults to 1):
+ The number of groups in the first feed forward network layer.
+ intermediate_groups (`int`, *optional*, defaults to 4):
+ The number of groups in the second feed forward network layer.
+ output_groups (`int`, *optional*, defaults to 4):
+ The number of groups in the third feed forward network layer.
+
+ Examples:
+
+ ```python
+ >>> from transformers import SqueezeBertConfig, SqueezeBertModel
+
+ >>> # Initializing a SqueezeBERT configuration
+ >>> configuration = SqueezeBertConfig()
+
+ >>> # Initializing a model (with random weights) from the configuration above
+ >>> model = SqueezeBertModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```
+ """
+
+ model_type = "squeezebert"
+
+ vocab_size: int = 30522
+ hidden_size: int = 768
+ num_hidden_layers: int = 12
+ num_attention_heads: int = 12
+ intermediate_size: int = 3072
+ hidden_act: str = "gelu"
+ hidden_dropout_prob: float | int = 0.1
+ attention_probs_dropout_prob: float | int = 0.1
+ max_position_embeddings: int = 512
+ type_vocab_size: int = 2
+ initializer_range: float = 0.02
+ layer_norm_eps: float = 1e-12
+ pad_token_id: int | None = 0
+ bos_token_id: int | None = None
+ eos_token_id: int | list[int] | None = None
+ embedding_size: int = 768
+ q_groups: int = 4
+ k_groups: int = 4
+ v_groups: int = 4
+ post_attention_groups: int = 1
+ intermediate_groups: int = 4
+ output_groups: int = 4
+ tie_word_embeddings: bool = True
+
+
+__all__ = ["SqueezeBertConfig"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/squeezebert/modeling_squeezebert.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/squeezebert/modeling_squeezebert.py
new file mode 100644
index 0000000000000000000000000000000000000000..658be0fbb6debb4bfa531725065e8379c837ce1f
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/squeezebert/modeling_squeezebert.py
@@ -0,0 +1,927 @@
+# Copyright 2020 The SqueezeBert authors and The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch SqueezeBert model."""
+
+import math
+
+import torch
+from torch import nn
+from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...masking_utils import create_bidirectional_mask
+from ...modeling_outputs import (
+ BaseModelOutput,
+ BaseModelOutputWithPooling,
+ MaskedLMOutput,
+ MultipleChoiceModelOutput,
+ QuestionAnsweringModelOutput,
+ SequenceClassifierOutput,
+ TokenClassifierOutput,
+)
+from ...modeling_utils import PreTrainedModel
+from ...utils import (
+ auto_docstring,
+ logging,
+)
+from .configuration_squeezebert import SqueezeBertConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+class SqueezeBertEmbeddings(nn.Module):
+ """Construct the embeddings from word, position and token_type embeddings."""
+
+ def __init__(self, config):
+ super().__init__()
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.embedding_size, padding_idx=config.pad_token_id)
+ self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.embedding_size)
+ self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.embedding_size)
+
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
+ self.register_buffer(
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
+ )
+
+ def forward(self, input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None):
+ if input_ids is not None:
+ input_shape = input_ids.size()
+ else:
+ input_shape = inputs_embeds.size()[:-1]
+
+ seq_length = input_shape[1]
+
+ if position_ids is None:
+ position_ids = self.position_ids[:, :seq_length]
+
+ if token_type_ids is None:
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
+
+ if inputs_embeds is None:
+ inputs_embeds = self.word_embeddings(input_ids)
+ position_embeddings = self.position_embeddings(position_ids)
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
+
+ embeddings = inputs_embeds + position_embeddings + token_type_embeddings
+ embeddings = self.LayerNorm(embeddings)
+ embeddings = self.dropout(embeddings)
+ return embeddings
+
+
+class MatMulWrapper(nn.Module):
+ """
+ Wrapper for torch.matmul(). This makes flop-counting easier to implement. Note that if you directly call
+ torch.matmul() in your code, the flop counter will typically ignore the flops of the matmul.
+ """
+
+ def __init__(self):
+ super().__init__()
+
+ def forward(self, mat1, mat2):
+ """
+
+ :param inputs: two torch tensors :return: matmul of these tensors
+
+ Here are the typical dimensions found in BERT (the B is optional) mat1.shape: [B, , M, K]
+ mat2.shape: [B, , K, N] output shape: [B, , M, N]
+ """
+ return torch.matmul(mat1, mat2)
+
+
+class SqueezeBertLayerNorm(nn.LayerNorm):
+ """
+ This is a nn.LayerNorm subclass that accepts NCW data layout and performs normalization in the C dimension.
+
+ N = batch C = channels W = sequence length
+ """
+
+ def __init__(self, hidden_size, eps=1e-12):
+ nn.LayerNorm.__init__(self, normalized_shape=hidden_size, eps=eps) # instantiates self.{weight, bias, eps}
+
+ def forward(self, x):
+ x = x.permute(0, 2, 1)
+ x = nn.LayerNorm.forward(self, x)
+ return x.permute(0, 2, 1)
+
+
+class ConvDropoutLayerNorm(nn.Module):
+ """
+ ConvDropoutLayerNorm: Conv, Dropout, LayerNorm
+ """
+
+ def __init__(self, cin, cout, groups, dropout_prob):
+ super().__init__()
+
+ self.conv1d = nn.Conv1d(in_channels=cin, out_channels=cout, kernel_size=1, groups=groups)
+ self.layernorm = SqueezeBertLayerNorm(cout)
+ self.dropout = nn.Dropout(dropout_prob)
+
+ def forward(self, hidden_states, input_tensor):
+ x = self.conv1d(hidden_states)
+ x = self.dropout(x)
+ x = x + input_tensor
+ x = self.layernorm(x)
+ return x
+
+
+class ConvActivation(nn.Module):
+ """
+ ConvActivation: Conv, Activation
+ """
+
+ def __init__(self, cin, cout, groups, act):
+ super().__init__()
+ self.conv1d = nn.Conv1d(in_channels=cin, out_channels=cout, kernel_size=1, groups=groups)
+ self.act = ACT2FN[act]
+
+ def forward(self, x):
+ output = self.conv1d(x)
+ return self.act(output)
+
+
+class SqueezeBertSelfAttention(nn.Module):
+ def __init__(self, config, cin, q_groups=1, k_groups=1, v_groups=1):
+ """
+ config = used for some things; ignored for others (work in progress...) cin = input channels = output channels
+ groups = number of groups to use in conv1d layers
+ """
+ super().__init__()
+ if cin % config.num_attention_heads != 0:
+ raise ValueError(
+ f"cin ({cin}) is not a multiple of the number of attention heads ({config.num_attention_heads})"
+ )
+ self.num_attention_heads = config.num_attention_heads
+ self.attention_head_size = int(cin / config.num_attention_heads)
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
+
+ self.query = nn.Conv1d(in_channels=cin, out_channels=cin, kernel_size=1, groups=q_groups)
+ self.key = nn.Conv1d(in_channels=cin, out_channels=cin, kernel_size=1, groups=k_groups)
+ self.value = nn.Conv1d(in_channels=cin, out_channels=cin, kernel_size=1, groups=v_groups)
+
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
+ self.softmax = nn.Softmax(dim=-1)
+
+ self.matmul_qk = MatMulWrapper()
+ self.matmul_qkv = MatMulWrapper()
+
+ def transpose_for_scores(self, x):
+ """
+ - input: [N, C, W]
+ - output: [N, C1, W, C2] where C1 is the head index, and C2 is one head's contents
+ """
+ new_x_shape = (x.size()[0], self.num_attention_heads, self.attention_head_size, x.size()[-1]) # [N, C1, C2, W]
+ x = x.view(*new_x_shape)
+ return x.permute(0, 1, 3, 2) # [N, C1, C2, W] --> [N, C1, W, C2]
+
+ def transpose_key_for_scores(self, x):
+ """
+ - input: [N, C, W]
+ - output: [N, C1, C2, W] where C1 is the head index, and C2 is one head's contents
+ """
+ new_x_shape = (x.size()[0], self.num_attention_heads, self.attention_head_size, x.size()[-1]) # [N, C1, C2, W]
+ x = x.view(*new_x_shape)
+ # no `permute` needed
+ return x
+
+ def transpose_output(self, x):
+ """
+ - input: [N, C1, W, C2]
+ - output: [N, C, W]
+ """
+ x = x.permute(0, 1, 3, 2).contiguous() # [N, C1, C2, W]
+ new_x_shape = (x.size()[0], self.all_head_size, x.size()[3]) # [N, C, W]
+ x = x.view(*new_x_shape)
+ return x
+
+ def forward(self, hidden_states, attention_mask, output_attentions):
+ """
+ expects hidden_states in [N, C, W] data layout.
+
+ The attention_mask data layout is [N, W], and it does not need to be transposed.
+ """
+ mixed_query_layer = self.query(hidden_states)
+ mixed_key_layer = self.key(hidden_states)
+ mixed_value_layer = self.value(hidden_states)
+
+ query_layer = self.transpose_for_scores(mixed_query_layer)
+ key_layer = self.transpose_key_for_scores(mixed_key_layer)
+ value_layer = self.transpose_for_scores(mixed_value_layer)
+
+ # Take the dot product between "query" and "key" to get the raw attention scores.
+ attention_score = self.matmul_qk(query_layer, key_layer)
+ attention_score = attention_score / math.sqrt(self.attention_head_size)
+ # Apply the attention mask is (precomputed for all layers in BertModel forward() function)
+ if attention_mask is not None:
+ attention_score = attention_score + attention_mask
+
+ # Normalize the attention scores to probabilities.
+ attention_probs = self.softmax(attention_score)
+
+ # This is actually dropping out entire tokens to attend to, which might
+ # seem a bit unusual, but is taken from the original Transformer paper.
+ attention_probs = self.dropout(attention_probs)
+
+ context_layer = self.matmul_qkv(attention_probs, value_layer)
+ context_layer = self.transpose_output(context_layer)
+
+ result = {"context_layer": context_layer}
+ if output_attentions:
+ result["attention_score"] = attention_score
+ return result
+
+
+class SqueezeBertModule(nn.Module):
+ def __init__(self, config):
+ """
+ - hidden_size = input chans = output chans for Q, K, V (they are all the same ... for now) = output chans for
+ the module
+ - intermediate_size = output chans for intermediate layer
+ - groups = number of groups for all layers in the BertModule. (eventually we could change the interface to
+ allow different groups for different layers)
+ """
+ super().__init__()
+
+ c0 = config.hidden_size
+ c1 = config.hidden_size
+ c2 = config.intermediate_size
+ c3 = config.hidden_size
+
+ self.attention = SqueezeBertSelfAttention(
+ config=config, cin=c0, q_groups=config.q_groups, k_groups=config.k_groups, v_groups=config.v_groups
+ )
+ self.post_attention = ConvDropoutLayerNorm(
+ cin=c0, cout=c1, groups=config.post_attention_groups, dropout_prob=config.hidden_dropout_prob
+ )
+ self.intermediate = ConvActivation(cin=c1, cout=c2, groups=config.intermediate_groups, act=config.hidden_act)
+ self.output = ConvDropoutLayerNorm(
+ cin=c2, cout=c3, groups=config.output_groups, dropout_prob=config.hidden_dropout_prob
+ )
+
+ def forward(self, hidden_states, attention_mask, output_attentions):
+ att = self.attention(hidden_states, attention_mask, output_attentions)
+ attention_output = att["context_layer"]
+
+ post_attention_output = self.post_attention(attention_output, hidden_states)
+ intermediate_output = self.intermediate(post_attention_output)
+ layer_output = self.output(intermediate_output, post_attention_output)
+
+ output_dict = {"feature_map": layer_output}
+ if output_attentions:
+ output_dict["attention_score"] = att["attention_score"]
+
+ return output_dict
+
+
+class SqueezeBertEncoder(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+
+ assert config.embedding_size == config.hidden_size, (
+ "If you want embedding_size != intermediate hidden_size, "
+ "please insert a Conv1d layer to adjust the number of channels "
+ "before the first SqueezeBertModule."
+ )
+
+ self.layers = nn.ModuleList(SqueezeBertModule(config) for _ in range(config.num_hidden_layers))
+
+ def forward(
+ self,
+ hidden_states,
+ attention_mask=None,
+ output_attentions=False,
+ output_hidden_states=False,
+ return_dict=True,
+ ):
+ # [batch_size, sequence_length, hidden_size] --> [batch_size, hidden_size, sequence_length]
+ hidden_states = hidden_states.permute(0, 2, 1)
+
+ all_hidden_states = () if output_hidden_states else None
+ all_attentions = () if output_attentions else None
+
+ for layer in self.layers:
+ if output_hidden_states:
+ hidden_states = hidden_states.permute(0, 2, 1)
+ all_hidden_states += (hidden_states,)
+ hidden_states = hidden_states.permute(0, 2, 1)
+
+ layer_output = layer.forward(hidden_states, attention_mask, output_attentions)
+
+ hidden_states = layer_output["feature_map"]
+
+ if output_attentions:
+ all_attentions += (layer_output["attention_score"],)
+
+ # [batch_size, hidden_size, sequence_length] --> [batch_size, sequence_length, hidden_size]
+ hidden_states = hidden_states.permute(0, 2, 1)
+
+ if output_hidden_states:
+ all_hidden_states += (hidden_states,)
+
+ if not return_dict:
+ return tuple(v for v in [hidden_states, all_hidden_states, all_attentions] if v is not None)
+ return BaseModelOutput(
+ last_hidden_state=hidden_states, hidden_states=all_hidden_states, attentions=all_attentions
+ )
+
+
+class SqueezeBertPooler(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.activation = nn.Tanh()
+
+ def forward(self, hidden_states):
+ # We "pool" the model by simply taking the hidden state corresponding
+ # to the first token.
+ first_token_tensor = hidden_states[:, 0]
+ pooled_output = self.dense(first_token_tensor)
+ pooled_output = self.activation(pooled_output)
+ return pooled_output
+
+
+class SqueezeBertPredictionHeadTransform(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ if isinstance(config.hidden_act, str):
+ self.transform_act_fn = ACT2FN[config.hidden_act]
+ else:
+ self.transform_act_fn = config.hidden_act
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+
+ def forward(self, hidden_states):
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.transform_act_fn(hidden_states)
+ hidden_states = self.LayerNorm(hidden_states)
+ return hidden_states
+
+
+class SqueezeBertLMPredictionHead(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.transform = SqueezeBertPredictionHeadTransform(config)
+
+ # The output weights are the same as the input embeddings, but there is
+ # an output-only bias for each token.
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=True)
+
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
+
+ # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
+
+ def forward(self, hidden_states):
+ hidden_states = self.transform(hidden_states)
+ hidden_states = self.decoder(hidden_states)
+ return hidden_states
+
+
+class SqueezeBertOnlyMLMHead(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.predictions = SqueezeBertLMPredictionHead(config)
+
+ def forward(self, sequence_output):
+ prediction_scores = self.predictions(sequence_output)
+ return prediction_scores
+
+
+@auto_docstring
+class SqueezeBertPreTrainedModel(PreTrainedModel):
+ config: SqueezeBertConfig
+ base_model_prefix = "transformer"
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ """Initialize the weights"""
+ super()._init_weights(module)
+ if isinstance(module, SqueezeBertLMPredictionHead):
+ init.zeros_(module.bias)
+ elif isinstance(module, SqueezeBertEmbeddings):
+ init.copy_(module.position_ids, torch.arange(module.position_ids.shape[-1]).expand((1, -1)))
+
+
+@auto_docstring
+class SqueezeBertModel(SqueezeBertPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.embeddings = SqueezeBertEmbeddings(config)
+ self.encoder = SqueezeBertEncoder(config)
+ self.pooler = SqueezeBertPooler(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.embeddings.word_embeddings
+
+ def set_input_embeddings(self, new_embeddings):
+ self.embeddings.word_embeddings = new_embeddings
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ token_type_ids: torch.Tensor | None = None,
+ position_ids: torch.Tensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple | BaseModelOutputWithPooling:
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ if input_ids is not None and inputs_embeds is not None:
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
+ elif input_ids is not None:
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
+ input_shape = input_ids.size()
+ elif inputs_embeds is not None:
+ input_shape = inputs_embeds.size()[:-1]
+ else:
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
+
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
+
+ if attention_mask is None:
+ attention_mask = torch.ones(input_shape, device=device)
+ if token_type_ids is None:
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
+
+ embedding_output = self.embeddings(
+ input_ids=input_ids, position_ids=position_ids, token_type_ids=token_type_ids, inputs_embeds=inputs_embeds
+ )
+
+ attention_mask = create_bidirectional_mask(
+ config=self.config,
+ inputs_embeds=embedding_output,
+ attention_mask=attention_mask,
+ )
+
+ encoder_outputs = self.encoder(
+ hidden_states=embedding_output,
+ attention_mask=attention_mask,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+ sequence_output = encoder_outputs[0]
+ pooled_output = self.pooler(sequence_output)
+
+ if not return_dict:
+ return (sequence_output, pooled_output) + encoder_outputs[1:]
+
+ return BaseModelOutputWithPooling(
+ last_hidden_state=sequence_output,
+ pooler_output=pooled_output,
+ hidden_states=encoder_outputs.hidden_states,
+ attentions=encoder_outputs.attentions,
+ )
+
+
+@auto_docstring
+class SqueezeBertForMaskedLM(SqueezeBertPreTrainedModel):
+ _tied_weights_keys = {
+ "cls.predictions.decoder.bias": "cls.predictions.bias",
+ "cls.predictions.decoder.weight": "transformer.embeddings.word_embeddings.weight",
+ }
+
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.transformer = SqueezeBertModel(config)
+ self.cls = SqueezeBertOnlyMLMHead(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_output_embeddings(self):
+ return self.cls.predictions.decoder
+
+ def set_output_embeddings(self, new_embeddings):
+ self.cls.predictions.decoder = new_embeddings
+ self.cls.predictions.bias = new_embeddings.bias
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ token_type_ids: torch.Tensor | None = None,
+ position_ids: torch.Tensor | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ labels: torch.Tensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple | MaskedLMOutput:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
+ """
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ outputs = self.transformer(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ sequence_output = outputs[0]
+ prediction_scores = self.cls(sequence_output)
+
+ masked_lm_loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss() # -100 index = padding token
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
+
+ if not return_dict:
+ output = (prediction_scores,) + outputs[2:]
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
+
+ return MaskedLMOutput(
+ loss=masked_lm_loss,
+ logits=prediction_scores,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ SqueezeBERT Model transformer with a sequence classification/regression head on top (a linear layer on top of the
+ pooled output) e.g. for GLUE tasks.
+ """
+)
+class SqueezeBertForSequenceClassification(SqueezeBertPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+ self.config = config
+
+ self.transformer = SqueezeBertModel(config)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+ self.classifier = nn.Linear(config.hidden_size, self.config.num_labels)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ token_type_ids: torch.Tensor | None = None,
+ position_ids: torch.Tensor | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ labels: torch.Tensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple | SequenceClassifierOutput:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ outputs = self.transformer(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ pooled_output = outputs[1]
+
+ pooled_output = self.dropout(pooled_output)
+ logits = self.classifier(pooled_output)
+
+ loss = None
+ if labels is not None:
+ if self.config.problem_type is None:
+ if self.num_labels == 1:
+ self.config.problem_type = "regression"
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
+ self.config.problem_type = "single_label_classification"
+ else:
+ self.config.problem_type = "multi_label_classification"
+
+ if self.config.problem_type == "regression":
+ loss_fct = MSELoss()
+ if self.num_labels == 1:
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
+ else:
+ loss = loss_fct(logits, labels)
+ elif self.config.problem_type == "single_label_classification":
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+ elif self.config.problem_type == "multi_label_classification":
+ loss_fct = BCEWithLogitsLoss()
+ loss = loss_fct(logits, labels)
+
+ if not return_dict:
+ output = (logits,) + outputs[2:]
+ return ((loss,) + output) if loss is not None else output
+
+ return SequenceClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+class SqueezeBertForMultipleChoice(SqueezeBertPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.transformer = SqueezeBertModel(config)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+ self.classifier = nn.Linear(config.hidden_size, 1)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ token_type_ids: torch.Tensor | None = None,
+ position_ids: torch.Tensor | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ labels: torch.Tensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple | MultipleChoiceModelOutput:
+ r"""
+ input_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input-ids)
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
+ 1]`:
+
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ position_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
+ config.max_position_embeddings - 1]`.
+
+ [What are position IDs?](../glossary#position-ids)
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_choices, sequence_length, hidden_size)`, *optional*):
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
+ model's internal embedding lookup matrix.
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
+ num_choices-1]` where *num_choices* is the size of the second dimension of the input tensors. (see
+ *input_ids* above)
+ """
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+ num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
+
+ input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
+ attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
+ token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
+ position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
+ inputs_embeds = (
+ inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
+ if inputs_embeds is not None
+ else None
+ )
+
+ outputs = self.transformer(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ pooled_output = outputs[1]
+
+ pooled_output = self.dropout(pooled_output)
+ logits = self.classifier(pooled_output)
+ reshaped_logits = logits.view(-1, num_choices)
+
+ loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(reshaped_logits, labels)
+
+ if not return_dict:
+ output = (reshaped_logits,) + outputs[2:]
+ return ((loss,) + output) if loss is not None else output
+
+ return MultipleChoiceModelOutput(
+ loss=loss,
+ logits=reshaped_logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+class SqueezeBertForTokenClassification(SqueezeBertPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+
+ self.transformer = SqueezeBertModel(config)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ token_type_ids: torch.Tensor | None = None,
+ position_ids: torch.Tensor | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ labels: torch.Tensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple | TokenClassifierOutput:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
+ """
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ outputs = self.transformer(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ sequence_output = outputs[0]
+
+ sequence_output = self.dropout(sequence_output)
+ logits = self.classifier(sequence_output)
+
+ loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+
+ if not return_dict:
+ output = (logits,) + outputs[2:]
+ return ((loss,) + output) if loss is not None else output
+
+ return TokenClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+class SqueezeBertForQuestionAnswering(SqueezeBertPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+
+ self.transformer = SqueezeBertModel(config)
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ token_type_ids: torch.Tensor | None = None,
+ position_ids: torch.Tensor | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ start_positions: torch.Tensor | None = None,
+ end_positions: torch.Tensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple | QuestionAnsweringModelOutput:
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ outputs = self.transformer(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ sequence_output = outputs[0]
+
+ logits = self.qa_outputs(sequence_output)
+ start_logits, end_logits = logits.split(1, dim=-1)
+ start_logits = start_logits.squeeze(-1).contiguous()
+ end_logits = end_logits.squeeze(-1).contiguous()
+
+ total_loss = None
+ if start_positions is not None and end_positions is not None:
+ # If we are on multi-GPU, split add a dimension
+ if len(start_positions.size()) > 1:
+ start_positions = start_positions.squeeze(-1)
+ if len(end_positions.size()) > 1:
+ end_positions = end_positions.squeeze(-1)
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
+ ignored_index = start_logits.size(1)
+ start_positions = start_positions.clamp(0, ignored_index)
+ end_positions = end_positions.clamp(0, ignored_index)
+
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
+ start_loss = loss_fct(start_logits, start_positions)
+ end_loss = loss_fct(end_logits, end_positions)
+ total_loss = (start_loss + end_loss) / 2
+
+ if not return_dict:
+ output = (start_logits, end_logits) + outputs[2:]
+ return ((total_loss,) + output) if total_loss is not None else output
+
+ return QuestionAnsweringModelOutput(
+ loss=total_loss,
+ start_logits=start_logits,
+ end_logits=end_logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+__all__ = [
+ "SqueezeBertForMaskedLM",
+ "SqueezeBertForMultipleChoice",
+ "SqueezeBertForQuestionAnswering",
+ "SqueezeBertForSequenceClassification",
+ "SqueezeBertForTokenClassification",
+ "SqueezeBertModel",
+ "SqueezeBertModule",
+ "SqueezeBertPreTrainedModel",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/squeezebert/tokenization_squeezebert.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/squeezebert/tokenization_squeezebert.py
new file mode 100644
index 0000000000000000000000000000000000000000..043654d90c041726402f4df5fa6bd0f3ab18b477
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/squeezebert/tokenization_squeezebert.py
@@ -0,0 +1,25 @@
+# Copyright 2024 The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Tokenization classes for SqueezeBERT model."""
+
+from ..bert.tokenization_bert import BertTokenizer
+
+
+# SqueezeBertTokenizer is an alias for BertTokenizer
+SqueezeBertTokenizer = BertTokenizer
+
+# SqueezeBertTokenizerFast is an alias for SqueezeBertTokenizer (since BertTokenizer is already a fast tokenizer)
+SqueezeBertTokenizerFast = SqueezeBertTokenizer
+
+__all__ = ["SqueezeBertTokenizer", "SqueezeBertTokenizerFast"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/stablelm/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/stablelm/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..004a82f49cd66857a6d10e614da2451046a1dcad
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/stablelm/__init__.py
@@ -0,0 +1,27 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_stablelm import *
+ from .modeling_stablelm import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/stablelm/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/stablelm/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e0fa42f0d8562b32fc5788793123ab1ebfd644da
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/stablelm/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/stablelm/__pycache__/configuration_stablelm.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/stablelm/__pycache__/configuration_stablelm.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..431f2328f5027f5e481b73f1bd4b0880b06b208a
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/stablelm/__pycache__/configuration_stablelm.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/stablelm/__pycache__/modeling_stablelm.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/stablelm/__pycache__/modeling_stablelm.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9e96134e122e2ab62230515affb8c9ade6431998
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/stablelm/__pycache__/modeling_stablelm.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/stablelm/configuration_stablelm.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/stablelm/configuration_stablelm.py
new file mode 100644
index 0000000000000000000000000000000000000000..1ada7bb9b12378ee5450a6b8393d054ace189c74
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/stablelm/configuration_stablelm.py
@@ -0,0 +1,72 @@
+# Copyright 2024 Stability AI and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""StableLM model configuration"""
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...modeling_rope_utils import RopeParameters
+from ...utils import auto_docstring
+
+
+@auto_docstring(checkpoint="stabilityai/stablelm-3b-4e1t")
+@strict
+class StableLmConfig(PreTrainedConfig):
+ r"""
+ use_parallel_residual (`bool`, *optional*, defaults to `False`):
+ Whether to use a "parallel" formulation in each Transformer layer, which can provide a slight training
+ speedup at large scales.
+ hidden_dropout (`float`, *optional*, defaults to 0.0):
+ The dropout ratio after applying the MLP to the hidden states.
+
+ Example:
+
+ ```python
+ >>> from transformers import StableLmModel, StableLmConfig
+
+ >>> # Initializing a StableLM stablelm-3b style configuration
+ >>> configuration = StableLmConfig()
+ ```"""
+
+ model_type = "stablelm"
+ keys_to_ignore_at_inference = ["past_key_values"]
+
+ vocab_size: int = 50304
+ intermediate_size: int = 6912
+ hidden_size: int = 2560
+ num_hidden_layers: int = 32
+ num_attention_heads: int = 32
+ num_key_value_heads: int = 32
+ hidden_act: str = "silu"
+ max_position_embeddings: int = 4096
+ initializer_range: float = 0.02
+ layer_norm_eps: float = 1.0e-5
+ use_cache: bool = True
+ tie_word_embeddings: bool = False
+ rope_parameters: RopeParameters | dict | None = None
+ use_qkv_bias: bool = False
+ qk_layernorm: bool = False
+ use_parallel_residual: bool = False
+ hidden_dropout: float | int = 0.0
+ attention_dropout: float | int = 0.0
+ bos_token_id: int | None = 0
+ eos_token_id: int | list[int] | None = 0
+ pad_token_id: int | None = None
+
+ def __post_init__(self, **kwargs):
+ kwargs.setdefault("partial_rotary_factor", 0.25) # assign default for BC
+ super().__post_init__(**kwargs)
+
+
+__all__ = ["StableLmConfig"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/stablelm/modeling_stablelm.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/stablelm/modeling_stablelm.py
new file mode 100644
index 0000000000000000000000000000000000000000..328a78a6726086969d9d7b218d5d4107f07aa6c3
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/stablelm/modeling_stablelm.py
@@ -0,0 +1,584 @@
+# Copyright 2024 EleutherAI and the HuggingFace Inc. team. All rights reserved.
+#
+# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
+# and OPT implementations in this library. It has been modified from its
+# original forms to accommodate minor architectural differences compared
+# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch StableLM model."""
+
+from collections.abc import Callable
+from typing import Optional
+
+import torch
+from torch import nn
+
+from ...activations import ACT2FN
+from ...cache_utils import Cache, DynamicCache
+from ...generation import GenerationMixin
+from ...masking_utils import create_causal_mask
+from ...modeling_layers import (
+ GenericForSequenceClassification,
+ GenericForTokenClassification,
+ GradientCheckpointingLayer,
+)
+from ...modeling_outputs import (
+ BaseModelOutputWithPast,
+ CausalLMOutputWithPast,
+)
+from ...modeling_rope_utils import (
+ ROPE_INIT_FUNCTIONS,
+ dynamic_rope_update,
+)
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, logging
+from ...utils.generic import maybe_autocast, merge_with_config_defaults
+from ...utils.output_capturing import capture_outputs
+from .configuration_stablelm import StableLmConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+# Copied from transformers.models.llama.modeling_llama.LlamaRotaryEmbedding with Llama->StableLm
+class StableLmRotaryEmbedding(nn.Module):
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
+
+ def __init__(self, config: StableLmConfig, device=None):
+ super().__init__()
+ self.max_seq_len_cached = config.max_position_embeddings
+ self.original_max_seq_len = config.max_position_embeddings
+
+ self.config = config
+
+ self.rope_type = self.config.rope_parameters["rope_type"]
+ rope_init_fn: Callable = self.compute_default_rope_parameters
+ if self.rope_type != "default":
+ rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
+ inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
+
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
+ self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
+
+ @staticmethod
+ # Ignore copy
+ def compute_default_rope_parameters(
+ config: StableLmConfig | None = None,
+ device: Optional["torch.device"] = None,
+ seq_len: int | None = None,
+ ) -> tuple["torch.Tensor", float]:
+ """
+ Computes the inverse frequencies according to the original RoPE implementation
+ Args:
+ config ([`~transformers.PreTrainedConfig`]):
+ The model configuration.
+ device (`torch.device`):
+ The device to use for initialization of the inverse frequencies.
+ seq_len (`int`, *optional*):
+ The current sequence length. Unused for this type of RoPE.
+ Returns:
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
+ """
+ base = config.rope_parameters["rope_theta"]
+ partial_rotary_factor = config.rope_parameters.get("partial_rotary_factor", 1.0)
+ head_dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
+ dim = int(head_dim * partial_rotary_factor)
+
+ attention_factor = 1.0 # Unused in this type of RoPE
+
+ # Compute the inverse frequencies
+ inv_freq = 1.0 / (
+ base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
+ )
+ return inv_freq, attention_factor
+
+ @torch.no_grad()
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
+ def forward(self, x, position_ids):
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
+ position_ids_expanded = position_ids[:, None, :].float()
+
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
+ with maybe_autocast(device_type=device_type, enabled=False): # Force float32
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
+ emb = torch.cat((freqs, freqs), dim=-1)
+ cos = emb.cos() * self.attention_scaling
+ sin = emb.sin() * self.attention_scaling
+
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
+
+
+# Copied from transformers.models.llama.modeling_llama.rotate_half
+def rotate_half(x):
+ """Rotates half the hidden dims of the input."""
+ x1 = x[..., : x.shape[-1] // 2]
+ x2 = x[..., x.shape[-1] // 2 :]
+ return torch.cat((-x2, x1), dim=-1)
+
+
+# Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
+def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
+ """Applies Rotary Position Embedding to the query and key tensors.
+
+ Args:
+ q (`torch.Tensor`): The query tensor.
+ k (`torch.Tensor`): The key tensor.
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
+ Returns:
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
+ """
+ cos = cos.unsqueeze(unsqueeze_dim)
+ sin = sin.unsqueeze(unsqueeze_dim)
+ q_embed = (q * cos) + (rotate_half(q) * sin)
+ k_embed = (k * cos) + (rotate_half(k) * sin)
+ return q_embed, k_embed
+
+
+# Copied from transformers.models.mistral.modeling_mistral.MistralMLP with Mistral->StableLm
+class StableLmMLP(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.hidden_size = config.hidden_size
+ self.intermediate_size = config.intermediate_size
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
+ self.act_fn = ACT2FN[config.hidden_act]
+
+ def forward(self, x):
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
+ return down_proj
+
+
+class StableLmLayerNormPerHead(nn.Module):
+ def __init__(self, dim, num_heads, eps=1e-5, bias=False):
+ super().__init__()
+ self.dim = dim
+ self.num_heads = num_heads
+ self.norms = nn.ModuleList([nn.LayerNorm(dim, eps=eps, bias=bias) for _ in range(self.num_heads)])
+
+ def forward(self, hidden_states: torch.Tensor):
+ # Split along the num_heads axis to get per-head inputs
+ # [batch_size, num_heads, seq_len, head_dim] -> [batch_size, 1, seq_len, head_dim] * num_heads
+ states_per_heads = torch.split(hidden_states, 1, dim=1)
+ # Normalize and merge the heads back together
+ return torch.cat([norm(hidden_states) for norm, hidden_states in zip(self.norms, states_per_heads)], dim=1)
+
+
+# Copied from transformers.models.llama.modeling_llama.repeat_kv
+def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
+ """
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
+ """
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
+ if n_rep == 1:
+ return hidden_states
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
+
+
+# Copied from transformers.models.llama.modeling_llama.eager_attention_forward
+def eager_attention_forward(
+ module: nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: torch.Tensor | None,
+ scaling: float,
+ dropout: float = 0.0,
+ **kwargs: Unpack[TransformersKwargs],
+):
+ key_states = repeat_kv(key, module.num_key_value_groups)
+ value_states = repeat_kv(value, module.num_key_value_groups)
+
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
+ if attention_mask is not None:
+ attn_weights = attn_weights + attention_mask
+
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
+ attn_output = torch.matmul(attn_weights, value_states)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+
+ return attn_output, attn_weights
+
+
+class StableLmAttention(nn.Module):
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
+
+ def __init__(self, config: StableLmConfig, layer_idx: int | None = None):
+ super().__init__()
+ self.config = config
+ self.layer_idx = layer_idx
+ if layer_idx is None:
+ logger.warning_once(
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
+ "when creating this class."
+ )
+
+ self.hidden_size = config.hidden_size
+ self.num_heads = config.num_attention_heads
+ self.head_dim = self.hidden_size // self.num_heads
+ self.num_key_value_heads = config.num_key_value_heads
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
+
+ self.rotary_ndims = int(self.head_dim * config.rope_parameters["partial_rotary_factor"])
+ self.is_causal = True
+ self.scaling = self.head_dim**-0.5
+
+ if (self.head_dim * self.num_heads) != self.hidden_size:
+ raise ValueError(
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
+ f" and `num_heads`: {self.num_heads})."
+ )
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.use_qkv_bias)
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.use_qkv_bias)
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.use_qkv_bias)
+ self.o_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=False)
+
+ self.qk_layernorm = config.qk_layernorm
+ if self.qk_layernorm:
+ self.q_layernorm = StableLmLayerNormPerHead(self.head_dim, self.num_heads, eps=config.layer_norm_eps)
+ self.k_layernorm = StableLmLayerNormPerHead(
+ self.head_dim, self.num_key_value_heads, eps=config.layer_norm_eps
+ )
+
+ self.attention_dropout = config.attention_dropout
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ output_attentions: bool = False,
+ use_cache: bool = False,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
+ **kwargs,
+ ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
+ bsz, q_len, _ = hidden_states.size()
+
+ query_states = self.q_proj(hidden_states)
+ key_states = self.k_proj(hidden_states)
+ value_states = self.v_proj(hidden_states)
+
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
+
+ if self.qk_layernorm:
+ query_states = self.q_layernorm(query_states)
+ key_states = self.k_layernorm(key_states)
+
+ cos, sin = position_embeddings
+ query_rot, query_pass = (
+ query_states[..., : self.rotary_ndims],
+ query_states[..., self.rotary_ndims :],
+ )
+ key_rot, key_pass = (
+ key_states[..., : self.rotary_ndims],
+ key_states[..., self.rotary_ndims :],
+ )
+ # [batch_size, seq_length, num_heads, head_dim // config.partial_rotary_factor]
+ query_rot, key_rot = apply_rotary_pos_emb(query_rot, key_rot, cos, sin)
+
+ # [batch_size, seq_length, num_heads, head_dim]
+ query_states = torch.cat((query_rot, query_pass), dim=-1)
+ key_states = torch.cat((key_rot, key_pass), dim=-1)
+
+ if past_key_values is not None:
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_states,
+ key_states,
+ value_states,
+ attention_mask,
+ dropout=0.0 if not self.training else self.attention_dropout,
+ scaling=self.scaling,
+ position_ids=position_ids, # pass `position_ids` for FA2
+ **kwargs,
+ )
+
+ attn_output = attn_output.reshape(bsz, q_len, -1)
+ attn_output = self.o_proj(attn_output)
+
+ return attn_output, attn_weights
+
+
+class StableLmDecoderLayer(GradientCheckpointingLayer):
+ def __init__(self, config: StableLmConfig, layer_idx: int):
+ super().__init__()
+ self.use_parallel_residual = config.use_parallel_residual
+ self.hidden_size = config.hidden_size
+ self.self_attn = StableLmAttention(config, layer_idx=layer_idx)
+ self.mlp = StableLmMLP(config)
+ self.input_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.post_attention_layernorm = None
+ if not self.use_parallel_residual:
+ self.post_attention_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ use_cache: bool | None = False,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
+ **kwargs,
+ ) -> torch.Tensor:
+ residual = hidden_states
+
+ hidden_states = self.input_layernorm(hidden_states)
+
+ # Self Attention
+ self_attn_output, _ = self.self_attn(
+ hidden_states=hidden_states,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ position_embeddings=position_embeddings,
+ )
+
+ # copied from transformers.models.gpt_neox.modeling_gpt_neox.GPTNeoXLayer.forward
+ if self.use_parallel_residual:
+ # x = x + attn(ln1(x)) + mlp(ln1(x))
+ # Fully Connected
+ mlp_output = self.mlp(hidden_states)
+ mlp_output = self.dropout(mlp_output)
+ hidden_states = residual + self_attn_output + mlp_output
+ else:
+ # x = x + attn(ln1(x))
+ # x = x + mlp(ln2(x))
+ residual = residual + self_attn_output
+ # Fully Connected
+ mlp_output = self.mlp(self.post_attention_layernorm(residual))
+ mlp_output = self.dropout(mlp_output)
+ hidden_states = residual + mlp_output
+
+ return hidden_states
+
+
+@auto_docstring
+class StableLmPreTrainedModel(PreTrainedModel):
+ config: StableLmConfig
+ base_model_prefix = "model"
+ supports_gradient_checkpointing = True
+ _no_split_modules = ["StableLmDecoderLayer"]
+ _skip_keys_device_placement = ["past_key_values"]
+ _supports_flash_attn = True
+ _supports_sdpa = True
+ _can_compile_fullgraph = True
+ _can_record_outputs = {
+ "hidden_states": StableLmDecoderLayer,
+ "attentions": StableLmAttention,
+ }
+
+
+@auto_docstring
+class StableLmModel(StableLmPreTrainedModel):
+ """
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`StableLmDecoderLayer`]
+
+ Args:
+ config: StableLmConfig
+ """
+
+ def __init__(self, config: StableLmConfig):
+ super().__init__(config)
+ self.padding_idx = config.pad_token_id
+ self.vocab_size = config.vocab_size
+
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
+ self.layers = nn.ModuleList(
+ [StableLmDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
+ )
+ self.norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+
+ self._attn_implementation = config._attn_implementation
+ self.gradient_checkpointing = False
+ self.rotary_emb = StableLmRotaryEmbedding(config=self.config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @merge_with_config_defaults
+ @capture_outputs
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ use_cache: bool | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> BaseModelOutputWithPast:
+ if (input_ids is None) ^ (inputs_embeds is not None):
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
+
+ if use_cache and past_key_values is None:
+ past_key_values = DynamicCache(config=self.config)
+
+ if inputs_embeds is None:
+ inputs_embeds = self.embed_tokens(input_ids)
+
+ if position_ids is None:
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
+ position_ids = position_ids.unsqueeze(0)
+
+ causal_mask = create_causal_mask(
+ config=self.config,
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ position_ids=position_ids,
+ )
+
+ hidden_states = inputs_embeds
+ position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
+
+ for decoder_layer in self.layers:
+ hidden_states = decoder_layer(
+ hidden_states,
+ attention_mask=causal_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ position_embeddings=position_embeddings,
+ **kwargs,
+ )
+
+ hidden_states = self.norm(hidden_states)
+
+ return BaseModelOutputWithPast(
+ last_hidden_state=hidden_states,
+ past_key_values=past_key_values,
+ )
+
+
+# Copied from transformers.models.persimmon.modeling_persimmon.PersimmonForCausalLM with PERSIMMON->STABLELM,Persimmon->StableLm
+class StableLmForCausalLM(StableLmPreTrainedModel, GenerationMixin):
+ _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
+
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.__init__ with LLAMA->STABLELM,Llama->StableLm
+ def __init__(self, config):
+ super().__init__(config)
+ self.model = StableLmModel(config)
+ self.vocab_size = config.vocab_size
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ # Ignore copy
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ use_cache: bool | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> CausalLMOutputWithPast:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
+
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, StableLmForCausalLM
+
+ >>> model = StableLmForCausalLM.from_pretrained("adept/persimmon-8b-base")
+ >>> tokenizer = AutoTokenizer.from_pretrained("adept/persimmon-8b-base")
+
+ >>> prompt = "human: Hey, what should I eat for dinner?"
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
+
+ >>> # Generate
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
+ 'human: Hey, what should I eat for dinner?\n\ncat: 🐱\n\nhuman: 😐\n\n'
+ ```"""
+ outputs: BaseModelOutputWithPast = self.model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ **kwargs,
+ )
+
+ hidden_states = outputs.last_hidden_state
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(logits, labels, vocab_size=self.config.vocab_size, **kwargs)
+
+ return CausalLMOutputWithPast(
+ loss=loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+class StableLmForSequenceClassification(GenericForSequenceClassification, StableLmPreTrainedModel): ...
+
+
+class StableLmForTokenClassification(GenericForTokenClassification, StableLmPreTrainedModel): ...
+
+
+__all__ = [
+ "StableLmForCausalLM",
+ "StableLmModel",
+ "StableLmPreTrainedModel",
+ "StableLmForSequenceClassification",
+ "StableLmForTokenClassification",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/starcoder2/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/starcoder2/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8fa55c8dae8d625253459cb19e2160a9642b57ad
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/starcoder2/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/starcoder2/__pycache__/configuration_starcoder2.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/starcoder2/__pycache__/configuration_starcoder2.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cab1cdc0044ed994d0f4f8e924e1579c68eb127e
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/starcoder2/__pycache__/configuration_starcoder2.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/starcoder2/__pycache__/modeling_starcoder2.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/starcoder2/__pycache__/modeling_starcoder2.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..476bcdf806237f82527881d1c02fcfe2f0517e09
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/starcoder2/__pycache__/modeling_starcoder2.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/starcoder2/__pycache__/modular_starcoder2.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/starcoder2/__pycache__/modular_starcoder2.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7cadcaafb9cce8ac183ae43113ec72fd82086e35
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/starcoder2/__pycache__/modular_starcoder2.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/swiftformer/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/swiftformer/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..b239996fb976c5135453f784d7483eb81eee2d3d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/swiftformer/__init__.py
@@ -0,0 +1,27 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_swiftformer import *
+ from .modeling_swiftformer import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/swiftformer/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/swiftformer/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2dc3bc950fe2b8fbf7fc6e76da6e18ef007f43b4
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/swiftformer/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/swiftformer/__pycache__/configuration_swiftformer.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/swiftformer/__pycache__/configuration_swiftformer.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f17aae08a23fc012f0a9a1f9099718fd0babaa49
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/swiftformer/__pycache__/configuration_swiftformer.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/swiftformer/__pycache__/modeling_swiftformer.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/swiftformer/__pycache__/modeling_swiftformer.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8cd106a8de5eddad42d2f3c044501a6d9f85ee07
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/swiftformer/__pycache__/modeling_swiftformer.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/swiftformer/configuration_swiftformer.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/swiftformer/configuration_swiftformer.py
new file mode 100644
index 0000000000000000000000000000000000000000..a8940c68dd96c9da87ef4f7ad33a922a11630118
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/swiftformer/configuration_swiftformer.py
@@ -0,0 +1,78 @@
+# Copyright 2023 MBZUAI and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""SwiftFormer model configuration"""
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring
+
+
+@auto_docstring(checkpoint="MBZUAI/swiftformer-xs")
+@strict
+class SwiftFormerConfig(PreTrainedConfig):
+ r"""
+ embed_dims (`list[int]`, *optional*, defaults to `[48, 56, 112, 220]`):
+ The embedding dimension at each stage
+ downsamples (`list[bool]`, *optional*, defaults to `[True, True, True, True]`):
+ Whether or not to downsample inputs between two stages.
+ down_patch_size (`int`, *optional*, defaults to 3):
+ The size of patches in downsampling layers.
+ down_stride (`int`, *optional*, defaults to 2):
+ The stride of convolution kernels in downsampling layers.
+ down_pad (`int`, *optional*, defaults to 1):
+ Padding in downsampling layers.
+ drop_mlp_rate (`float`, *optional*, defaults to 0.0):
+ Dropout rate for the MLP component of SwiftFormer.
+ drop_conv_encoder_rate (`float`, *optional*, defaults to 0.0):
+ Dropout rate for the ConvEncoder component of SwiftFormer.
+ use_layer_scale (`bool`, *optional*, defaults to `True`):
+ Whether to scale outputs from token mixers.
+
+ Example:
+
+ ```python
+ >>> from transformers import SwiftFormerConfig, SwiftFormerModel
+
+ >>> # Initializing a SwiftFormer swiftformer-base-patch16-224 style configuration
+ >>> configuration = SwiftFormerConfig()
+
+ >>> # Initializing a model (with random weights) from the swiftformer-base-patch16-224 style configuration
+ >>> model = SwiftFormerModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "swiftformer"
+
+ image_size: int | list[int] | tuple[int, int] = 224
+ num_channels: int = 3
+ depths: list[int] | tuple[int, ...] = (3, 3, 6, 4)
+ embed_dims: list[int] | tuple[int, ...] = (48, 56, 112, 220)
+ mlp_ratio: int = 4
+ downsamples: list[bool] | tuple[bool, ...] = (True, True, True, True)
+ hidden_act: str = "gelu"
+ down_patch_size: int | list[int] | tuple[int, int] = 3
+ down_stride: int = 2
+ down_pad: int = 1
+ drop_path_rate: float | int = 0.0
+ drop_mlp_rate: float | int = 0.0
+ drop_conv_encoder_rate: float | int = 0.0
+ use_layer_scale: bool = True
+ layer_scale_init_value: float = 1e-5
+ batch_norm_eps: float = 1e-5
+
+
+__all__ = ["SwiftFormerConfig"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/swiftformer/modeling_swiftformer.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/swiftformer/modeling_swiftformer.py
new file mode 100644
index 0000000000000000000000000000000000000000..9d16e85c0bb2f7d1acea2f6c0b6a02ca287b2783
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/swiftformer/modeling_swiftformer.py
@@ -0,0 +1,521 @@
+# Copyright 2023 MBZUAI and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch SwiftFormer model."""
+
+import collections.abc
+
+import torch
+from torch import nn
+
+from ... import initialization as init
+from ...activations import ACT2CLS
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import BaseModelOutputWithNoAttention, ImageClassifierOutputWithNoAttention
+from ...modeling_utils import PreTrainedModel
+from ...utils import auto_docstring, logging
+from .configuration_swiftformer import SwiftFormerConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+class SwiftFormerPatchEmbedding(nn.Module):
+ """
+ Patch Embedding Layer constructed of two 2D convolutional layers.
+
+ Input: tensor of shape `[batch_size, in_channels, height, width]`
+
+ Output: tensor of shape `[batch_size, out_channels, height/4, width/4]`
+ """
+
+ def __init__(self, config: SwiftFormerConfig):
+ super().__init__()
+
+ in_chs = config.num_channels
+ out_chs = config.embed_dims[0]
+ self.patch_embedding = nn.Sequential(
+ nn.Conv2d(in_chs, out_chs // 2, kernel_size=3, stride=2, padding=1),
+ nn.BatchNorm2d(out_chs // 2, eps=config.batch_norm_eps),
+ nn.ReLU(),
+ nn.Conv2d(out_chs // 2, out_chs, kernel_size=3, stride=2, padding=1),
+ nn.BatchNorm2d(out_chs, eps=config.batch_norm_eps),
+ nn.ReLU(),
+ )
+
+ def forward(self, x):
+ return self.patch_embedding(x)
+
+
+class SwiftFormerEmbeddings(nn.Module):
+ """
+ Embeddings layer consisting of a single 2D convolutional and batch normalization layer.
+
+ Input: tensor of shape `[batch_size, channels, height, width]`
+
+ Output: tensor of shape `[batch_size, channels, height/stride, width/stride]`
+ """
+
+ def __init__(self, config: SwiftFormerConfig, index: int):
+ super().__init__()
+
+ patch_size = config.down_patch_size
+ stride = config.down_stride
+ padding = config.down_pad
+ embed_dims = config.embed_dims
+
+ in_chans = embed_dims[index]
+ embed_dim = embed_dims[index + 1]
+
+ patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
+ stride = stride if isinstance(stride, collections.abc.Iterable) else (stride, stride)
+ padding = padding if isinstance(padding, collections.abc.Iterable) else (padding, padding)
+
+ self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=stride, padding=padding)
+ self.norm = nn.BatchNorm2d(embed_dim, eps=config.batch_norm_eps)
+
+ def forward(self, x):
+ x = self.proj(x)
+ x = self.norm(x)
+ return x
+
+
+class SwiftFormerConvEncoder(nn.Module):
+ """
+ `SwiftFormerConvEncoder` with 3*3 and 1*1 convolutions.
+
+ Input: tensor of shape `[batch_size, channels, height, width]`
+
+ Output: tensor of shape `[batch_size, channels, height, width]`
+ """
+
+ def __init__(self, config: SwiftFormerConfig, dim: int):
+ super().__init__()
+ hidden_dim = int(config.mlp_ratio * dim)
+
+ self.depth_wise_conv = nn.Conv2d(dim, dim, kernel_size=3, padding=1, groups=dim)
+ self.norm = nn.BatchNorm2d(dim, eps=config.batch_norm_eps)
+ self.point_wise_conv1 = nn.Conv2d(dim, hidden_dim, kernel_size=1)
+ self.act = nn.GELU()
+ self.point_wise_conv2 = nn.Conv2d(hidden_dim, dim, kernel_size=1)
+ self.drop_path = nn.Dropout(p=config.drop_conv_encoder_rate)
+ self.layer_scale = nn.Parameter(torch.ones(dim).unsqueeze(-1).unsqueeze(-1), requires_grad=True)
+
+ def forward(self, x):
+ input = x
+ x = self.depth_wise_conv(x)
+ x = self.norm(x)
+ x = self.point_wise_conv1(x)
+ x = self.act(x)
+ x = self.point_wise_conv2(x)
+ x = input + self.drop_path(self.layer_scale * x)
+ return x
+
+
+class SwiftFormerMlp(nn.Module):
+ """
+ MLP layer with 1*1 convolutions.
+
+ Input: tensor of shape `[batch_size, channels, height, width]`
+
+ Output: tensor of shape `[batch_size, channels, height, width]`
+ """
+
+ def __init__(self, config: SwiftFormerConfig, in_features: int):
+ super().__init__()
+ hidden_features = int(in_features * config.mlp_ratio)
+ self.norm1 = nn.BatchNorm2d(in_features, eps=config.batch_norm_eps)
+ self.fc1 = nn.Conv2d(in_features, hidden_features, 1)
+ act_layer = ACT2CLS[config.hidden_act]
+ self.act = act_layer()
+ self.fc2 = nn.Conv2d(hidden_features, in_features, 1)
+ self.drop = nn.Dropout(p=config.drop_mlp_rate)
+
+ def forward(self, x):
+ x = self.norm1(x)
+ x = self.fc1(x)
+ x = self.act(x)
+ x = self.drop(x)
+ x = self.fc2(x)
+ x = self.drop(x)
+ return x
+
+
+class SwiftFormerEfficientAdditiveAttention(nn.Module):
+ """
+ Efficient Additive Attention module for SwiftFormer.
+
+ Input: tensor of shape `[batch_size, channels, height, width]`
+
+ Output: tensor of shape `[batch_size, channels, height, width]`
+ """
+
+ def __init__(self, config: SwiftFormerConfig, dim: int = 512):
+ super().__init__()
+
+ self.to_query = nn.Linear(dim, dim)
+ self.to_key = nn.Linear(dim, dim)
+
+ self.w_g = nn.Parameter(torch.randn(dim, 1))
+ self.scale_factor = dim**-0.5
+ self.proj = nn.Linear(dim, dim)
+ self.final = nn.Linear(dim, dim)
+
+ def forward(self, x):
+ query = self.to_query(x)
+ key = self.to_key(x)
+
+ query = torch.nn.functional.normalize(query, dim=-1)
+ key = torch.nn.functional.normalize(key, dim=-1)
+
+ query_weight = query @ self.w_g
+ scaled_query_weight = query_weight * self.scale_factor
+ scaled_query_weight = scaled_query_weight.softmax(dim=-1)
+
+ global_queries = torch.sum(scaled_query_weight * query, dim=1)
+ global_queries = global_queries.unsqueeze(1).repeat(1, key.shape[1], 1)
+
+ out = self.proj(global_queries * key) + query
+ out = self.final(out)
+
+ return out
+
+
+class SwiftFormerLocalRepresentation(nn.Module):
+ """
+ Local Representation module for SwiftFormer that is implemented by 3*3 depth-wise and point-wise convolutions.
+
+ Input: tensor of shape `[batch_size, channels, height, width]`
+
+ Output: tensor of shape `[batch_size, channels, height, width]`
+ """
+
+ def __init__(self, config: SwiftFormerConfig, dim: int):
+ super().__init__()
+
+ self.depth_wise_conv = nn.Conv2d(dim, dim, kernel_size=3, padding=1, groups=dim)
+ self.norm = nn.BatchNorm2d(dim, eps=config.batch_norm_eps)
+ self.point_wise_conv1 = nn.Conv2d(dim, dim, kernel_size=1)
+ self.act = nn.GELU()
+ self.point_wise_conv2 = nn.Conv2d(dim, dim, kernel_size=1)
+ self.drop_path = nn.Identity()
+ self.layer_scale = nn.Parameter(torch.ones(dim).unsqueeze(-1).unsqueeze(-1), requires_grad=True)
+
+ def forward(self, x):
+ input = x
+ x = self.depth_wise_conv(x)
+ x = self.norm(x)
+ x = self.point_wise_conv1(x)
+ x = self.act(x)
+ x = self.point_wise_conv2(x)
+ x = input + self.drop_path(self.layer_scale * x)
+ return x
+
+
+# Copied from transformers.models.swin.modular_swin.SwinDropPath with SwinDropPath->SwiftFormerDropPath
+class SwiftFormerDropPath(nn.Module):
+ """Stochastic depth (DropPath) per sample, for residual blocks.
+
+ Identity when ``drop_prob`` is 0 or outside training. See `Deep Networks with Stochastic Depth
+ `_.
+ """
+
+ def __init__(self, drop_prob: float = 0.0) -> None:
+ super().__init__()
+ self.drop_prob = drop_prob
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ if self.drop_prob == 0.0 or not self.training:
+ return hidden_states
+ keep_prob = 1 - self.drop_prob
+ shape = (hidden_states.shape[0],) + (1,) * (hidden_states.ndim - 1)
+ random_tensor = torch.rand(shape, dtype=hidden_states.dtype, device=hidden_states.device)
+ random_tensor = torch.floor(random_tensor + keep_prob)
+ return hidden_states.div(keep_prob) * random_tensor
+
+ def extra_repr(self) -> str:
+ return f"p={self.drop_prob}"
+
+
+class SwiftFormerEncoderBlock(nn.Module):
+ """
+ SwiftFormer Encoder Block for SwiftFormer. It consists of (1) Local representation module, (2)
+ SwiftFormerEfficientAdditiveAttention, and (3) MLP block.
+
+ Input: tensor of shape `[batch_size, channels, height, width]`
+
+ Output: tensor of shape `[batch_size, channels,height, width]`
+ """
+
+ def __init__(self, config: SwiftFormerConfig, dim: int, drop_path: float = 0.0) -> None:
+ super().__init__()
+
+ layer_scale_init_value = config.layer_scale_init_value
+ use_layer_scale = config.use_layer_scale
+
+ self.local_representation = SwiftFormerLocalRepresentation(config, dim=dim)
+ self.attn = SwiftFormerEfficientAdditiveAttention(config, dim=dim)
+ self.linear = SwiftFormerMlp(config, in_features=dim)
+ self.drop_path = SwiftFormerDropPath(drop_path) if drop_path > 0.0 else nn.Identity()
+ self.use_layer_scale = use_layer_scale
+ if use_layer_scale:
+ self.layer_scale_1 = nn.Parameter(
+ layer_scale_init_value * torch.ones(dim).unsqueeze(-1).unsqueeze(-1), requires_grad=True
+ )
+ self.layer_scale_2 = nn.Parameter(
+ layer_scale_init_value * torch.ones(dim).unsqueeze(-1).unsqueeze(-1), requires_grad=True
+ )
+
+ def forward(self, x):
+ x = self.local_representation(x)
+ batch_size, channels, height, width = x.shape
+ res = self.attn(x.permute(0, 2, 3, 1).reshape(batch_size, height * width, channels))
+ res = res.reshape(batch_size, height, width, channels).permute(0, 3, 1, 2)
+ if self.use_layer_scale:
+ x = x + self.drop_path(self.layer_scale_1 * res)
+ x = x + self.drop_path(self.layer_scale_2 * self.linear(x))
+ else:
+ x = x + self.drop_path(res)
+ x = x + self.drop_path(self.linear(x))
+ return x
+
+
+class SwiftFormerStage(GradientCheckpointingLayer):
+ """
+ A Swiftformer stage consisting of a series of `SwiftFormerConvEncoder` blocks and a final
+ `SwiftFormerEncoderBlock`.
+
+ Input: tensor in shape `[batch_size, channels, height, width]`
+
+ Output: tensor in shape `[batch_size, channels, height, width]`
+ """
+
+ def __init__(self, config: SwiftFormerConfig, index: int) -> None:
+ super().__init__()
+
+ layer_depths = config.depths
+ dim = config.embed_dims[index]
+ depth = layer_depths[index]
+
+ blocks = []
+ for block_idx in range(depth):
+ block_dpr = config.drop_path_rate * (block_idx + sum(layer_depths[:index])) / (sum(layer_depths) - 1)
+
+ if depth - block_idx <= 1:
+ blocks.append(SwiftFormerEncoderBlock(config, dim=dim, drop_path=block_dpr))
+ else:
+ blocks.append(SwiftFormerConvEncoder(config, dim=dim))
+
+ self.blocks = nn.ModuleList(blocks)
+
+ def forward(self, input):
+ for block in self.blocks:
+ input = block(input)
+ return input
+
+
+class SwiftFormerEncoder(nn.Module):
+ def __init__(self, config: SwiftFormerConfig) -> None:
+ super().__init__()
+ self.config = config
+
+ embed_dims = config.embed_dims
+ downsamples = config.downsamples
+ layer_depths = config.depths
+
+ # Transformer model
+ network = []
+ for i in range(len(layer_depths)):
+ stage = SwiftFormerStage(config=config, index=i)
+ network.append(stage)
+ if i >= len(layer_depths) - 1:
+ break
+ if downsamples[i] or embed_dims[i] != embed_dims[i + 1]:
+ # downsampling between two stages
+ network.append(SwiftFormerEmbeddings(config, index=i))
+ self.network = nn.ModuleList(network)
+
+ self.gradient_checkpointing = False
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ ) -> tuple | BaseModelOutputWithNoAttention:
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ all_hidden_states = (hidden_states,) if output_hidden_states else None
+
+ for block in self.network:
+ hidden_states = block(hidden_states)
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ if not return_dict:
+ return tuple(v for v in [hidden_states, all_hidden_states] if v is not None)
+
+ return BaseModelOutputWithNoAttention(
+ last_hidden_state=hidden_states,
+ hidden_states=all_hidden_states,
+ )
+
+
+@auto_docstring
+class SwiftFormerPreTrainedModel(PreTrainedModel):
+ config: SwiftFormerConfig
+ base_model_prefix = "swiftformer"
+ main_input_name = "pixel_values"
+ input_modalities = ("image",)
+ supports_gradient_checkpointing = True
+ _no_split_modules = ["SwiftFormerEncoderBlock"]
+
+ @torch.no_grad()
+ def _init_weights(self, module: nn.Module) -> None:
+ """Initialize the weights"""
+ if isinstance(module, (nn.Conv2d, nn.Linear)):
+ init.trunc_normal_(module.weight, std=0.02)
+ if module.bias is not None:
+ init.constant_(module.bias, 0)
+ elif isinstance(module, (nn.LayerNorm, nn.BatchNorm2d)):
+ init.constant_(module.bias, 0)
+ init.constant_(module.weight, 1.0)
+ if getattr(module, "running_mean", None) is not None:
+ init.zeros_(module.running_mean)
+ init.ones_(module.running_var)
+ init.zeros_(module.num_batches_tracked)
+ elif isinstance(module, (SwiftFormerConvEncoder, SwiftFormerLocalRepresentation)):
+ init.ones_(module.layer_scale)
+ elif isinstance(module, SwiftFormerEncoderBlock):
+ if self.config.use_layer_scale:
+ init.constant_(module.layer_scale_1, self.config.layer_scale_init_value)
+ init.constant_(module.layer_scale_2, self.config.layer_scale_init_value)
+ elif isinstance(module, SwiftFormerEfficientAdditiveAttention):
+ init.normal_(module.w_g)
+
+
+@auto_docstring
+class SwiftFormerModel(SwiftFormerPreTrainedModel):
+ def __init__(self, config: SwiftFormerConfig):
+ super().__init__(config)
+ self.config = config
+
+ self.patch_embed = SwiftFormerPatchEmbedding(config)
+ self.encoder = SwiftFormerEncoder(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: torch.Tensor | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple | BaseModelOutputWithNoAttention:
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ if pixel_values is None:
+ raise ValueError("You have to specify pixel_values")
+
+ embedding_output = self.patch_embed(pixel_values)
+ encoder_outputs = self.encoder(
+ embedding_output,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ if not return_dict:
+ return tuple(v for v in encoder_outputs if v is not None)
+
+ return BaseModelOutputWithNoAttention(
+ last_hidden_state=encoder_outputs.last_hidden_state,
+ hidden_states=encoder_outputs.hidden_states,
+ )
+
+
+@auto_docstring
+class SwiftFormerForImageClassification(SwiftFormerPreTrainedModel):
+ def __init__(self, config: SwiftFormerConfig) -> None:
+ super().__init__(config)
+
+ embed_dims = config.embed_dims
+
+ self.num_labels = config.num_labels
+ self.swiftformer = SwiftFormerModel(config)
+
+ # Classifier head
+ self.norm = nn.BatchNorm2d(embed_dims[-1], eps=config.batch_norm_eps)
+ self.head = nn.Linear(embed_dims[-1], self.num_labels) if self.num_labels > 0 else nn.Identity()
+ self.dist_head = nn.Linear(embed_dims[-1], self.num_labels) if self.num_labels > 0 else nn.Identity()
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: torch.Tensor | None = None,
+ labels: torch.Tensor | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple | ImageClassifierOutputWithNoAttention:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ # run base model
+ outputs = self.swiftformer(
+ pixel_values,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ sequence_output = outputs.last_hidden_state if return_dict else outputs[0]
+
+ # run classification head
+ sequence_output = self.norm(sequence_output)
+ sequence_output = sequence_output.flatten(2).mean(-1)
+ cls_out = self.head(sequence_output)
+ distillation_out = self.dist_head(sequence_output)
+ logits = (cls_out + distillation_out) / 2
+
+ # calculate loss
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(labels, logits, self.config)
+
+ if not return_dict:
+ output = (logits,) + outputs[1:]
+ return ((loss,) + output) if loss is not None else output
+
+ return ImageClassifierOutputWithNoAttention(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ )
+
+
+__all__ = ["SwiftFormerForImageClassification", "SwiftFormerModel", "SwiftFormerPreTrainedModel"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/swinv2/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/swinv2/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..172f1573f1eb1bca4893b2495879346c0b044b9c
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/swinv2/__init__.py
@@ -0,0 +1,27 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_swinv2 import *
+ from .modeling_swinv2 import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/swinv2/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/swinv2/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..85829fba5a6084f1fc233850281489493671f4a7
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/swinv2/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/swinv2/__pycache__/configuration_swinv2.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/swinv2/__pycache__/configuration_swinv2.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2fb445b93cac8e405e664f6c0c27aaa8a346695b
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/swinv2/__pycache__/configuration_swinv2.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/swinv2/__pycache__/modeling_swinv2.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/swinv2/__pycache__/modeling_swinv2.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..60f167d5edde9db71c35cb7d582891a752fe67a6
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/swinv2/__pycache__/modeling_swinv2.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/swinv2/configuration_swinv2.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/swinv2/configuration_swinv2.py
new file mode 100644
index 0000000000000000000000000000000000000000..81510e4e9e26bfb8a94c35f434034a0704d2e7ab
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/swinv2/configuration_swinv2.py
@@ -0,0 +1,89 @@
+# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Swinv2 Transformer model configuration"""
+
+from huggingface_hub.dataclasses import strict
+
+from ...backbone_utils import BackboneConfigMixin
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring
+
+
+@auto_docstring(checkpoint="microsoft/swinv2-tiny-patch4-window8-256")
+@strict
+class Swinv2Config(BackboneConfigMixin, PreTrainedConfig):
+ r"""
+ window_size (`int`, *optional*, defaults to 7):
+ Size of windows.
+ pretrained_window_sizes (`list(int)`, *optional*, defaults to `[0, 0, 0, 0]`):
+ Size of windows during pretraining.
+ encoder_stride (`int`, *optional*, defaults to 32):
+ Factor to increase the spatial resolution by in the decoder head for masked image modeling.
+
+ Example:
+
+ ```python
+ >>> from transformers import Swinv2Config, Swinv2Model
+
+ >>> # Initializing a Swinv2 microsoft/swinv2-tiny-patch4-window8-256 style configuration
+ >>> configuration = Swinv2Config()
+
+ >>> # Initializing a model (with random weights) from the microsoft/swinv2-tiny-patch4-window8-256 style configuration
+ >>> model = Swinv2Model(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "swinv2"
+
+ attribute_map = {
+ "num_attention_heads": "num_heads",
+ "num_hidden_layers": "num_layers",
+ }
+
+ image_size: int | list[int] | tuple[int, int] = 224
+ patch_size: int | list[int] | tuple[int, int] = 4
+ num_channels: int = 3
+ embed_dim: int = 96
+ depths: list[int] | tuple[int, ...] = (2, 2, 6, 2)
+ num_heads: list[int] | tuple[int, ...] = (3, 6, 12, 24)
+ window_size: int = 7
+ pretrained_window_sizes: list[int] | tuple[int, ...] = (0, 0, 0, 0)
+ mlp_ratio: float = 4.0
+ qkv_bias: bool = True
+ hidden_dropout_prob: float | int = 0.0
+ attention_probs_dropout_prob: float | int = 0.0
+ drop_path_rate: float | int = 0.1
+ hidden_act: str = "gelu"
+ use_absolute_embeddings: bool = False
+ initializer_range: float = 0.02
+ layer_norm_eps: float = 1e-5
+ encoder_stride: int = 32
+ _out_features: list[str] | None = None
+ _out_indices: list[int] | None = None
+
+ def __post_init__(self, **kwargs):
+ self.num_layers = len(self.depths)
+ self.stage_names = ["stem"] + [f"stage{idx}" for idx in range(1, len(self.depths) + 1)]
+ self.set_output_features_output_indices(
+ out_indices=kwargs.pop("out_indices", None), out_features=kwargs.pop("out_features", None)
+ )
+ # we set the hidden_size attribute in order to make Swinv2 work with VisionEncoderDecoderModel
+ # this indicates the channel dimension after the last stage of the model
+ self.hidden_size = int(self.embed_dim * 2 ** (len(self.depths) - 1))
+ super().__post_init__(**kwargs)
+
+
+__all__ = ["Swinv2Config"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/swinv2/modeling_swinv2.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/swinv2/modeling_swinv2.py
new file mode 100644
index 0000000000000000000000000000000000000000..779e6f55f606be08fa6d47baa2ec3df82ac33f7f
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/swinv2/modeling_swinv2.py
@@ -0,0 +1,1280 @@
+# Copyright 2022 Microsoft Research and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch Swinv2 Transformer model."""
+
+import collections.abc
+import math
+from dataclasses import dataclass
+
+import torch
+from torch import Tensor, nn
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...backbone_utils import BackboneMixin, filter_output_hidden_states
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import BackboneOutput
+from ...modeling_utils import PreTrainedModel
+from ...utils import ModelOutput, auto_docstring, logging, torch_int
+from ...utils.generic import can_return_tuple
+from .configuration_swinv2 import Swinv2Config
+
+
+logger = logging.get_logger(__name__)
+
+
+# Swinv2PatchEmbeddings and Swinv2PatchMerging are from https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/swin_transformer_v2.py.
+
+
+@auto_docstring(
+ custom_intro="""
+ Swinv2 encoder's outputs, with potential hidden states and attentions.
+ """
+)
+@dataclass
+# Copied from transformers.models.swin.modeling_swin.SwinEncoderOutput with Swin->Swinv2
+class Swinv2EncoderOutput(ModelOutput):
+ r"""
+ reshaped_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
+ shape `(batch_size, hidden_size, height, width)`.
+
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs reshaped to
+ include the spatial dimensions.
+ """
+
+ last_hidden_state: torch.FloatTensor | None = None
+ hidden_states: tuple[torch.FloatTensor, ...] | None = None
+ attentions: tuple[torch.FloatTensor, ...] | None = None
+ reshaped_hidden_states: tuple[torch.FloatTensor, ...] | None = None
+
+
+@auto_docstring(
+ custom_intro="""
+ Swinv2 model's outputs that also contains a pooling of the last hidden states.
+ """
+)
+@dataclass
+# Copied from transformers.models.swin.modeling_swin.SwinModelOutput with Swin->Swinv2
+class Swinv2ModelOutput(ModelOutput):
+ r"""
+ pooler_output (`torch.FloatTensor` of shape `(batch_size, hidden_size)`, *optional*, returned when `add_pooling_layer=True` is passed):
+ Average pooling of the last layer hidden-state.
+ reshaped_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
+ shape `(batch_size, hidden_size, height, width)`.
+
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs reshaped to
+ include the spatial dimensions.
+ """
+
+ last_hidden_state: torch.FloatTensor | None = None
+ pooler_output: torch.FloatTensor | None = None
+ hidden_states: tuple[torch.FloatTensor, ...] | None = None
+ attentions: tuple[torch.FloatTensor, ...] | None = None
+ reshaped_hidden_states: tuple[torch.FloatTensor, ...] | None = None
+
+
+@auto_docstring(
+ custom_intro="""
+ Swinv2 masked image model outputs.
+ """
+)
+@dataclass
+# Copied from transformers.models.swin.modeling_swin.SwinMaskedImageModelingOutput with Swin->Swinv2
+class Swinv2MaskedImageModelingOutput(ModelOutput):
+ r"""
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `bool_masked_pos` is provided):
+ Masked image modeling (MLM) loss.
+ reconstruction (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
+ Reconstructed pixel values.
+ reshaped_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
+ shape `(batch_size, hidden_size, height, width)`.
+
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs reshaped to
+ include the spatial dimensions.
+ """
+
+ loss: torch.FloatTensor | None = None
+ reconstruction: torch.FloatTensor | None = None
+ hidden_states: tuple[torch.FloatTensor, ...] | None = None
+ attentions: tuple[torch.FloatTensor, ...] | None = None
+ reshaped_hidden_states: tuple[torch.FloatTensor, ...] | None = None
+
+
+@auto_docstring(
+ custom_intro="""
+ Swinv2 outputs for image classification.
+ """
+)
+@dataclass
+# Copied from transformers.models.swin.modeling_swin.SwinImageClassifierOutput with Swin->Swinv2
+class Swinv2ImageClassifierOutput(ModelOutput):
+ r"""
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
+ Classification (or regression if config.num_labels==1) loss.
+ logits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`):
+ Classification (or regression if config.num_labels==1) scores (before SoftMax).
+ reshaped_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
+ shape `(batch_size, hidden_size, height, width)`.
+
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs reshaped to
+ include the spatial dimensions.
+ """
+
+ loss: torch.FloatTensor | None = None
+ logits: torch.FloatTensor | None = None
+ hidden_states: tuple[torch.FloatTensor, ...] | None = None
+ attentions: tuple[torch.FloatTensor, ...] | None = None
+ reshaped_hidden_states: tuple[torch.FloatTensor, ...] | None = None
+
+
+# Copied from transformers.models.swin.modeling_swin.window_partition
+def window_partition(input_feature, window_size):
+ """
+ Partitions the given input into windows.
+ """
+ batch_size, height, width, num_channels = input_feature.shape
+ input_feature = input_feature.view(
+ batch_size, height // window_size, window_size, width // window_size, window_size, num_channels
+ )
+ windows = input_feature.transpose(2, 3).contiguous().view(-1, window_size, window_size, num_channels)
+ return windows
+
+
+# Copied from transformers.models.swin.modeling_swin.window_reverse
+def window_reverse(windows, window_size, height, width):
+ """
+ Merges windows to produce higher resolution features.
+ """
+ num_channels = windows.shape[-1]
+ windows = windows.view(-1, height // window_size, width // window_size, window_size, window_size, num_channels)
+ windows = windows.transpose(2, 3).contiguous().view(-1, height, width, num_channels)
+ return windows
+
+
+# Todo - Refactor as part of vision refactor. Copied from transformers.models.swin.modeling_swin.SwinEmbeddings with Swin->Swinv2
+class Swinv2Embeddings(nn.Module):
+ """
+ Construct the patch and position embeddings. Optionally, also the mask token.
+ """
+
+ def __init__(self, config, use_mask_token=False):
+ super().__init__()
+
+ self.patch_embeddings = Swinv2PatchEmbeddings(config)
+ num_patches = self.patch_embeddings.num_patches
+ self.patch_grid = self.patch_embeddings.grid_size
+ self.mask_token = nn.Parameter(torch.zeros(1, 1, config.embed_dim)) if use_mask_token else None
+
+ if config.use_absolute_embeddings:
+ self.position_embeddings = nn.Parameter(torch.zeros(1, num_patches + 1, config.embed_dim))
+ else:
+ self.position_embeddings = None
+
+ self.norm = nn.LayerNorm(config.embed_dim)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+ self.patch_size = config.patch_size
+ self.config = config
+
+ # Copied from transformers.models.vit.modeling_vit.ViTEmbeddings.interpolate_pos_encoding
+ def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor:
+ """
+ This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher resolution
+ images. This method is also adapted to support torch.jit tracing.
+
+ Adapted from:
+ - https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174-L194, and
+ - https://github.com/facebookresearch/dinov2/blob/e1277af2ba9496fbadf7aec6eba56e8d882d1e35/dinov2/models/vision_transformer.py#L179-L211
+ """
+
+ num_patches = embeddings.shape[1] - 1
+ num_positions = self.position_embeddings.shape[1] - 1
+
+ # always interpolate when tracing to ensure the exported model works for dynamic input shapes
+ if not torch.jit.is_tracing() and num_patches == num_positions and height == width:
+ return self.position_embeddings
+
+ class_pos_embed = self.position_embeddings[:, :1]
+ patch_pos_embed = self.position_embeddings[:, 1:]
+
+ dim = embeddings.shape[-1]
+
+ new_height = height // self.patch_size
+ new_width = width // self.patch_size
+
+ sqrt_num_positions = torch_int(num_positions**0.5)
+ patch_pos_embed = patch_pos_embed.reshape(1, sqrt_num_positions, sqrt_num_positions, dim)
+ patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2)
+
+ patch_pos_embed = nn.functional.interpolate(
+ patch_pos_embed,
+ size=(new_height, new_width),
+ mode="bicubic",
+ align_corners=False,
+ )
+
+ patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
+
+ return torch.cat((class_pos_embed, patch_pos_embed), dim=1)
+
+ def forward(
+ self,
+ pixel_values: torch.FloatTensor | None,
+ bool_masked_pos: torch.BoolTensor | None = None,
+ interpolate_pos_encoding: bool = False,
+ ) -> tuple[torch.Tensor]:
+ _, num_channels, height, width = pixel_values.shape
+ embeddings, output_dimensions = self.patch_embeddings(pixel_values)
+ embeddings = self.norm(embeddings)
+ batch_size, seq_len, _ = embeddings.size()
+
+ if bool_masked_pos is not None:
+ mask_tokens = self.mask_token.expand(batch_size, seq_len, -1)
+ # replace the masked visual tokens by mask_tokens
+ mask = bool_masked_pos.unsqueeze(-1).type_as(mask_tokens)
+ embeddings = embeddings * (1.0 - mask) + mask_tokens * mask
+
+ if self.position_embeddings is not None:
+ if interpolate_pos_encoding:
+ embeddings = embeddings + self.interpolate_pos_encoding(embeddings, height, width)
+ else:
+ embeddings = embeddings + self.position_embeddings
+
+ embeddings = self.dropout(embeddings)
+
+ return embeddings, output_dimensions
+
+
+# Copied from transformers.models.swin.modeling_swin.SwinPatchEmbeddings with Swin->Swinv2
+class Swinv2PatchEmbeddings(nn.Module):
+ """
+ This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
+ `hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
+ Transformer.
+ """
+
+ def __init__(self, config):
+ super().__init__()
+ image_size, patch_size = config.image_size, config.patch_size
+ num_channels, hidden_size = config.num_channels, config.embed_dim
+ image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
+ patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
+ num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
+ self.patch_size = patch_size
+ self.num_patches = num_patches
+ self.grid_size = (image_size[0] // patch_size[0], image_size[1] // patch_size[1])
+
+ self.projection = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=patch_size)
+
+ def maybe_pad(self, pixel_values, height, width):
+ """Pad pixel_values to be divisible by patch_size if needed."""
+ if width % self.patch_size[1] != 0:
+ pad_values = (0, self.patch_size[1] - width % self.patch_size[1])
+ pixel_values = nn.functional.pad(pixel_values, pad_values)
+ if height % self.patch_size[0] != 0:
+ pad_values = (0, 0, 0, self.patch_size[0] - height % self.patch_size[0])
+ pixel_values = nn.functional.pad(pixel_values, pad_values)
+ return pixel_values
+
+ def forward(self, pixel_values: torch.FloatTensor | None) -> tuple[torch.Tensor, tuple[int]]:
+ _, num_channels, height, width = pixel_values.shape
+ # pad the input to be divisible by self.patch_size, if needed
+ pixel_values = self.maybe_pad(pixel_values, height, width)
+ embeddings = self.projection(pixel_values)
+ _, _, height, width = embeddings.shape
+ output_dimensions = (height, width)
+ embeddings = embeddings.flatten(2).transpose(1, 2)
+
+ return embeddings, output_dimensions
+
+
+class Swinv2PatchMerging(nn.Module):
+ """
+ Patch Merging Layer.
+
+ Args:
+ input_resolution (`tuple[int]`):
+ Resolution of input feature.
+ dim (`int`):
+ Number of input channels.
+ norm_layer (`nn.Module`, *optional*, defaults to `nn.LayerNorm`):
+ Normalization layer class.
+ """
+
+ def __init__(self, input_resolution: tuple[int], dim: int, norm_layer: nn.Module = nn.LayerNorm) -> None:
+ super().__init__()
+ self.input_resolution = input_resolution
+ self.dim = dim
+ self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False)
+ self.norm = norm_layer(2 * dim)
+
+ def maybe_pad(self, input_feature, height, width):
+ should_pad = (height % 2 == 1) or (width % 2 == 1)
+ if should_pad:
+ pad_values = (0, 0, 0, width % 2, 0, height % 2)
+ input_feature = nn.functional.pad(input_feature, pad_values)
+
+ return input_feature
+
+ def forward(self, input_feature: torch.Tensor, input_dimensions: tuple[int, int]) -> torch.Tensor:
+ height, width = input_dimensions
+ # `dim` is height * width
+ batch_size, dim, num_channels = input_feature.shape
+
+ input_feature = input_feature.view(batch_size, height, width, num_channels)
+ # pad input to be divisible by width and height, if needed
+ input_feature = self.maybe_pad(input_feature, height, width)
+ # [batch_size, height/2, width/2, num_channels]
+ input_feature_0 = input_feature[:, 0::2, 0::2, :]
+ # [batch_size, height/2, width/2, num_channels]
+ input_feature_1 = input_feature[:, 1::2, 0::2, :]
+ # [batch_size, height/2, width/2, num_channels]
+ input_feature_2 = input_feature[:, 0::2, 1::2, :]
+ # [batch_size, height/2, width/2, num_channels]
+ input_feature_3 = input_feature[:, 1::2, 1::2, :]
+ # [batch_size, height/2 * width/2, 4*num_channels]
+ input_feature = torch.cat([input_feature_0, input_feature_1, input_feature_2, input_feature_3], -1)
+ input_feature = input_feature.view(batch_size, -1, 4 * num_channels) # [batch_size, height/2 * width/2, 4*C]
+
+ input_feature = self.reduction(input_feature)
+ input_feature = self.norm(input_feature)
+
+ return input_feature
+
+
+class Swinv2SelfAttention(nn.Module):
+ def __init__(self, config, dim, num_heads, window_size, pretrained_window_size=[0, 0]):
+ super().__init__()
+ if dim % num_heads != 0:
+ raise ValueError(
+ f"The hidden size ({dim}) is not a multiple of the number of attention heads ({num_heads})"
+ )
+
+ self.num_attention_heads = num_heads
+ self.attention_head_size = int(dim / num_heads)
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
+ self.window_size = (
+ window_size if isinstance(window_size, collections.abc.Iterable) else (window_size, window_size)
+ )
+ self.pretrained_window_size = pretrained_window_size
+ self.logit_scale = nn.Parameter(torch.log(10 * torch.ones((num_heads, 1, 1))))
+ # mlp to generate continuous relative position bias
+ self.continuous_position_bias_mlp = nn.Sequential(
+ nn.Linear(2, 512, bias=True), nn.ReLU(inplace=True), nn.Linear(512, num_heads, bias=False)
+ )
+
+ relative_coords_table, relative_position_index = self.create_coords_table_and_index()
+ self.register_buffer("relative_coords_table", relative_coords_table, persistent=False)
+ self.register_buffer("relative_position_index", relative_position_index, persistent=False)
+
+ self.query = nn.Linear(self.all_head_size, self.all_head_size, bias=config.qkv_bias)
+ self.key = nn.Linear(self.all_head_size, self.all_head_size, bias=False)
+ self.value = nn.Linear(self.all_head_size, self.all_head_size, bias=config.qkv_bias)
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.FloatTensor | None = None,
+ output_attentions: bool | None = False,
+ ) -> tuple[torch.Tensor]:
+ batch_size, dim, num_channels = hidden_states.shape
+ query_layer = (
+ self.query(hidden_states)
+ .view(batch_size, -1, self.num_attention_heads, self.attention_head_size)
+ .transpose(1, 2)
+ )
+ key_layer = (
+ self.key(hidden_states)
+ .view(batch_size, -1, self.num_attention_heads, self.attention_head_size)
+ .transpose(1, 2)
+ )
+ value_layer = (
+ self.value(hidden_states)
+ .view(batch_size, -1, self.num_attention_heads, self.attention_head_size)
+ .transpose(1, 2)
+ )
+
+ # cosine attention
+ attention_scores = nn.functional.normalize(query_layer, dim=-1) @ nn.functional.normalize(
+ key_layer, dim=-1
+ ).transpose(-2, -1)
+ logit_scale = torch.clamp(self.logit_scale, max=math.log(1.0 / 0.01)).exp()
+ attention_scores = attention_scores * logit_scale
+ relative_position_bias_table = self.continuous_position_bias_mlp(self.relative_coords_table).view(
+ -1, self.num_attention_heads
+ )
+ # [window_height*window_width,window_height*window_width,num_attention_heads]
+ relative_position_bias = relative_position_bias_table[self.relative_position_index.view(-1)].view(
+ self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1], -1
+ )
+ # [num_attention_heads,window_height*window_width,window_height*window_width]
+ relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww
+ relative_position_bias = 16 * torch.sigmoid(relative_position_bias)
+ attention_scores = attention_scores + relative_position_bias.unsqueeze(0)
+
+ if attention_mask is not None:
+ # Apply the attention mask is (precomputed for all layers in Swinv2Model forward() function)
+ mask_shape = attention_mask.shape[0]
+ attention_scores = attention_scores.view(
+ batch_size // mask_shape, mask_shape, self.num_attention_heads, dim, dim
+ ) + attention_mask.unsqueeze(1).unsqueeze(0)
+ attention_scores = attention_scores + attention_mask.unsqueeze(1).unsqueeze(0)
+ attention_scores = attention_scores.view(-1, self.num_attention_heads, dim, dim)
+
+ # Normalize the attention scores to probabilities.
+ attention_probs = nn.functional.softmax(attention_scores, dim=-1)
+
+ # This is actually dropping out entire tokens to attend to, which might
+ # seem a bit unusual, but is taken from the original Transformer paper.
+ attention_probs = self.dropout(attention_probs)
+
+ # Mask heads if we want to
+
+ context_layer = torch.matmul(attention_probs, value_layer)
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
+ context_layer = context_layer.view(new_context_layer_shape)
+
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
+
+ return outputs
+
+ def create_coords_table_and_index(self):
+ # get relative_coords_table
+ relative_coords_h = torch.arange(-(self.window_size[0] - 1), self.window_size[0], dtype=torch.int64).float()
+ relative_coords_w = torch.arange(-(self.window_size[1] - 1), self.window_size[1], dtype=torch.int64).float()
+ relative_coords_table = (
+ torch.stack(torch.meshgrid([relative_coords_h, relative_coords_w], indexing="ij"))
+ .permute(1, 2, 0)
+ .contiguous()
+ .unsqueeze(0)
+ ) # [1, 2*window_height - 1, 2*window_width - 1, 2]
+ if self.pretrained_window_size[0] > 0:
+ relative_coords_table[:, :, :, 0] /= self.pretrained_window_size[0] - 1
+ relative_coords_table[:, :, :, 1] /= self.pretrained_window_size[1] - 1
+ elif self.window_size[0] > 1:
+ relative_coords_table[:, :, :, 0] /= self.window_size[0] - 1
+ relative_coords_table[:, :, :, 1] /= self.window_size[1] - 1
+ relative_coords_table *= 8 # normalize to -8, 8
+ relative_coords_table = (
+ torch.sign(relative_coords_table) * torch.log2(torch.abs(relative_coords_table) + 1.0) / math.log2(8)
+ )
+ # set to same dtype as mlp weight
+ relative_coords_table = relative_coords_table.to(next(self.continuous_position_bias_mlp.parameters()).dtype)
+
+ # get pair-wise relative position index for each token inside the window
+ coords_h = torch.arange(self.window_size[0])
+ coords_w = torch.arange(self.window_size[1])
+ coords = torch.stack(torch.meshgrid([coords_h, coords_w], indexing="ij"))
+ coords_flatten = torch.flatten(coords, 1)
+ relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :]
+ relative_coords = relative_coords.permute(1, 2, 0).contiguous()
+ relative_coords[:, :, 0] += self.window_size[0] - 1
+ relative_coords[:, :, 1] += self.window_size[1] - 1
+ relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1
+ relative_position_index = relative_coords.sum(-1)
+
+ return relative_coords_table, relative_position_index
+
+
+# Todo - Refactor as part of vision refactor. Copied from transformers.models.swin.modeling_swin.SwinSelfOutput with Swin->Swinv2
+class Swinv2SelfOutput(nn.Module):
+ def __init__(self, config, dim):
+ super().__init__()
+ self.dense = nn.Linear(dim, dim)
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
+
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+
+ return hidden_states
+
+
+class Swinv2Attention(nn.Module):
+ def __init__(self, config, dim, num_heads, window_size, pretrained_window_size=0):
+ super().__init__()
+ self.self = Swinv2SelfAttention(
+ config=config,
+ dim=dim,
+ num_heads=num_heads,
+ window_size=window_size,
+ pretrained_window_size=pretrained_window_size
+ if isinstance(pretrained_window_size, collections.abc.Iterable)
+ else (pretrained_window_size, pretrained_window_size),
+ )
+ self.output = Swinv2SelfOutput(config, dim)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.FloatTensor | None = None,
+ output_attentions: bool | None = False,
+ ) -> tuple[torch.Tensor]:
+ self_outputs = self.self(hidden_states, attention_mask, output_attentions)
+ attention_output = self.output(self_outputs[0], hidden_states)
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
+ return outputs
+
+
+# Todo - Refactor as part of vision refactor. Copied from transformers.models.swin.modeling_swin.SwinIntermediate with Swin->Swinv2
+class Swinv2Intermediate(nn.Module):
+ def __init__(self, config, dim):
+ super().__init__()
+ self.dense = nn.Linear(dim, int(config.mlp_ratio * dim))
+ if isinstance(config.hidden_act, str):
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
+ else:
+ self.intermediate_act_fn = config.hidden_act
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.intermediate_act_fn(hidden_states)
+ return hidden_states
+
+
+# Todo - Refactor as part of vision refactor. Copied from transformers.models.swin.modeling_swin.SwinOutput with Swin->Swinv2
+class Swinv2Output(nn.Module):
+ def __init__(self, config, dim):
+ super().__init__()
+ self.dense = nn.Linear(int(config.mlp_ratio * dim), dim)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ return hidden_states
+
+
+# Copied from transformers.models.swin.modular_swin.SwinDropPath with SwinDropPath->Swinv2DropPath
+class Swinv2DropPath(nn.Module):
+ """Stochastic depth (DropPath) per sample, for residual blocks.
+
+ Identity when ``drop_prob`` is 0 or outside training. See `Deep Networks with Stochastic Depth
+ `_.
+ """
+
+ def __init__(self, drop_prob: float = 0.0) -> None:
+ super().__init__()
+ self.drop_prob = drop_prob
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ if self.drop_prob == 0.0 or not self.training:
+ return hidden_states
+ keep_prob = 1 - self.drop_prob
+ shape = (hidden_states.shape[0],) + (1,) * (hidden_states.ndim - 1)
+ random_tensor = torch.rand(shape, dtype=hidden_states.dtype, device=hidden_states.device)
+ random_tensor = torch.floor(random_tensor + keep_prob)
+ return hidden_states.div(keep_prob) * random_tensor
+
+ def extra_repr(self) -> str:
+ return f"p={self.drop_prob}"
+
+
+class Swinv2Layer(nn.Module):
+ def __init__(
+ self, config, dim, input_resolution, num_heads, drop_path_rate=0.0, shift_size=0, pretrained_window_size=0
+ ):
+ super().__init__()
+ self.input_resolution = input_resolution
+ window_size, shift_size = self._compute_window_shift(
+ (config.window_size, config.window_size), (shift_size, shift_size)
+ )
+ self.window_size = window_size[0]
+ self.shift_size = shift_size[0]
+ self.attention = Swinv2Attention(
+ config=config,
+ dim=dim,
+ num_heads=num_heads,
+ window_size=self.window_size,
+ pretrained_window_size=pretrained_window_size
+ if isinstance(pretrained_window_size, collections.abc.Iterable)
+ else (pretrained_window_size, pretrained_window_size),
+ )
+ self.layernorm_before = nn.LayerNorm(dim, eps=config.layer_norm_eps)
+ self.drop_path = Swinv2DropPath(drop_path_rate) if drop_path_rate > 0.0 else nn.Identity()
+ self.intermediate = Swinv2Intermediate(config, dim)
+ self.output = Swinv2Output(config, dim)
+ self.layernorm_after = nn.LayerNorm(dim, eps=config.layer_norm_eps)
+
+ def _compute_window_shift(self, target_window_size, target_shift_size) -> tuple[tuple[int, int], tuple[int, int]]:
+ window_size = [min(r, w) for r, w in zip(self.input_resolution, target_window_size)]
+ shift_size = [0 if r <= w else s for r, w, s in zip(self.input_resolution, window_size, target_shift_size)]
+ return window_size, shift_size
+
+ def get_attn_mask(self, height, width, dtype):
+ if self.shift_size > 0:
+ # calculate attention mask for shifted window multihead self attention
+ img_mask = torch.zeros((1, height, width, 1), dtype=dtype)
+ height_slices = (
+ slice(0, -self.window_size),
+ slice(-self.window_size, -self.shift_size),
+ slice(-self.shift_size, None),
+ )
+ width_slices = (
+ slice(0, -self.window_size),
+ slice(-self.window_size, -self.shift_size),
+ slice(-self.shift_size, None),
+ )
+ count = 0
+ for height_slice in height_slices:
+ for width_slice in width_slices:
+ img_mask[:, height_slice, width_slice, :] = count
+ count += 1
+
+ mask_windows = window_partition(img_mask, self.window_size)
+ mask_windows = mask_windows.view(-1, self.window_size * self.window_size)
+ attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2)
+ attn_mask = attn_mask.masked_fill(attn_mask != 0, -100.0).masked_fill(attn_mask == 0, 0.0)
+ else:
+ attn_mask = None
+ return attn_mask
+
+ def maybe_pad(self, hidden_states, height, width):
+ pad_right = (self.window_size - width % self.window_size) % self.window_size
+ pad_bottom = (self.window_size - height % self.window_size) % self.window_size
+ pad_values = (0, 0, 0, pad_right, 0, pad_bottom)
+ hidden_states = nn.functional.pad(hidden_states, pad_values)
+ return hidden_states, pad_values
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ input_dimensions: tuple[int, int],
+ output_attentions: bool | None = False,
+ ) -> tuple[torch.Tensor, torch.Tensor]:
+ height, width = input_dimensions
+ batch_size, _, channels = hidden_states.size()
+ shortcut = hidden_states
+
+ # pad hidden_states to multiples of window size
+ hidden_states = hidden_states.view(batch_size, height, width, channels)
+ hidden_states, pad_values = self.maybe_pad(hidden_states, height, width)
+ _, height_pad, width_pad, _ = hidden_states.shape
+ # cyclic shift
+ if self.shift_size > 0:
+ shifted_hidden_states = torch.roll(hidden_states, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2))
+ else:
+ shifted_hidden_states = hidden_states
+
+ # partition windows
+ hidden_states_windows = window_partition(shifted_hidden_states, self.window_size)
+ hidden_states_windows = hidden_states_windows.view(-1, self.window_size * self.window_size, channels)
+ attn_mask = self.get_attn_mask(height_pad, width_pad, dtype=hidden_states.dtype)
+ if attn_mask is not None:
+ attn_mask = attn_mask.to(hidden_states_windows.device)
+
+ attention_outputs = self.attention(hidden_states_windows, attn_mask, output_attentions=output_attentions)
+
+ attention_output = attention_outputs[0]
+
+ attention_windows = attention_output.view(-1, self.window_size, self.window_size, channels)
+ shifted_windows = window_reverse(attention_windows, self.window_size, height_pad, width_pad)
+
+ # reverse cyclic shift
+ if self.shift_size > 0:
+ attention_windows = torch.roll(shifted_windows, shifts=(self.shift_size, self.shift_size), dims=(1, 2))
+ else:
+ attention_windows = shifted_windows
+
+ was_padded = pad_values[3] > 0 or pad_values[5] > 0
+ if was_padded:
+ attention_windows = attention_windows[:, :height, :width, :].contiguous()
+
+ attention_windows = attention_windows.view(batch_size, height * width, channels)
+ hidden_states = self.layernorm_before(attention_windows)
+ hidden_states = shortcut + self.drop_path(hidden_states)
+
+ layer_output = self.intermediate(hidden_states)
+ layer_output = self.output(layer_output)
+ layer_output = hidden_states + self.drop_path(self.layernorm_after(layer_output))
+
+ layer_outputs = (layer_output, attention_outputs[1]) if output_attentions else (layer_output,)
+ return layer_outputs
+
+
+class Swinv2Stage(GradientCheckpointingLayer):
+ def __init__(
+ self, config, dim, input_resolution, depth, num_heads, drop_path, downsample, pretrained_window_size=0
+ ):
+ super().__init__()
+ self.config = config
+ self.dim = dim
+ blocks = []
+ for i in range(depth):
+ block = Swinv2Layer(
+ config=config,
+ dim=dim,
+ input_resolution=input_resolution,
+ num_heads=num_heads,
+ drop_path_rate=drop_path[i],
+ shift_size=0 if (i % 2 == 0) else config.window_size // 2,
+ pretrained_window_size=pretrained_window_size,
+ )
+ blocks.append(block)
+ self.blocks = nn.ModuleList(blocks)
+
+ # patch merging layer
+ if downsample is not None:
+ self.downsample = downsample(input_resolution, dim=dim, norm_layer=nn.LayerNorm)
+ else:
+ self.downsample = None
+
+ self.pointing = False
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ input_dimensions: tuple[int, int],
+ output_attentions: bool | None = False,
+ ) -> tuple[torch.Tensor]:
+ height, width = input_dimensions
+ for i, layer_module in enumerate(self.blocks):
+ layer_outputs = layer_module(
+ hidden_states,
+ input_dimensions,
+ output_attentions,
+ )
+
+ hidden_states = layer_outputs[0]
+
+ hidden_states_before_downsampling = hidden_states
+ if self.downsample is not None:
+ height_downsampled, width_downsampled = (height + 1) // 2, (width + 1) // 2
+ output_dimensions = (height, width, height_downsampled, width_downsampled)
+ hidden_states = self.downsample(hidden_states_before_downsampling, input_dimensions)
+ else:
+ output_dimensions = (height, width, height, width)
+
+ stage_outputs = (hidden_states, hidden_states_before_downsampling, output_dimensions)
+
+ if output_attentions:
+ stage_outputs += layer_outputs[1:]
+ return stage_outputs
+
+
+class Swinv2Encoder(nn.Module):
+ def __init__(self, config, grid_size, pretrained_window_sizes=(0, 0, 0, 0)):
+ super().__init__()
+ self.num_layers = len(config.depths)
+ self.config = config
+ if self.config.pretrained_window_sizes is not None:
+ pretrained_window_sizes = config.pretrained_window_sizes
+ dpr = [x.item() for x in torch.linspace(0, config.drop_path_rate, sum(config.depths), device="cpu")]
+
+ layers = []
+ for i_layer in range(self.num_layers):
+ stage = Swinv2Stage(
+ config=config,
+ dim=int(config.embed_dim * 2**i_layer),
+ input_resolution=(grid_size[0] // (2**i_layer), grid_size[1] // (2**i_layer)),
+ depth=config.depths[i_layer],
+ num_heads=config.num_heads[i_layer],
+ drop_path=dpr[sum(config.depths[:i_layer]) : sum(config.depths[: i_layer + 1])],
+ downsample=Swinv2PatchMerging if (i_layer < self.num_layers - 1) else None,
+ pretrained_window_size=pretrained_window_sizes[i_layer],
+ )
+ layers.append(stage)
+ self.layers = nn.ModuleList(layers)
+
+ self.gradient_checkpointing = False
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ input_dimensions: tuple[int, int],
+ output_attentions: bool | None = False,
+ output_hidden_states: bool | None = False,
+ output_hidden_states_before_downsampling: bool | None = False,
+ return_dict: bool | None = True,
+ ) -> tuple | Swinv2EncoderOutput:
+ all_hidden_states = () if output_hidden_states else None
+ all_reshaped_hidden_states = () if output_hidden_states else None
+ all_self_attentions = () if output_attentions else None
+
+ if output_hidden_states:
+ batch_size, _, hidden_size = hidden_states.shape
+ # rearrange b (h w) c -> b c h w
+ reshaped_hidden_state = hidden_states.view(batch_size, *input_dimensions, hidden_size)
+ reshaped_hidden_state = reshaped_hidden_state.permute(0, 3, 1, 2)
+ all_hidden_states += (hidden_states,)
+ all_reshaped_hidden_states += (reshaped_hidden_state,)
+
+ for i, layer_module in enumerate(self.layers):
+ layer_outputs = layer_module(
+ hidden_states,
+ input_dimensions,
+ output_attentions,
+ )
+
+ hidden_states = layer_outputs[0]
+ hidden_states_before_downsampling = layer_outputs[1]
+ output_dimensions = layer_outputs[2]
+
+ input_dimensions = (output_dimensions[-2], output_dimensions[-1])
+
+ if output_hidden_states and output_hidden_states_before_downsampling:
+ batch_size, _, hidden_size = hidden_states_before_downsampling.shape
+ # rearrange b (h w) c -> b c h w
+ # here we use the original (not downsampled) height and width
+ reshaped_hidden_state = hidden_states_before_downsampling.view(
+ batch_size, *(output_dimensions[0], output_dimensions[1]), hidden_size
+ )
+ reshaped_hidden_state = reshaped_hidden_state.permute(0, 3, 1, 2)
+ all_hidden_states += (hidden_states_before_downsampling,)
+ all_reshaped_hidden_states += (reshaped_hidden_state,)
+ elif output_hidden_states and not output_hidden_states_before_downsampling:
+ batch_size, _, hidden_size = hidden_states.shape
+ # rearrange b (h w) c -> b c h w
+ reshaped_hidden_state = hidden_states.view(batch_size, *input_dimensions, hidden_size)
+ reshaped_hidden_state = reshaped_hidden_state.permute(0, 3, 1, 2)
+ all_hidden_states += (hidden_states,)
+ all_reshaped_hidden_states += (reshaped_hidden_state,)
+
+ if output_attentions:
+ all_self_attentions += layer_outputs[3:]
+
+ if not return_dict:
+ return tuple(
+ v
+ for v in [hidden_states, all_hidden_states, all_self_attentions, all_reshaped_hidden_states]
+ if v is not None
+ )
+
+ return Swinv2EncoderOutput(
+ last_hidden_state=hidden_states,
+ hidden_states=all_hidden_states,
+ attentions=all_self_attentions,
+ reshaped_hidden_states=all_reshaped_hidden_states,
+ )
+
+
+@auto_docstring
+class Swinv2PreTrainedModel(PreTrainedModel):
+ config: Swinv2Config
+ base_model_prefix = "swinv2"
+ main_input_name = "pixel_values"
+ input_modalities = ("image",)
+ supports_gradient_checkpointing = True
+ _no_split_modules = ["Swinv2Stage"]
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ """Initialize the weights"""
+ if isinstance(module, (nn.Linear, nn.Conv2d)):
+ init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
+ if module.bias is not None:
+ init.zeros_(module.bias)
+ elif isinstance(module, nn.LayerNorm):
+ init.zeros_(module.bias)
+ init.ones_(module.weight)
+ elif isinstance(module, Swinv2Embeddings):
+ if module.mask_token is not None:
+ init.zeros_(module.mask_token)
+ if module.position_embeddings is not None:
+ init.zeros_(module.position_embeddings)
+ elif isinstance(module, Swinv2SelfAttention):
+ init.constant_(module.logit_scale, math.log(10))
+ relative_coords_table, relative_position_index = module.create_coords_table_and_index()
+ init.copy_(module.relative_coords_table, relative_coords_table)
+ init.copy_(module.relative_position_index, relative_position_index)
+
+
+@auto_docstring
+# Todo - Refactor as part of vision refactor. Copied from transformers.models.swin.modeling_swin.SwinModel with SWIN->SWINV2,Swin->Swinv2
+class Swinv2Model(Swinv2PreTrainedModel):
+ def __init__(self, config, add_pooling_layer=True, use_mask_token=False):
+ r"""
+ add_pooling_layer (`bool`, *optional*, defaults to `True`):
+ Whether or not to apply pooling layer.
+ use_mask_token (`bool`, *optional*, defaults to `False`):
+ Whether or not to create and apply mask tokens in the embedding layer.
+ """
+ super().__init__(config)
+ self.config = config
+ self.num_layers = len(config.depths)
+ self.num_features = int(config.embed_dim * 2 ** (self.num_layers - 1))
+
+ self.embeddings = Swinv2Embeddings(config, use_mask_token=use_mask_token)
+ self.encoder = Swinv2Encoder(config, self.embeddings.patch_grid)
+
+ self.layernorm = nn.LayerNorm(self.num_features, eps=config.layer_norm_eps)
+ self.pooler = nn.AdaptiveAvgPool1d(1) if add_pooling_layer else None
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.embeddings.patch_embeddings
+
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: torch.FloatTensor | None = None,
+ bool_masked_pos: torch.BoolTensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ interpolate_pos_encoding: bool = False,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple | Swinv2ModelOutput:
+ r"""
+ bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, num_patches)`, *optional*):
+ Boolean masked positions. Indicates which patches are masked (1) and which aren't (0).
+ """
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ if pixel_values is None:
+ raise ValueError("You have to specify pixel_values")
+
+ embedding_output, input_dimensions = self.embeddings(
+ pixel_values, bool_masked_pos=bool_masked_pos, interpolate_pos_encoding=interpolate_pos_encoding
+ )
+
+ encoder_outputs = self.encoder(
+ embedding_output,
+ input_dimensions,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ sequence_output = encoder_outputs[0]
+ sequence_output = self.layernorm(sequence_output)
+
+ pooled_output = None
+ if self.pooler is not None:
+ pooled_output = self.pooler(sequence_output.transpose(1, 2))
+ pooled_output = torch.flatten(pooled_output, 1)
+
+ if not return_dict:
+ output = (sequence_output, pooled_output) + encoder_outputs[1:]
+
+ return output
+
+ return Swinv2ModelOutput(
+ last_hidden_state=sequence_output,
+ pooler_output=pooled_output,
+ hidden_states=encoder_outputs.hidden_states,
+ attentions=encoder_outputs.attentions,
+ reshaped_hidden_states=encoder_outputs.reshaped_hidden_states,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ Swinv2 Model with a decoder on top for masked image modeling, as proposed in
+ [SimMIM](https://huggingface.co/papers/2111.09886).
+
+
+
+ Note that we provide a script to pre-train this model on custom data in our [examples
+ directory](https://github.com/huggingface/transformers/tree/main/examples/pytorch/image-pretraining).
+
+
+ """
+)
+# Todo - Refactor as part of vision refactor. Copied from transformers.models.swin.modeling_swin.SwinForMaskedImageModeling with swin->swinv2, base-simmim-window6-192->tiny-patch4-window8-256,SWIN->SWINV2,Swin->Swinv2,192->256
+class Swinv2ForMaskedImageModeling(Swinv2PreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.swinv2 = Swinv2Model(config, add_pooling_layer=False, use_mask_token=True)
+
+ num_features = int(config.embed_dim * 2 ** (config.num_layers - 1))
+ self.decoder = nn.Sequential(
+ nn.Conv2d(
+ in_channels=num_features, out_channels=config.encoder_stride**2 * config.num_channels, kernel_size=1
+ ),
+ nn.PixelShuffle(config.encoder_stride),
+ )
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: torch.FloatTensor | None = None,
+ bool_masked_pos: torch.BoolTensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ interpolate_pos_encoding: bool = False,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple | Swinv2MaskedImageModelingOutput:
+ r"""
+ bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, num_patches)`):
+ Boolean masked positions. Indicates which patches are masked (1) and which aren't (0).
+
+ Examples:
+ ```python
+ >>> from transformers import AutoImageProcessor, Swinv2ForMaskedImageModeling
+ >>> import torch
+ >>> from PIL import Image
+ >>> import httpx
+ >>> from io import BytesIO
+
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
+ >>> with httpx.stream("GET", url) as response:
+ ... image = Image.open(BytesIO(response.read()))
+
+ >>> image_processor = AutoImageProcessor.from_pretrained("microsoft/swinv2-tiny-patch4-window8-256")
+ >>> model = Swinv2ForMaskedImageModeling.from_pretrained("microsoft/swinv2-tiny-patch4-window8-256")
+
+ >>> num_patches = (model.config.image_size // model.config.patch_size) ** 2
+ >>> pixel_values = image_processor(images=image, return_tensors="pt").pixel_values
+ >>> # create random boolean mask of shape (batch_size, num_patches)
+ >>> bool_masked_pos = torch.randint(low=0, high=2, size=(1, num_patches)).bool()
+
+ >>> outputs = model(pixel_values, bool_masked_pos=bool_masked_pos)
+ >>> loss, reconstructed_pixel_values = outputs.loss, outputs.reconstruction
+ >>> list(reconstructed_pixel_values.shape)
+ [1, 3, 256, 256]
+ ```"""
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ outputs = self.swinv2(
+ pixel_values,
+ bool_masked_pos=bool_masked_pos,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ interpolate_pos_encoding=interpolate_pos_encoding,
+ return_dict=return_dict,
+ )
+
+ sequence_output = outputs[0]
+ # Reshape to (batch_size, num_channels, height, width)
+ sequence_output = sequence_output.transpose(1, 2)
+ batch_size, num_channels, sequence_length = sequence_output.shape
+ height = width = math.floor(sequence_length**0.5)
+ sequence_output = sequence_output.reshape(batch_size, num_channels, height, width)
+
+ # Reconstruct pixel values
+ reconstructed_pixel_values = self.decoder(sequence_output)
+
+ masked_im_loss = None
+ if bool_masked_pos is not None:
+ size = self.config.image_size // self.config.patch_size
+ bool_masked_pos = bool_masked_pos.reshape(-1, size, size)
+ mask = (
+ bool_masked_pos.repeat_interleave(self.config.patch_size, 1)
+ .repeat_interleave(self.config.patch_size, 2)
+ .unsqueeze(1)
+ .contiguous()
+ )
+ reconstruction_loss = nn.functional.l1_loss(pixel_values, reconstructed_pixel_values, reduction="none")
+ masked_im_loss = (reconstruction_loss * mask).sum() / (mask.sum() + 1e-5) / self.config.num_channels
+
+ if not return_dict:
+ output = (reconstructed_pixel_values,) + outputs[2:]
+ return ((masked_im_loss,) + output) if masked_im_loss is not None else output
+
+ return Swinv2MaskedImageModelingOutput(
+ loss=masked_im_loss,
+ reconstruction=reconstructed_pixel_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ reshaped_hidden_states=outputs.reshaped_hidden_states,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ Swinv2 Model transformer with an image classification head on top (a linear layer on top of the final hidden state
+ of the [CLS] token) e.g. for ImageNet.
+
+
+
+ Note that it's possible to fine-tune SwinV2 on higher resolution images than the ones it has been trained on, by
+ setting `interpolate_pos_encoding` to `True` in the forward of the model. This will interpolate the pre-trained
+ position embeddings to the higher resolution.
+
+
+ """
+)
+# Todo - Refactor as part of vision refactor. Copied from transformers.models.swin.modeling_swin.SwinForImageClassification with SWIN->SWINV2,Swin->Swinv2,swin->swinv2
+class Swinv2ForImageClassification(Swinv2PreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.num_labels = config.num_labels
+ self.swinv2 = Swinv2Model(config)
+
+ # Classifier head
+ self.classifier = (
+ nn.Linear(self.swinv2.num_features, config.num_labels) if config.num_labels > 0 else nn.Identity()
+ )
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ interpolate_pos_encoding: bool = False,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple | Swinv2ImageClassifierOutput:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ outputs = self.swinv2(
+ pixel_values,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ interpolate_pos_encoding=interpolate_pos_encoding,
+ return_dict=return_dict,
+ )
+
+ pooled_output = outputs[1]
+
+ logits = self.classifier(pooled_output)
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(labels, logits, self.config)
+
+ if not return_dict:
+ output = (logits,) + outputs[2:]
+ return ((loss,) + output) if loss is not None else output
+
+ return Swinv2ImageClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ reshaped_hidden_states=outputs.reshaped_hidden_states,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ Swinv2 backbone, to be used with frameworks like DETR and MaskFormer.
+ """
+)
+class Swinv2Backbone(BackboneMixin, Swinv2PreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.num_features = [config.embed_dim] + [int(config.embed_dim * 2**i) for i in range(len(config.depths))]
+ self.embeddings = Swinv2Embeddings(config)
+ self.encoder = Swinv2Encoder(config, self.embeddings.patch_grid)
+
+ # initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.embeddings.patch_embeddings
+
+ @can_return_tuple
+ @filter_output_hidden_states
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: Tensor,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> BackboneOutput:
+ r"""
+ Examples:
+
+ ```python
+ >>> from transformers import AutoImageProcessor, AutoBackbone
+ >>> import torch
+ >>> from PIL import Image
+ >>> import httpx
+ >>> from io import BytesIO
+
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
+ >>> with httpx.stream("GET", url) as response:
+ ... image = Image.open(BytesIO(response.read()))
+
+ >>> processor = AutoImageProcessor.from_pretrained("microsoft/swinv2-tiny-patch4-window8-256")
+ >>> model = AutoBackbone.from_pretrained(
+ ... "microsoft/swinv2-tiny-patch4-window8-256", out_features=["stage1", "stage2", "stage3", "stage4"]
+ ... )
+
+ >>> inputs = processor(image, return_tensors="pt")
+
+ >>> outputs = model(**inputs)
+ >>> feature_maps = outputs.feature_maps
+ >>> list(feature_maps[-1].shape)
+ [1, 2048, 7, 7]
+ ```"""
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+
+ embedding_output, input_dimensions = self.embeddings(pixel_values)
+
+ outputs = self.encoder(
+ embedding_output,
+ input_dimensions,
+ output_attentions=output_attentions,
+ output_hidden_states=True,
+ output_hidden_states_before_downsampling=True,
+ return_dict=return_dict,
+ )
+
+ hidden_states = outputs.reshaped_hidden_states if return_dict else outputs[-1]
+
+ feature_maps = ()
+ for stage, hidden_state in zip(self.stage_names, hidden_states):
+ if stage in self.out_features:
+ feature_maps += (hidden_state,)
+
+ if not return_dict:
+ output = (feature_maps,)
+ if output_hidden_states:
+ output += (outputs[1],)
+ if output_attentions:
+ output += (outputs[2],)
+ return output
+
+ return BackboneOutput(
+ feature_maps=feature_maps,
+ hidden_states=outputs.hidden_states if output_hidden_states else None,
+ attentions=outputs.attentions,
+ )
+
+
+__all__ = [
+ "Swinv2ForImageClassification",
+ "Swinv2ForMaskedImageModeling",
+ "Swinv2Model",
+ "Swinv2PreTrainedModel",
+ "Swinv2Backbone",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/t5/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/t5/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..5ba44f774dba82304e5dcbec0cbd6ee21fed1ef6
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/t5/__init__.py
@@ -0,0 +1,28 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_t5 import *
+ from .modeling_t5 import *
+ from .tokenization_t5 import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/t5/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/t5/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2c83811b9b6e3ed2caf6c0909f8927635020a070
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/t5/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/t5/__pycache__/configuration_t5.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/t5/__pycache__/configuration_t5.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..222a1e3994e3289d869866ec2dde3b8b4cc77bc2
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/t5/__pycache__/configuration_t5.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/t5/__pycache__/modeling_t5.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/t5/__pycache__/modeling_t5.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..69346775a49a64b2f01649e931698f761701d669
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/t5/__pycache__/modeling_t5.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/t5/__pycache__/tokenization_t5.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/t5/__pycache__/tokenization_t5.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d31135d7bba735a030edf6f357eff2086854ca7f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/t5/__pycache__/tokenization_t5.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/t5/configuration_t5.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/t5/configuration_t5.py
new file mode 100644
index 0000000000000000000000000000000000000000..5223811a5e9e5dc0157663d1019687013230fede
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/t5/configuration_t5.py
@@ -0,0 +1,98 @@
+# Copyright 2020, The T5 Authors and HuggingFace Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""T5 model configuration"""
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring
+
+
+@auto_docstring(checkpoint="google-t5/t5-small")
+@strict
+class T5Config(PreTrainedConfig):
+ r"""
+ relative_attention_num_buckets (`int`, *optional*, defaults to 32):
+ The number of buckets to use for each attention layer.
+ relative_attention_max_distance (`int`, *optional*, defaults to 128):
+ The maximum distance of the longer sequences for the bucket separation.
+ feed_forward_proj (`string`, *optional*, defaults to `"relu"`):
+ Type of feed forward layer to be used. Should be one of `"relu"` or `"gated-gelu"`. T5v1.1 uses the
+ `"gated-gelu"` feed forward projection. Original T5 uses `"relu"`.
+ """
+
+ model_type = "t5"
+ keys_to_ignore_at_inference = ["past_key_values"]
+ attribute_map = {
+ "hidden_size": "d_model",
+ "num_attention_heads": "num_heads",
+ "num_hidden_layers": "num_layers",
+ "head_dim": "d_kv",
+ }
+
+ vocab_size: int = 32128
+ d_model: int = 512
+ d_kv: int = 64
+ d_ff: int = 2048
+ num_layers: int = 6
+ num_decoder_layers: int | None = None
+ num_heads: int = 8
+ relative_attention_num_buckets: int = 32
+ relative_attention_max_distance: int = 128
+ dropout_rate: float | int = 0.1
+ layer_norm_epsilon: float = 1e-6
+ initializer_factor: float = 1.0
+ feed_forward_proj: str = "relu"
+ is_encoder_decoder: bool = True
+ use_cache: bool = True
+ pad_token_id: int | None = 0
+ eos_token_id: int | list[int] | None = 1
+ classifier_dropout: float | int = 0.0
+ is_decoder: bool = False
+
+ def __post_init__(self, **kwargs):
+ self.num_decoder_layers = (
+ self.num_decoder_layers if self.num_decoder_layers is not None else self.num_layers
+ ) # default = symmetry
+
+ act_info = self.feed_forward_proj.split("-")
+ self.dense_act_fn = act_info[-1]
+ self.is_gated_act = act_info[0] == "gated"
+
+ # for backwards compatibility
+ if self.feed_forward_proj == "gated-gelu":
+ self.dense_act_fn = "gelu_new"
+
+ # Super weird feature of T5 because we support T5 and T51.1 from the same
+ # model code. Original T5 always scaled outputs, but the 1.1v does not.
+ # The model code was relying on saved configs where `tie_word_embeddings` is
+ # set to `False` in 1.1v and using it as indicator of whether to scale or not
+ # But in fact we tie weights always and force it to be `True`
+ self.scale_decoder_outputs = kwargs.pop("tie_word_embeddings", None) is not False
+ self.tie_word_embeddings = True
+
+ super().__post_init__(**kwargs)
+
+ def validate_architecture(self):
+ """Part of `@strict`-powered validation. Validates the architecture of the config."""
+ act_info = self.feed_forward_proj.split("-")
+ if len(act_info) > 1 and act_info[0] != "gated" or len(act_info) > 2:
+ raise ValueError(
+ f"`feed_forward_proj`: {self.feed_forward_proj} is not a valid activation function of the dense layer. "
+ "Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. "
+ "'gated-gelu' or 'relu'"
+ )
+
+
+__all__ = ["T5Config"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/t5/modeling_t5.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/t5/modeling_t5.py
new file mode 100644
index 0000000000000000000000000000000000000000..465a5c0153927e4dc9925dc6e1584b6773f85d41
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/t5/modeling_t5.py
@@ -0,0 +1,1606 @@
+# Copyright 2018 Mesh TensorFlow authors, T5 Authors and HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch T5 model."""
+
+import copy
+import math
+
+import torch
+from torch import nn
+from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...cache_utils import Cache, DynamicCache, EncoderDecoderCache
+from ...generation import GenerationMixin
+from ...masking_utils import create_bidirectional_mask, create_causal_mask
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import (
+ BaseModelOutput,
+ BaseModelOutputWithPastAndCrossAttentions,
+ Seq2SeqLMOutput,
+ Seq2SeqModelOutput,
+ Seq2SeqQuestionAnsweringModelOutput,
+ Seq2SeqSequenceClassifierOutput,
+ TokenClassifierOutput,
+)
+from ...modeling_utils import PreTrainedModel
+from ...utils import DUMMY_INPUTS, DUMMY_MASK, auto_docstring, logging, torch_compilable_check
+from .configuration_t5 import T5Config
+
+
+logger = logging.get_logger(__name__)
+
+
+class T5LayerNorm(nn.Module):
+ def __init__(self, hidden_size, eps=1e-6):
+ """
+ Construct a layernorm module in the T5 style. No bias and no subtraction of mean.
+ """
+ super().__init__()
+ self.weight = nn.Parameter(torch.ones(hidden_size))
+ self.variance_epsilon = eps
+
+ def forward(self, hidden_states):
+ # T5 uses a layer_norm which only scales and doesn't shift, which is also known as Root Mean
+ # Square Layer Normalization https://huggingface.co/papers/1910.07467 thus variance is calculated
+ # w/o mean and there is no bias. Additionally we want to make sure that the accumulation for
+ # half-precision inputs is done in fp32
+
+ variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
+
+ # convert into half-precision if necessary
+ if self.weight.dtype in [torch.float16, torch.bfloat16]:
+ hidden_states = hidden_states.to(self.weight.dtype)
+
+ return self.weight * hidden_states
+
+
+class T5DenseActDense(nn.Module):
+ def __init__(self, config: T5Config):
+ super().__init__()
+ self.wi = nn.Linear(config.d_model, config.d_ff, bias=False)
+ self.wo = nn.Linear(config.d_ff, config.d_model, bias=False)
+ self.dropout = nn.Dropout(config.dropout_rate)
+ self.act = ACT2FN[config.dense_act_fn]
+
+ def forward(self, hidden_states):
+ hidden_states = self.wi(hidden_states)
+ hidden_states = self.act(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ if (
+ isinstance(self.wo.weight, torch.Tensor)
+ and hidden_states.dtype != self.wo.weight.dtype
+ and self.wo.weight.dtype != torch.int8
+ ):
+ hidden_states = hidden_states.to(self.wo.weight.dtype)
+ hidden_states = self.wo(hidden_states)
+ return hidden_states
+
+
+class T5DenseGatedActDense(nn.Module):
+ def __init__(self, config: T5Config):
+ super().__init__()
+ self.wi_0 = nn.Linear(config.d_model, config.d_ff, bias=False)
+ self.wi_1 = nn.Linear(config.d_model, config.d_ff, bias=False)
+ self.wo = nn.Linear(config.d_ff, config.d_model, bias=False)
+ self.dropout = nn.Dropout(config.dropout_rate)
+ self.act = ACT2FN[config.dense_act_fn]
+
+ def forward(self, hidden_states):
+ hidden_gelu = self.act(self.wi_0(hidden_states))
+ hidden_linear = self.wi_1(hidden_states)
+ hidden_states = hidden_gelu * hidden_linear
+ hidden_states = self.dropout(hidden_states)
+
+ # To make 8bit quantization work for google/flan-t5-xxl, self.wo is kept in float32.
+ # See https://github.com/huggingface/transformers/issues/20287
+ # we also make sure the weights are not in `int8` in case users will force `_keep_in_fp32_modules` to be `None``
+ if (
+ isinstance(self.wo.weight, torch.Tensor)
+ and hidden_states.dtype != self.wo.weight.dtype
+ and self.wo.weight.dtype != torch.int8
+ ):
+ hidden_states = hidden_states.to(self.wo.weight.dtype)
+
+ hidden_states = self.wo(hidden_states)
+ return hidden_states
+
+
+class T5LayerFF(nn.Module):
+ def __init__(self, config: T5Config):
+ super().__init__()
+ if config.is_gated_act:
+ self.DenseReluDense = T5DenseGatedActDense(config)
+ else:
+ self.DenseReluDense = T5DenseActDense(config)
+
+ self.layer_norm = T5LayerNorm(config.d_model, eps=config.layer_norm_epsilon)
+ self.dropout = nn.Dropout(config.dropout_rate)
+
+ def forward(self, hidden_states):
+ forwarded_states = self.layer_norm(hidden_states)
+ forwarded_states = self.DenseReluDense(forwarded_states)
+ hidden_states = hidden_states + self.dropout(forwarded_states)
+ return hidden_states
+
+
+class T5Attention(nn.Module):
+ def __init__(
+ self,
+ config: T5Config,
+ has_relative_attention_bias=False,
+ layer_idx: int | None = None,
+ ):
+ super().__init__()
+ self.is_decoder = config.is_decoder
+ self.has_relative_attention_bias = has_relative_attention_bias
+ self.relative_attention_num_buckets = config.relative_attention_num_buckets
+ self.relative_attention_max_distance = config.relative_attention_max_distance
+ self.d_model = config.d_model
+ self.key_value_proj_dim = config.d_kv
+ self.n_heads = config.num_heads
+ self.dropout = config.dropout_rate
+ self.inner_dim = self.n_heads * self.key_value_proj_dim
+ self.layer_idx = layer_idx
+ if layer_idx is None and self.is_decoder:
+ logger.warning_once(
+ f"Instantiating a decoder {self.__class__.__name__} without passing `layer_idx` is not recommended and "
+ "will to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
+ "when creating this class."
+ )
+
+ self.q = nn.Linear(self.d_model, self.inner_dim, bias=False)
+ self.k = nn.Linear(self.d_model, self.inner_dim, bias=False)
+ self.v = nn.Linear(self.d_model, self.inner_dim, bias=False)
+ self.o = nn.Linear(self.inner_dim, self.d_model, bias=False)
+
+ if self.has_relative_attention_bias:
+ self.relative_attention_bias = nn.Embedding(self.relative_attention_num_buckets, self.n_heads)
+
+ self.gradient_checkpointing = False
+
+ @staticmethod
+ def _relative_position_bucket(relative_position, bidirectional=True, num_buckets=32, max_distance=128):
+ """
+ Adapted from Mesh Tensorflow:
+ https://github.com/tensorflow/mesh/blob/0cb87fe07da627bf0b7e60475d59f95ed6b5be3d/mesh_tensorflow/transformer/transformer_layers.py#L593
+
+ Translate relative position to a bucket number for relative attention. The relative position is defined as
+ memory_position - query_position, i.e. the distance in tokens from the attending position to the attended-to
+ position. If bidirectional=False, then positive relative positions are invalid. We use smaller buckets for
+ small absolute relative_position and larger buckets for larger absolute relative_positions. All relative
+ positions >=max_distance map to the same bucket. All relative positions <=-max_distance map to the same bucket.
+ This should allow for more graceful generalization to longer sequences than the model has been trained on
+
+ Args:
+ relative_position: an int32 Tensor
+ bidirectional: a boolean - whether the attention is bidirectional
+ num_buckets: an integer
+ max_distance: an integer
+
+ Returns:
+ a Tensor with the same shape as relative_position, containing int32 values in the range [0, num_buckets)
+ """
+ relative_buckets = 0
+ if bidirectional:
+ num_buckets //= 2
+ relative_buckets += (relative_position > 0).to(torch.long) * num_buckets
+ relative_position = torch.abs(relative_position)
+ else:
+ relative_position = -torch.min(relative_position, torch.zeros_like(relative_position))
+ # now relative_position is in the range [0, inf)
+
+ # half of the buckets are for exact increments in positions
+ max_exact = num_buckets // 2
+ is_small = relative_position < max_exact
+
+ # The other half of the buckets are for logarithmically bigger bins in positions up to max_distance
+ relative_position_if_large = max_exact + (
+ torch.log(relative_position.float() / max_exact)
+ / math.log(max_distance / max_exact)
+ * (num_buckets - max_exact)
+ ).to(torch.long)
+ relative_position_if_large = torch.min(
+ relative_position_if_large, torch.full_like(relative_position_if_large, num_buckets - 1)
+ )
+
+ relative_buckets += torch.where(is_small, relative_position, relative_position_if_large)
+ return relative_buckets
+
+ def compute_bias(self, query_length, key_length, device=None, past_seen_tokens=0):
+ """Compute binned relative position bias"""
+ if device is None:
+ device = self.relative_attention_bias.weight.device
+ context_position = torch.arange(query_length, dtype=torch.long, device=device)[:, None] + past_seen_tokens
+ memory_position = torch.arange(key_length, dtype=torch.long, device=device)[None, :]
+ relative_position = memory_position - context_position # shape (query_length, key_length)
+ relative_position_bucket = self._relative_position_bucket(
+ relative_position, # shape (query_length, key_length)
+ bidirectional=(not self.is_decoder),
+ num_buckets=self.relative_attention_num_buckets,
+ max_distance=self.relative_attention_max_distance,
+ )
+ values = self.relative_attention_bias(relative_position_bucket) # shape (query_length, key_length, num_heads)
+ values = values.permute([2, 0, 1]).unsqueeze(0) # shape (1, num_heads, query_length, key_length)
+ return values
+
+ def forward(
+ self,
+ hidden_states,
+ mask=None,
+ key_value_states=None,
+ position_bias=None,
+ past_key_values=None,
+ output_attentions=False,
+ **kwargs,
+ ):
+ """
+ Self-attention (if key_value_states is None) or attention over source sentence (provided by key_value_states).
+ """
+ # Input is (batch_size, seq_length, dim)
+ # Mask is (batch_size, 1, 1, key_length) (non-causal encoder) or (batch_size, 1, seq_length, key_length) (causal decoder)
+ input_shape = hidden_states.shape[:-1]
+ hidden_shape = (*input_shape, -1, self.key_value_proj_dim)
+ past_seen_tokens = past_key_values.get_seq_length(self.layer_idx) if past_key_values is not None else 0
+ # We clone here for StaticCache, as we get the value before updating it, but use it after and it's the same ref
+ past_seen_tokens = past_seen_tokens.clone() if isinstance(past_seen_tokens, torch.Tensor) else past_seen_tokens
+
+ # if key_value_states are provided this layer is used as a cross-attention layer for the decoder
+ is_cross_attention = key_value_states is not None
+
+ query_states = self.q(hidden_states).view(hidden_shape).transpose(1, 2)
+
+ # Check is encoder-decoder model is being used. Otherwise we'll get `DynamicCache`
+ is_updated = False
+ if isinstance(past_key_values, EncoderDecoderCache):
+ is_updated = past_key_values.is_updated.get(self.layer_idx)
+ if is_cross_attention:
+ # after the first generated id, we can subsequently re-use all key/value_states from cache
+ curr_past_key_values = past_key_values.cross_attention_cache
+ else:
+ curr_past_key_values = past_key_values.self_attention_cache
+ else:
+ curr_past_key_values = past_key_values
+
+ current_states = key_value_states if is_cross_attention else hidden_states
+ if is_cross_attention and past_key_values is not None and is_updated:
+ # reuse k,v, cross_attentions
+ key_states = curr_past_key_values.layers[self.layer_idx].keys
+ value_states = curr_past_key_values.layers[self.layer_idx].values
+ else:
+ kv_shape = (*current_states.shape[:-1], -1, self.key_value_proj_dim)
+ key_states = self.k(current_states).view(kv_shape).transpose(1, 2)
+ value_states = self.v(current_states).view(kv_shape).transpose(1, 2)
+
+ if past_key_values is not None:
+ key_states, value_states = curr_past_key_values.update(key_states, value_states, self.layer_idx)
+ # set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls
+ if is_cross_attention and isinstance(past_key_values, EncoderDecoderCache):
+ past_key_values.is_updated[self.layer_idx] = True
+
+ # compute scores, equivalent of torch.einsum("bnqd,bnkd->bnqk", query_states, key_states), compatible with onnx op>9
+ scores = torch.matmul(query_states, key_states.transpose(3, 2))
+
+ if position_bias is None:
+ key_length = key_states.shape[-2]
+ if not self.has_relative_attention_bias:
+ position_bias = torch.zeros(
+ (1, query_states.shape[1], input_shape[1], key_length), device=scores.device, dtype=scores.dtype
+ )
+ if self.gradient_checkpointing and self.training:
+ position_bias.requires_grad = True
+ else:
+ position_bias = self.compute_bias(
+ input_shape[1], key_length, device=scores.device, past_seen_tokens=past_seen_tokens
+ )
+
+ if mask is not None:
+ causal_mask = mask[:, :, :, : key_states.shape[-2]]
+ position_bias = position_bias + causal_mask
+
+ position_bias_masked = position_bias
+ scores += position_bias_masked
+
+ # (batch_size, n_heads, seq_length, key_length)
+ attn_weights = nn.functional.softmax(scores.float(), dim=-1).type_as(scores)
+ attn_weights = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
+
+ attn_output = torch.matmul(attn_weights, value_states)
+
+ attn_output = attn_output.transpose(1, 2).contiguous()
+ attn_output = attn_output.reshape(*input_shape, -1)
+ attn_output = self.o(attn_output)
+
+ outputs = (attn_output, position_bias)
+
+ if output_attentions:
+ outputs = outputs + (attn_weights,)
+ return outputs
+
+
+class T5LayerSelfAttention(nn.Module):
+ def __init__(self, config, has_relative_attention_bias=False, layer_idx: int | None = None):
+ super().__init__()
+ self.SelfAttention = T5Attention(
+ config, has_relative_attention_bias=has_relative_attention_bias, layer_idx=layer_idx
+ )
+ self.layer_norm = T5LayerNorm(config.d_model, eps=config.layer_norm_epsilon)
+ self.dropout = nn.Dropout(config.dropout_rate)
+
+ def forward(
+ self,
+ hidden_states,
+ attention_mask=None,
+ position_bias=None,
+ past_key_values=None,
+ use_cache=False,
+ output_attentions=False,
+ **kwargs,
+ ):
+ normed_hidden_states = self.layer_norm(hidden_states)
+ attention_output = self.SelfAttention(
+ normed_hidden_states,
+ mask=attention_mask,
+ position_bias=position_bias,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ )
+ hidden_states = hidden_states + self.dropout(attention_output[0])
+ outputs = (hidden_states,) + attention_output[1:] # add attentions if we output them
+ return outputs
+
+
+class T5LayerCrossAttention(nn.Module):
+ def __init__(self, config, layer_idx: int | None = None):
+ super().__init__()
+ self.EncDecAttention = T5Attention(config, has_relative_attention_bias=False, layer_idx=layer_idx)
+ self.layer_norm = T5LayerNorm(config.d_model, eps=config.layer_norm_epsilon)
+ self.dropout = nn.Dropout(config.dropout_rate)
+
+ def forward(
+ self,
+ hidden_states,
+ key_value_states,
+ attention_mask=None,
+ position_bias=None,
+ past_key_values=None,
+ output_attentions=False,
+ **kwargs,
+ ):
+ normed_hidden_states = self.layer_norm(hidden_states)
+ attention_output = self.EncDecAttention(
+ normed_hidden_states,
+ mask=attention_mask,
+ key_value_states=key_value_states,
+ position_bias=position_bias,
+ past_key_values=past_key_values,
+ output_attentions=output_attentions,
+ )
+ layer_output = hidden_states + self.dropout(attention_output[0])
+ outputs = (layer_output,) + attention_output[1:] # add attentions if we output them
+ return outputs
+
+
+class T5Block(GradientCheckpointingLayer):
+ def __init__(self, config, has_relative_attention_bias=False, layer_idx: int | None = None):
+ super().__init__()
+ self.is_decoder = config.is_decoder
+ self.layer = nn.ModuleList()
+ self.layer.append(
+ T5LayerSelfAttention(config, has_relative_attention_bias=has_relative_attention_bias, layer_idx=layer_idx)
+ )
+ if self.is_decoder:
+ self.layer.append(T5LayerCrossAttention(config, layer_idx=layer_idx))
+
+ self.layer.append(T5LayerFF(config))
+
+ def forward(
+ self,
+ hidden_states,
+ attention_mask=None,
+ position_bias=None,
+ encoder_hidden_states=None,
+ encoder_attention_mask=None,
+ encoder_decoder_position_bias=None,
+ past_key_values=None,
+ use_cache=False,
+ output_attentions=False,
+ return_dict=True,
+ **kwargs,
+ ):
+ self_attention_outputs = self.layer[0](
+ hidden_states,
+ attention_mask=attention_mask,
+ position_bias=position_bias,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ )
+ hidden_states = self_attention_outputs[0]
+ attention_outputs = self_attention_outputs[1:] # Keep self-attention outputs and relative position weights
+
+ # clamp inf values to enable fp16 training
+ if hidden_states.dtype == torch.float16:
+ clamp_value = torch.where(
+ torch.isinf(hidden_states).any(),
+ torch.finfo(hidden_states.dtype).max - 1000,
+ torch.finfo(hidden_states.dtype).max,
+ )
+ hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
+
+ do_cross_attention = self.is_decoder and encoder_hidden_states is not None
+ if do_cross_attention:
+ cross_attention_outputs = self.layer[1](
+ hidden_states,
+ key_value_states=encoder_hidden_states,
+ attention_mask=encoder_attention_mask,
+ position_bias=encoder_decoder_position_bias,
+ past_key_values=past_key_values,
+ output_attentions=output_attentions,
+ )
+ hidden_states = cross_attention_outputs[0]
+
+ # clamp inf values to enable fp16 training
+ if hidden_states.dtype == torch.float16:
+ clamp_value = torch.where(
+ torch.isinf(hidden_states).any(),
+ torch.finfo(hidden_states.dtype).max - 1000,
+ torch.finfo(hidden_states.dtype).max,
+ )
+ hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
+
+ # Keep cross-attention outputs and relative position weights
+ attention_outputs = attention_outputs + cross_attention_outputs[1:]
+
+ # Apply Feed Forward layer
+ hidden_states = self.layer[-1](hidden_states)
+
+ # clamp inf values to enable fp16 training
+ if hidden_states.dtype == torch.float16:
+ clamp_value = torch.where(
+ torch.isinf(hidden_states).any(),
+ torch.finfo(hidden_states.dtype).max - 1000,
+ torch.finfo(hidden_states.dtype).max,
+ )
+ hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
+
+ outputs = (hidden_states,)
+
+ return (
+ outputs + attention_outputs
+ ) # hidden-states, (self-attention position bias), (self-attention weights), (cross-attention position bias), (cross-attention weights)
+
+
+class T5ClassificationHead(nn.Module):
+ """Head for sentence-level classification tasks."""
+
+ def __init__(self, config: T5Config):
+ super().__init__()
+ self.dense = nn.Linear(config.d_model, config.d_model)
+ self.dropout = nn.Dropout(p=config.classifier_dropout)
+ self.out_proj = nn.Linear(config.d_model, config.num_labels)
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = self.dense(hidden_states)
+ hidden_states = torch.tanh(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = self.out_proj(hidden_states)
+ return hidden_states
+
+
+@auto_docstring
+class T5PreTrainedModel(PreTrainedModel):
+ config: T5Config
+ base_model_prefix = "transformer"
+ supports_gradient_checkpointing = True
+ _can_compile_fullgraph = True
+
+ _no_split_modules = ["T5Block"]
+ _keep_in_fp32_modules = ["wo"]
+
+ @property
+ def dummy_inputs(self):
+ input_ids = torch.tensor(DUMMY_INPUTS)
+ input_mask = torch.tensor(DUMMY_MASK)
+ dummy_inputs = {
+ "decoder_input_ids": input_ids,
+ "input_ids": input_ids,
+ "decoder_attention_mask": input_mask,
+ }
+ return dummy_inputs
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ """Initialize the weights"""
+ factor = self.config.initializer_factor # Used for testing weights initialization
+ if isinstance(module, T5LayerNorm):
+ init.constant_(module.weight, factor * 1.0)
+ elif isinstance(
+ module,
+ (T5Model, T5ForConditionalGeneration, T5EncoderModel, T5ForQuestionAnswering),
+ ):
+ init.normal_(module.shared.weight, mean=0.0, std=factor * 1.0)
+ if hasattr(module, "lm_head") and not self.config.tie_word_embeddings:
+ init.normal_(module.lm_head.weight, mean=0.0, std=factor * 1.0)
+ if hasattr(module, "qa_outputs"):
+ init.normal_(module.qa_outputs.weight, mean=0.0, std=factor * ((self.config.d_model) ** -0.5))
+ init.zeros_(module.qa_outputs.bias)
+ elif isinstance(module, T5ForTokenClassification):
+ if hasattr(module, "classifier"):
+ init.normal_(module.classifier.weight, mean=0.0, std=factor * 1.0)
+ init.zeros_(module.classifier.bias)
+ elif isinstance(module, T5ClassificationHead):
+ init.normal_(module.dense.weight, mean=0.0, std=factor * ((self.config.d_model) ** -0.5))
+ if hasattr(module.dense, "bias") and module.dense.bias is not None:
+ init.zeros_(module.dense.bias)
+ init.normal_(module.out_proj.weight, mean=0.0, std=factor * ((self.config.d_model) ** -0.5))
+ if hasattr(module.out_proj, "bias") and module.out_proj.bias is not None:
+ init.zeros_(module.out_proj.bias)
+ elif isinstance(module, T5DenseActDense):
+ init.normal_(module.wi.weight, mean=0.0, std=factor * ((self.config.d_model) ** -0.5))
+ if hasattr(module.wi, "bias") and module.wi.bias is not None:
+ init.zeros_(module.wi.bias)
+ init.normal_(module.wo.weight, mean=0.0, std=factor * ((self.config.d_ff) ** -0.5))
+ if hasattr(module.wo, "bias") and module.wo.bias is not None:
+ init.zeros_(module.wo.bias)
+ elif isinstance(module, T5DenseGatedActDense):
+ init.normal_(module.wi_0.weight, mean=0.0, std=factor * ((self.config.d_model) ** -0.5))
+ if hasattr(module.wi_0, "bias") and module.wi_0.bias is not None:
+ init.zeros_(module.wi_0.bias)
+ init.normal_(module.wi_1.weight, mean=0.0, std=factor * ((self.config.d_model) ** -0.5))
+ if hasattr(module.wi_1, "bias") and module.wi_1.bias is not None:
+ init.zeros_(module.wi_1.bias)
+ init.normal_(module.wo.weight, mean=0.0, std=factor * ((self.config.d_ff) ** -0.5))
+ if hasattr(module.wo, "bias") and module.wo.bias is not None:
+ init.zeros_(module.wo.bias)
+ elif isinstance(module, T5Attention):
+ d_model = self.config.d_model
+ key_value_proj_dim = self.config.d_kv
+ n_heads = self.config.num_heads
+ init.normal_(module.q.weight, mean=0.0, std=factor * ((d_model * key_value_proj_dim) ** -0.5))
+ init.normal_(module.k.weight, mean=0.0, std=factor * (d_model**-0.5))
+ init.normal_(module.v.weight, mean=0.0, std=factor * (d_model**-0.5))
+ init.normal_(module.o.weight, mean=0.0, std=factor * ((n_heads * key_value_proj_dim) ** -0.5))
+ if module.has_relative_attention_bias:
+ init.normal_(module.relative_attention_bias.weight, mean=0.0, std=factor * ((d_model) ** -0.5))
+
+ def _shift_right(self, input_ids):
+ decoder_start_token_id = self.config.decoder_start_token_id
+ pad_token_id = self.config.pad_token_id
+
+ if decoder_start_token_id is None:
+ raise ValueError(
+ "self.model.config.decoder_start_token_id has to be defined. In T5 it is usually set to the pad_token_id. "
+ "See T5 docs for more information."
+ )
+
+ shifted_input_ids = input_ids.new_zeros(input_ids.shape)
+ shifted_input_ids[..., 1:] = input_ids[..., :-1].clone()
+ shifted_input_ids[..., 0] = decoder_start_token_id
+
+ if pad_token_id is None:
+ raise ValueError("self.model.config.pad_token_id has to be defined.")
+ # replace possible -100 values in labels by `pad_token_id`
+ shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id)
+
+ return shifted_input_ids
+
+
+class T5Stack(T5PreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.d_model)
+ self.is_decoder = config.is_decoder
+
+ self.block = nn.ModuleList(
+ [T5Block(config, has_relative_attention_bias=bool(i == 0), layer_idx=i) for i in range(config.num_layers)]
+ )
+ self.final_layer_norm = T5LayerNorm(config.d_model, eps=config.layer_norm_epsilon)
+ self.dropout = nn.Dropout(config.dropout_rate)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+ self.gradient_checkpointing = False
+
+ def set_input_embeddings(self, new_embeddings):
+ self.embed_tokens = new_embeddings
+
+ def forward(
+ self,
+ input_ids=None,
+ attention_mask=None,
+ encoder_hidden_states=None,
+ encoder_attention_mask=None,
+ inputs_embeds=None,
+ past_key_values=None,
+ use_cache=None,
+ output_attentions=None,
+ output_hidden_states=None,
+ return_dict=None,
+ **kwargs,
+ ):
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ if input_ids is not None and inputs_embeds is not None:
+ err_msg_prefix = "decoder_" if self.is_decoder else ""
+ raise ValueError(
+ f"You cannot specify both {err_msg_prefix}input_ids and {err_msg_prefix}inputs_embeds at the same time"
+ )
+ elif input_ids is not None:
+ input_shape = input_ids.size()
+ input_ids = input_ids.view(-1, input_shape[-1])
+ elif inputs_embeds is not None:
+ input_shape = inputs_embeds.size()[:-1]
+ else:
+ err_msg_prefix = "decoder_" if self.is_decoder else ""
+ raise ValueError(f"You have to specify either {err_msg_prefix}input_ids or {err_msg_prefix}inputs_embeds")
+
+ if self.gradient_checkpointing and self.training:
+ if use_cache:
+ logger.warning_once(
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
+ )
+ use_cache = False
+
+ if inputs_embeds is None:
+ if self.embed_tokens is None:
+ raise ValueError("You have to initialize the model with valid token embeddings")
+ inputs_embeds = self.embed_tokens(input_ids)
+
+ batch_size, seq_length = input_shape
+
+ if use_cache is True:
+ if not self.is_decoder:
+ raise ValueError(f"`use_cache` can only be set to `True` if {self} is used as a decoder")
+
+ if self.is_decoder:
+ if use_cache and past_key_values is None:
+ if self.config.is_encoder_decoder:
+ past_key_values = EncoderDecoderCache(
+ DynamicCache(config=self.config), DynamicCache(config=self.config)
+ )
+ else:
+ past_key_values = DynamicCache(config=self.config)
+ elif not self.is_decoder:
+ # do not pass cache object down the line for encoder stack
+ # it messes indexing later in decoder-stack because cache object is modified in-place
+ past_key_values = None
+
+ if self.config.is_decoder:
+ attention_mask = create_causal_mask(
+ config=self.config,
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values.self_attention_cache
+ if isinstance(past_key_values, EncoderDecoderCache)
+ else past_key_values,
+ )
+ else:
+ attention_mask = create_bidirectional_mask(
+ config=self.config,
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ )
+
+ encoder_extended_attention_mask = None
+ if self.is_decoder and encoder_hidden_states is not None:
+ encoder_extended_attention_mask = create_bidirectional_mask(
+ config=self.config,
+ inputs_embeds=inputs_embeds,
+ attention_mask=encoder_attention_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ )
+
+ all_hidden_states = () if output_hidden_states else None
+ all_attentions = () if output_attentions else None
+ all_cross_attentions = () if (output_attentions and self.is_decoder) else None
+ position_bias = None
+ encoder_decoder_position_bias = None
+
+ hidden_states = self.dropout(inputs_embeds)
+
+ for layer_module in self.block:
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ layer_outputs = layer_module(
+ hidden_states,
+ attention_mask,
+ position_bias,
+ encoder_hidden_states,
+ encoder_extended_attention_mask,
+ encoder_decoder_position_bias, # as a positional argument for gradient checkpointing
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ return_dict=return_dict,
+ )
+
+ hidden_states = layer_outputs[0]
+
+ # We share the position biases between the layers - the first layer store them
+ # layer_outputs = hidden-states, key-value-states (self-attention position bias), (self-attention weights),
+ # (cross-attention position bias), (cross-attention weights)
+ position_bias = layer_outputs[1]
+ if self.is_decoder and encoder_hidden_states is not None:
+ encoder_decoder_position_bias = layer_outputs[3 if output_attentions else 2]
+
+ if output_attentions:
+ all_attentions = all_attentions + (layer_outputs[2],)
+ if self.is_decoder:
+ all_cross_attentions = all_cross_attentions + (layer_outputs[4],)
+
+ hidden_states = self.final_layer_norm(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+
+ # Add last layer
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ if not return_dict:
+ return tuple(
+ v
+ for v in [
+ hidden_states,
+ past_key_values,
+ all_hidden_states,
+ all_attentions,
+ all_cross_attentions,
+ ]
+ if v is not None
+ )
+ return BaseModelOutputWithPastAndCrossAttentions(
+ last_hidden_state=hidden_states,
+ past_key_values=past_key_values,
+ hidden_states=all_hidden_states,
+ attentions=all_attentions,
+ cross_attentions=all_cross_attentions,
+ )
+
+
+@auto_docstring
+class T5Model(T5PreTrainedModel):
+ _keys_to_ignore_on_load_unexpected = [
+ "decoder.block.0.layer.1.EncDecAttention.relative_attention_bias.weight",
+ ]
+ _tied_weights_keys = {
+ "encoder.embed_tokens.weight": "shared.weight",
+ "decoder.embed_tokens.weight": "shared.weight",
+ }
+
+ def __init__(self, config: T5Config):
+ super().__init__(config)
+ self.shared = nn.Embedding(config.vocab_size, config.d_model)
+
+ encoder_config = copy.deepcopy(config)
+ encoder_config.is_decoder = False
+ encoder_config.use_cache = False
+ self.encoder = T5Stack(encoder_config)
+
+ decoder_config = copy.deepcopy(config)
+ decoder_config.is_decoder = True
+ decoder_config.num_layers = config.num_decoder_layers
+ self.decoder = T5Stack(decoder_config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.shared
+
+ def set_input_embeddings(self, new_embeddings):
+ self.shared = new_embeddings
+ self.encoder.set_input_embeddings(new_embeddings)
+ self.decoder.set_input_embeddings(new_embeddings)
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ decoder_input_ids: torch.LongTensor | None = None,
+ decoder_attention_mask: torch.BoolTensor | None = None,
+ encoder_outputs: tuple[tuple[torch.FloatTensor]] | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ decoder_inputs_embeds: torch.Tensor | None = None,
+ use_cache: bool | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple[torch.FloatTensor] | Seq2SeqModelOutput:
+ r"""
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary. T5 is a model with relative position embeddings so you
+ should be able to pad the inputs on both the right and the left.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for detail.
+
+ [What are input IDs?](../glossary#input-ids)
+
+ To know more on how to prepare `input_ids` for pretraining take a look a [T5 Training](./t5#training).
+ decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
+ Indices of decoder input sequence tokens in the vocabulary.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are decoder input IDs?](../glossary#decoder-input-ids)
+
+ T5 uses the `pad_token_id` as the starting token for `decoder_input_ids` generation. If `past_key_values`
+ is used, optionally only the last `decoder_input_ids` have to be input (see `past_key_values`).
+
+ To know more on how to prepare `decoder_input_ids` for pretraining take a look at [T5
+ Training](./t5#training).
+ decoder_attention_mask (`torch.BoolTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
+ Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
+ be used by default.
+
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, T5Model
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("google-t5/t5-small")
+ >>> model = T5Model.from_pretrained("google-t5/t5-small")
+
+ >>> input_ids = tokenizer(
+ ... "Studies have been shown that owning a dog is good for you", return_tensors="pt"
+ ... ).input_ids # Batch size 1
+ >>> decoder_input_ids = tokenizer("Studies show that", return_tensors="pt").input_ids # Batch size 1
+
+ >>> # preprocess: Prepend decoder_input_ids with start token which is pad token for T5Model.
+ >>> # This is not needed for torch's T5ForConditionalGeneration as it does this internally using labels arg.
+ >>> decoder_input_ids = model._shift_right(decoder_input_ids)
+
+ >>> # forward pass
+ >>> outputs = model(input_ids=input_ids, decoder_input_ids=decoder_input_ids)
+ >>> last_hidden_states = outputs.last_hidden_state
+ ```"""
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ # Encode if needed (training, first prediction pass)
+ if encoder_outputs is None:
+ encoder_outputs = self.encoder(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+ elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):
+ encoder_outputs = BaseModelOutput(
+ last_hidden_state=encoder_outputs[0],
+ hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
+ attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
+ )
+
+ hidden_states = encoder_outputs[0]
+
+ # Decode
+ decoder_outputs = self.decoder(
+ input_ids=decoder_input_ids,
+ attention_mask=decoder_attention_mask,
+ inputs_embeds=decoder_inputs_embeds,
+ past_key_values=past_key_values,
+ encoder_hidden_states=hidden_states,
+ encoder_attention_mask=attention_mask,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ if not return_dict:
+ return decoder_outputs + encoder_outputs
+
+ return Seq2SeqModelOutput(
+ last_hidden_state=decoder_outputs.last_hidden_state,
+ past_key_values=decoder_outputs.past_key_values,
+ decoder_hidden_states=decoder_outputs.hidden_states,
+ decoder_attentions=decoder_outputs.attentions,
+ cross_attentions=decoder_outputs.cross_attentions,
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
+ encoder_hidden_states=encoder_outputs.hidden_states,
+ encoder_attentions=encoder_outputs.attentions,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ T5 Model with a `language modeling` head on top.
+ """
+)
+class T5ForConditionalGeneration(T5PreTrainedModel, GenerationMixin):
+ _keys_to_ignore_on_load_unexpected = [
+ "decoder.block.0.layer.1.EncDecAttention.relative_attention_bias.weight",
+ ]
+ _tied_weights_keys = {
+ "lm_head.weight": "shared.weight",
+ "encoder.embed_tokens.weight": "shared.weight",
+ "decoder.embed_tokens.weight": "shared.weight",
+ }
+
+ def __init__(self, config: T5Config):
+ super().__init__(config)
+ self.model_dim = config.d_model
+
+ self.shared = nn.Embedding(config.vocab_size, config.d_model)
+
+ encoder_config = copy.deepcopy(config)
+ encoder_config.is_decoder = False
+ encoder_config.use_cache = False
+ self.encoder = T5Stack(encoder_config)
+
+ decoder_config = copy.deepcopy(config)
+ decoder_config.is_decoder = True
+ decoder_config.num_layers = config.num_decoder_layers
+ self.decoder = T5Stack(decoder_config)
+
+ self.lm_head = nn.Linear(config.d_model, config.vocab_size, bias=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.shared
+
+ def set_input_embeddings(self, new_embeddings):
+ self.shared = new_embeddings
+ self.encoder.set_input_embeddings(new_embeddings)
+ self.decoder.set_input_embeddings(new_embeddings)
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ decoder_input_ids: torch.LongTensor | None = None,
+ decoder_attention_mask: torch.BoolTensor | None = None,
+ encoder_outputs: tuple[tuple[torch.Tensor]] | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ decoder_inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ use_cache: bool | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple[torch.FloatTensor] | Seq2SeqLMOutput:
+ r"""
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary. T5 is a model with relative position embeddings so you
+ should be able to pad the inputs on both the right and the left.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for detail.
+
+ [What are input IDs?](../glossary#input-ids)
+
+ To know more on how to prepare `input_ids` for pretraining take a look a [T5 Training](./t5#training).
+ decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
+ Indices of decoder input sequence tokens in the vocabulary.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are decoder input IDs?](../glossary#decoder-input-ids)
+
+ T5 uses the `pad_token_id` as the starting token for `decoder_input_ids` generation. If `past_key_values`
+ is used, optionally only the last `decoder_input_ids` have to be input (see `past_key_values`).
+
+ To know more on how to prepare `decoder_input_ids` for pretraining take a look at [T5
+ Training](./t5#training).
+ decoder_attention_mask (`torch.BoolTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
+ Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
+ be used by default.
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[-100, 0, ...,
+ config.vocab_size - 1]`. All labels set to `-100` are ignored (masked), the loss is only computed for
+ labels in `[0, ..., config.vocab_size]`
+
+ Examples:
+
+ ```python
+ >>> from transformers import AutoTokenizer, T5ForConditionalGeneration
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("google-t5/t5-small")
+ >>> model = T5ForConditionalGeneration.from_pretrained("google-t5/t5-small")
+
+ >>> # training
+ >>> input_ids = tokenizer("The walks in park", return_tensors="pt").input_ids
+ >>> labels = tokenizer(" cute dog the ", return_tensors="pt").input_ids
+ >>> outputs = model(input_ids=input_ids, labels=labels)
+ >>> loss = outputs.loss
+ >>> logits = outputs.logits
+
+ >>> # inference
+ >>> input_ids = tokenizer(
+ ... "summarize: studies have shown that owning a dog is good for you", return_tensors="pt"
+ ... ).input_ids # Batch size 1
+ >>> outputs = model.generate(input_ids)
+ >>> print(tokenizer.decode(outputs[0], skip_special_tokens=True))
+ >>> # studies have shown that owning a dog is good for you.
+ ```"""
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ # Encode if needed (training, first prediction pass)
+ if encoder_outputs is None:
+ # Convert encoder inputs in embeddings if needed
+ encoder_outputs = self.encoder(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+ elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):
+ encoder_outputs = BaseModelOutput(
+ last_hidden_state=encoder_outputs[0],
+ hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
+ attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
+ )
+
+ hidden_states = encoder_outputs[0]
+
+ if labels is not None and decoder_input_ids is None and decoder_inputs_embeds is None:
+ # get decoder inputs from shifting lm labels to the right
+ decoder_input_ids = self._shift_right(labels)
+
+ # Decode
+ decoder_outputs = self.decoder(
+ input_ids=decoder_input_ids,
+ attention_mask=decoder_attention_mask,
+ inputs_embeds=decoder_inputs_embeds,
+ past_key_values=past_key_values,
+ encoder_hidden_states=hidden_states,
+ encoder_attention_mask=attention_mask,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ sequence_output = decoder_outputs[0]
+
+ if self.config.scale_decoder_outputs:
+ sequence_output = sequence_output * (self.model_dim**-0.5)
+
+ lm_logits = self.lm_head(sequence_output)
+
+ loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss(ignore_index=-100)
+ # move labels to correct device to enable PP
+ labels = labels.to(lm_logits.device)
+ loss = loss_fct(lm_logits.view(-1, lm_logits.size(-1)), labels.view(-1))
+
+ if not return_dict:
+ output = (lm_logits,) + decoder_outputs[1:] + encoder_outputs
+ return ((loss,) + output) if loss is not None else output
+
+ return Seq2SeqLMOutput(
+ loss=loss,
+ logits=lm_logits,
+ past_key_values=decoder_outputs.past_key_values,
+ decoder_hidden_states=decoder_outputs.hidden_states,
+ decoder_attentions=decoder_outputs.attentions,
+ cross_attentions=decoder_outputs.cross_attentions,
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
+ encoder_hidden_states=encoder_outputs.hidden_states,
+ encoder_attentions=encoder_outputs.attentions,
+ )
+
+ def prepare_decoder_input_ids_from_labels(self, labels: torch.Tensor):
+ return self._shift_right(labels)
+
+
+@auto_docstring
+class T5EncoderModel(T5PreTrainedModel):
+ _tied_weights_keys = {"encoder.embed_tokens.weight": "shared.weight"}
+ _keys_to_ignore_on_load_unexpected = [r"decoder"]
+
+ def __init__(self, config: T5Config):
+ super().__init__(config)
+ self.shared = nn.Embedding(config.vocab_size, config.d_model)
+
+ encoder_config = config
+ encoder_config.use_cache = False
+ encoder_config.is_encoder_decoder = False
+ self.encoder = T5Stack(encoder_config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.shared
+
+ def set_input_embeddings(self, new_embeddings):
+ self.shared = new_embeddings
+ self.encoder.set_input_embeddings(new_embeddings)
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple[torch.FloatTensor] | BaseModelOutput:
+ r"""
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary. T5 is a model with relative position embeddings so you
+ should be able to pad the inputs on both the right and the left.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for detail.
+
+ To know more on how to prepare `input_ids` for pretraining take a look a [T5 Training](./t5#training).
+
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, T5EncoderModel
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("google-t5/t5-small")
+ >>> model = T5EncoderModel.from_pretrained("google-t5/t5-small")
+ >>> input_ids = tokenizer(
+ ... "Studies have been shown that owning a dog is good for you", return_tensors="pt"
+ ... ).input_ids # Batch size 1
+ >>> outputs = model(input_ids=input_ids)
+ >>> last_hidden_states = outputs.last_hidden_state
+ ```"""
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ encoder_outputs = self.encoder(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ return encoder_outputs
+
+
+@auto_docstring(
+ custom_intro="""
+ T5 model with a sequence classification/head on top (a linear layer on top of the pooled output) e.g. for GLUE
+ tasks.
+ """
+)
+class T5ForSequenceClassification(T5PreTrainedModel):
+ _keys_to_ignore_on_load_unexpected = ["decoder.block.0.layer.1.EncDecAttention.relative_attention_bias.weight"]
+
+ def __init__(self, config: T5Config):
+ super().__init__(config)
+ self.transformer = T5Model(config)
+ self.classification_head = T5ClassificationHead(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ decoder_input_ids: torch.LongTensor | None = None,
+ decoder_attention_mask: torch.LongTensor | None = None,
+ encoder_outputs: list[torch.FloatTensor] | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ decoder_inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ use_cache: bool | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple | Seq2SeqSequenceClassifierOutput:
+ r"""
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary. T5 is a model with relative position embeddings so you
+ should be able to pad the inputs on both the right and the left.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for detail.
+
+ [What are input IDs?](../glossary#input-ids)
+
+ To know more on how to prepare `input_ids` for pretraining take a look a [T5 Training](./t5#training).
+ decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
+ Indices of decoder input sequence tokens in the vocabulary.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are decoder input IDs?](../glossary#decoder-input-ids)
+
+ T5 uses the `pad_token_id` as the starting token for `decoder_input_ids` generation. If `past_key_values`
+ is used, optionally only the last `decoder_input_ids` have to be input (see `past_key_values`).
+
+ To know more on how to prepare `decoder_input_ids` for pretraining take a look at [T5
+ Training](./t5#training).
+ decoder_attention_mask (`torch.BoolTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
+ Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
+ be used by default.
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+ if labels is not None:
+ use_cache = False
+
+ if input_ids is None and inputs_embeds is not None:
+ raise NotImplementedError(
+ f"Passing input embeddings is currently not supported for {self.__class__.__name__}"
+ )
+
+ # Copied from models.bart.modeling_bart.BartModel.forward different to other models, T5 automatically creates
+ # decoder_input_ids from input_ids if no decoder_input_ids are provided
+ if decoder_input_ids is None and decoder_inputs_embeds is None:
+ if input_ids is None:
+ raise ValueError(
+ "If no `decoder_input_ids` or `decoder_inputs_embeds` are "
+ "passed, `input_ids` cannot be `None`. Please pass either "
+ "`input_ids` or `decoder_input_ids` or `decoder_inputs_embeds`."
+ )
+ decoder_input_ids = self._shift_right(input_ids)
+
+ outputs = self.transformer(
+ input_ids,
+ attention_mask=attention_mask,
+ decoder_input_ids=decoder_input_ids,
+ decoder_attention_mask=decoder_attention_mask,
+ encoder_outputs=encoder_outputs,
+ inputs_embeds=inputs_embeds,
+ decoder_inputs_embeds=decoder_inputs_embeds,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+ sequence_output = outputs[0]
+
+ eos_mask = input_ids.eq(self.config.eos_token_id).to(sequence_output.device)
+
+ torch_compilable_check(
+ torch.unique_consecutive(eos_mask.sum(1)).numel() == 1,
+ "All examples must have the same number of tokens.",
+ )
+ batch_size, _, hidden_size = sequence_output.shape
+ sentence_representation = sequence_output[eos_mask, :].view(batch_size, -1, hidden_size)[:, -1, :]
+ logits = self.classification_head(sentence_representation)
+
+ loss = None
+ if labels is not None:
+ labels = labels.to(logits.device)
+ if self.config.problem_type is None:
+ if self.config.num_labels == 1:
+ self.config.problem_type = "regression"
+ elif self.config.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
+ self.config.problem_type = "single_label_classification"
+ else:
+ self.config.problem_type = "multi_label_classification"
+
+ if self.config.problem_type == "regression":
+ loss_fct = MSELoss()
+ if self.config.num_labels == 1:
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
+ else:
+ loss = loss_fct(logits, labels)
+ elif self.config.problem_type == "single_label_classification":
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.config.num_labels), labels.view(-1))
+ elif self.config.problem_type == "multi_label_classification":
+ loss_fct = BCEWithLogitsLoss()
+ loss = loss_fct(logits, labels)
+ if not return_dict:
+ output = (logits,) + outputs[1:]
+ return ((loss,) + output) if loss is not None else output
+
+ return Seq2SeqSequenceClassifierOutput(
+ loss=loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ decoder_hidden_states=outputs.decoder_hidden_states,
+ decoder_attentions=outputs.decoder_attentions,
+ cross_attentions=outputs.cross_attentions,
+ encoder_last_hidden_state=outputs.encoder_last_hidden_state,
+ encoder_hidden_states=outputs.encoder_hidden_states,
+ encoder_attentions=outputs.encoder_attentions,
+ )
+
+
+@auto_docstring
+class T5ForTokenClassification(T5PreTrainedModel):
+ def __init__(self, config: T5Config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+
+ self.transformer = T5EncoderModel(config)
+ self.dropout = nn.Dropout(config.classifier_dropout)
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ labels: torch.Tensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple[torch.Tensor] | TokenClassifierOutput:
+ r"""
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary. T5 is a model with relative position embeddings so you
+ should be able to pad the inputs on both the right and the left.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for detail.
+
+ [What are input IDs?](../glossary#input-ids)
+
+ To know more on how to prepare `input_ids` for pretraining take a look a [T5 Training](./t5#training).
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
+ """
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ outputs = self.transformer(
+ input_ids,
+ attention_mask=attention_mask,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ hidden_states = outputs[0]
+ hidden_states = self.dropout(hidden_states)
+ logits = self.classifier(hidden_states)
+
+ loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+
+ if not return_dict:
+ output = (logits, outputs[2:-1])
+ return ((loss,) + output) if loss is not None else output
+
+ return TokenClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+class T5ForQuestionAnswering(T5PreTrainedModel):
+ _keys_to_ignore_on_load_unexpected = ["decoder.block.0.layer.1.EncDecAttention.relative_attention_bias.weight"]
+ _tied_weights_keys = {
+ "encoder.embed_tokens.weight": "shared.weight",
+ "decoder.embed_tokens.weight": "shared.weight",
+ }
+
+ def __init__(self, config: T5Config):
+ super().__init__(config)
+ self.model_dim = config.d_model
+
+ self.shared = nn.Embedding(config.vocab_size, config.d_model)
+
+ encoder_config = copy.deepcopy(config)
+ encoder_config.is_decoder = False
+ encoder_config.use_cache = False
+ self.encoder = T5Stack(encoder_config)
+
+ decoder_config = copy.deepcopy(config)
+ decoder_config.is_decoder = True
+ decoder_config.num_layers = config.num_decoder_layers
+ self.decoder = T5Stack(decoder_config)
+
+ self.num_labels = config.num_labels
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.shared
+
+ def set_input_embeddings(self, new_embeddings):
+ self.shared = new_embeddings
+ self.encoder.set_input_embeddings(new_embeddings)
+ self.decoder.set_input_embeddings(new_embeddings)
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ decoder_input_ids: torch.LongTensor | None = None,
+ decoder_attention_mask: torch.BoolTensor | None = None,
+ encoder_outputs: tuple[tuple[torch.Tensor]] | None = None,
+ start_positions: torch.LongTensor | None = None,
+ end_positions: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ decoder_inputs_embeds: torch.FloatTensor | None = None,
+ use_cache: bool | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple[torch.FloatTensor] | Seq2SeqQuestionAnsweringModelOutput:
+ r"""
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary. T5 is a model with relative position embeddings so you
+ should be able to pad the inputs on both the right and the left.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for detail.
+
+ [What are input IDs?](../glossary#input-ids)
+
+ To know more on how to prepare `input_ids` for pretraining take a look a [T5 Training](./t5#training).
+ decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
+ Indices of decoder input sequence tokens in the vocabulary.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are decoder input IDs?](../glossary#decoder-input-ids)
+
+ T5 uses the `pad_token_id` as the starting token for `decoder_input_ids` generation. If `past_key_values`
+ is used, optionally only the last `decoder_input_ids` have to be input (see `past_key_values`).
+
+ To know more on how to prepare `decoder_input_ids` for pretraining take a look at [T5
+ Training](./t5#training).
+ decoder_attention_mask (`torch.BoolTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
+ Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
+ be used by default.
+ """
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
+ if start_positions is not None and end_positions is not None:
+ use_cache = False
+
+ # Copied from models.bart.modeling_bart.BartModel.forward
+ # different to other models, T5 automatically creates decoder_input_ids from
+ # input_ids if no decoder_input_ids are provided
+ if decoder_input_ids is None and decoder_inputs_embeds is None:
+ if input_ids is None:
+ raise ValueError(
+ "If no `decoder_input_ids` or `decoder_inputs_embeds` are "
+ "passed, `input_ids` cannot be `None`. Please pass either "
+ "`input_ids` or `decoder_input_ids` or `decoder_inputs_embeds`."
+ )
+ decoder_input_ids = self._shift_right(input_ids)
+
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ # Encode if needed (training, first prediction pass)
+ if encoder_outputs is None:
+ encoder_outputs = self.encoder(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+ elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):
+ encoder_outputs = BaseModelOutput(
+ last_hidden_state=encoder_outputs[0],
+ hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
+ attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
+ )
+
+ hidden_states = encoder_outputs[0]
+
+ # Decode
+ decoder_outputs = self.decoder(
+ input_ids=decoder_input_ids,
+ attention_mask=decoder_attention_mask,
+ inputs_embeds=decoder_inputs_embeds,
+ past_key_values=None,
+ encoder_hidden_states=hidden_states,
+ encoder_attention_mask=attention_mask,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ sequence_output = decoder_outputs[0]
+
+ logits = self.qa_outputs(sequence_output)
+ start_logits, end_logits = logits.split(1, dim=-1)
+ start_logits = start_logits.squeeze(-1).contiguous()
+ end_logits = end_logits.squeeze(-1).contiguous()
+
+ total_loss = None
+ if start_positions is not None and end_positions is not None:
+ # If we are on multi-GPU, split add a dimension
+ if len(start_positions.size()) > 1:
+ start_positions = start_positions.squeeze(-1).to(start_logits.device)
+ if len(end_positions.size()) > 1:
+ end_positions = end_positions.squeeze(-1).to(end_logits.device)
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
+ ignored_index = start_logits.size(1)
+ start_positions = start_positions.clamp(0, ignored_index)
+ end_positions = end_positions.clamp(0, ignored_index)
+
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
+ start_loss = loss_fct(start_logits, start_positions)
+ end_loss = loss_fct(end_logits, end_positions)
+ total_loss = (start_loss + end_loss) / 2
+
+ if not return_dict:
+ output = (start_logits, end_logits) + decoder_outputs[1:] + encoder_outputs
+ return ((total_loss,) + output) if total_loss is not None else output
+
+ return Seq2SeqQuestionAnsweringModelOutput(
+ loss=total_loss,
+ start_logits=start_logits,
+ end_logits=end_logits,
+ past_key_values=decoder_outputs.past_key_values,
+ decoder_hidden_states=decoder_outputs.hidden_states,
+ decoder_attentions=decoder_outputs.attentions,
+ cross_attentions=decoder_outputs.cross_attentions,
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
+ encoder_hidden_states=encoder_outputs.hidden_states,
+ encoder_attentions=encoder_outputs.attentions,
+ )
+
+
+__all__ = [
+ "T5EncoderModel",
+ "T5ForConditionalGeneration",
+ "T5Model",
+ "T5PreTrainedModel",
+ "T5ForQuestionAnswering",
+ "T5ForSequenceClassification",
+ "T5ForTokenClassification",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/t5/tokenization_t5.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/t5/tokenization_t5.py
new file mode 100644
index 0000000000000000000000000000000000000000..741fb8369b6ba2c63874ec1262b3f3c0698f9f11
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/t5/tokenization_t5.py
@@ -0,0 +1,159 @@
+# Copyright 2018 T5 Authors and HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Tokenization class for model T5."""
+
+import re
+
+from tokenizers import Tokenizer, decoders, normalizers, pre_tokenizers, processors
+from tokenizers.models import Unigram
+
+from ...tokenization_utils_tokenizers import TokenizersBackend
+from ...utils import logging
+
+
+logger = logging.get_logger(__name__)
+
+VOCAB_FILES_NAMES = {"vocab_file": "spiece.model", "tokenizer_file": "tokenizer.json"}
+
+
+class T5Tokenizer(TokenizersBackend):
+ """
+ Construct a T5 tokenizer (backed by HuggingFace's *tokenizers* library). Based on
+ [Unigram](https://huggingface.co/docs/tokenizers/python/latest/components.html?highlight=unigram#models).
+
+ This tokenizer inherits from [`TokenizersBackend`] which contains most of the main methods. Users should
+ refer to this superclass for more information regarding those methods.
+
+ Args:
+ vocab_file (`str`, *optional*):
+ [SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
+ contains the vocabulary necessary to instantiate a tokenizer.
+ eos_token (`str`, *optional*, defaults to `""`):
+ The end of sequence token.
+
+
+
+ When building a sequence using special tokens, this is not the token that is used for the end of sequence.
+ The token used is the `sep_token`.
+
+
+
+ unk_token (`str`, *optional*, defaults to `""`):
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
+ token instead.
+ pad_token (`str`, *optional*, defaults to `""`):
+ The token used for padding, for example when batching sequences of different lengths.
+ extra_ids (`int`, *optional*, defaults to 100):
+ Add a number of extra ids added to the vocabulary for use as sentinels. These tokens are accessible as
+ "" where "{%d}" is a number between 0 and extra_ids-1. These tokens can be retrieved by
+ calling get_sentinel_tokens method and token ids can be by calling get_sentinel_token_ids method
+ additional_special_tokens (`list[str]`, *optional*):
+ Additional special tokens used by the tokenizer.
+ vocab (`str`, `dict` or `list`, *optional*):
+ Custom vocabulary dict. If not provided, a minimal vocabulary is created using the special tokens.
+ """
+
+ vocab_files_names = VOCAB_FILES_NAMES
+ model_input_names = ["input_ids", "attention_mask"]
+ model = Unigram
+
+ def __init__(
+ self,
+ vocab: str | list[tuple[str, float]] | None = None,
+ eos_token="",
+ unk_token="",
+ pad_token="",
+ _spm_precompiled_charsmap=None,
+ extra_ids=100,
+ additional_special_tokens=None,
+ **kwargs,
+ ):
+ self._extra_ids = extra_ids
+
+ # Handle extra_ids and additional_special_tokens
+ if additional_special_tokens is not None:
+ extra_tokens = [x for x in additional_special_tokens if "" for i in range(extra_ids)]
+ elif extra_ids > 0 and extra_ids != len(extra_tokens):
+ raise ValueError(
+ f"Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are"
+ " provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids"
+ " tokens"
+ )
+ else:
+ extra_tokens = [f"" for i in range(extra_ids)]
+ additional_special_tokens = extra_tokens
+
+ # T5 vocab structure: =0, =1, =2, then regular vocab, then extra_ids in reverse
+ if vocab is not None:
+ self._vocab_scores = vocab
+ else:
+ self._vocab_scores = [
+ (str(pad_token), 0.0),
+ (str(eos_token), 0.0),
+ (str(unk_token), 0.0),
+ ("▁", -2.0), # Space token
+ ]
+ for i in range(extra_ids - 1, -1, -1):
+ self._vocab_scores.append((f"", 0.0))
+
+ self._tokenizer = Tokenizer(
+ Unigram(
+ self._vocab_scores,
+ unk_id=2,
+ byte_fallback=False,
+ )
+ )
+
+ if _spm_precompiled_charsmap is not None:
+ self._tokenizer.normalizer = normalizers.Precompiled(_spm_precompiled_charsmap)
+
+ self._tokenizer.pre_tokenizer = pre_tokenizers.Sequence(
+ [
+ pre_tokenizers.WhitespaceSplit(),
+ pre_tokenizers.Metaspace(replacement="▁", prepend_scheme="always", split=True),
+ ]
+ )
+ self._tokenizer.decoder = decoders.Metaspace(replacement="▁", prepend_scheme="always", split=True)
+
+ super().__init__(
+ eos_token=eos_token,
+ unk_token=unk_token,
+ pad_token=pad_token,
+ extra_ids=extra_ids,
+ additional_special_tokens=additional_special_tokens,
+ **kwargs,
+ )
+
+ self._tokenizer.post_processor = processors.TemplateProcessing(
+ single=["$A", ""],
+ pair=["$A", "", "$B", ""],
+ special_tokens=[
+ ("", self.eos_token_id),
+ ],
+ )
+
+ def get_sentinel_tokens(self):
+ """Get the list of sentinel tokens (extra_id tokens) from additional_special_tokens."""
+ return list(
+ set(filter(lambda x: bool(re.search(r"", x)) is not None, self.additional_special_tokens))
+ )
+
+ def get_sentinel_token_ids(self):
+ """Get the token IDs for sentinel tokens."""
+ return [self.convert_tokens_to_ids(token) for token in self.get_sentinel_tokens()]
+
+
+__all__ = ["T5Tokenizer"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/t5gemma/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/t5gemma/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9bc912dad74bf5fc823ecb83208cc70cc6fa4c66
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/t5gemma/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/t5gemma/__pycache__/configuration_t5gemma.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/t5gemma/__pycache__/configuration_t5gemma.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c669b0750b3450d836400724e167c3a8be5af886
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/t5gemma/__pycache__/configuration_t5gemma.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/t5gemma/__pycache__/modeling_t5gemma.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/t5gemma/__pycache__/modeling_t5gemma.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b1c1fa4e15c033b8de4813c54beac80c6598f88d
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/t5gemma/__pycache__/modeling_t5gemma.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/t5gemma/__pycache__/modular_t5gemma.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/t5gemma/__pycache__/modular_t5gemma.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..01e5667201be2acd1daf29482e85278b62932260
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/t5gemma/__pycache__/modular_t5gemma.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/tapas/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/tapas/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d85329883381e5e889f2c066fa4b24bb44acf09a
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/tapas/__init__.py
@@ -0,0 +1,28 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_tapas import *
+ from .modeling_tapas import *
+ from .tokenization_tapas import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/tapas/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/tapas/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..382408e17cca2bfdb17cb0729c2ced0f40402f68
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/tapas/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/tapas/__pycache__/configuration_tapas.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/tapas/__pycache__/configuration_tapas.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4b0e3772f11cebab286edf6f5bbcde0094a2d525
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/tapas/__pycache__/configuration_tapas.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/tapas/configuration_tapas.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/tapas/configuration_tapas.py
new file mode 100644
index 0000000000000000000000000000000000000000..91b4c49669b24007308c59e1bec18168f4bb34a9
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/tapas/configuration_tapas.py
@@ -0,0 +1,155 @@
+# Copyright 2020 Google Research and The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""
+TAPAS configuration. Based on the BERT configuration with added parameters.
+
+Hyperparameters are taken from run_task_main.py and hparam_utils.py of the original implementation. URLS:
+
+- https://github.com/google-research/tapas/blob/master/tapas/run_task_main.py
+- https://github.com/google-research/tapas/blob/master/tapas/utils/hparam_utils.py
+
+"""
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring
+
+
+@auto_docstring(checkpoint="google/tapas-base-finetuned-sqa")
+@strict
+class TapasConfig(PreTrainedConfig):
+ r"""
+ type_vocab_sizes (`list[int]`, *optional*, defaults to `[3, 256, 256, 2, 256, 256, 10]`):
+ The vocabulary sizes of the `token_type_ids` passed when calling [`TapasModel`].
+ positive_label_weight (`float`, *optional*, defaults to 10.0):
+ Weight for positive labels.
+ num_aggregation_labels (`int`, *optional*, defaults to 0):
+ The number of aggregation operators to predict.
+ aggregation_loss_weight (`float`, *optional*, defaults to 1.0):
+ Importance weight for the aggregation loss.
+ use_answer_as_supervision (`bool`, *optional*):
+ Whether to use the answer as the only supervision for aggregation examples.
+ answer_loss_importance (`float`, *optional*, defaults to 1.0):
+ Importance weight for the regression loss.
+ use_normalized_answer_loss (`bool`, *optional*, defaults to `False`):
+ Whether to normalize the answer loss by the maximum of the predicted and expected value.
+ huber_loss_delta (`float`, *optional*):
+ Delta parameter used to calculate the regression loss.
+ temperature (`float`, *optional*, defaults to 1.0):
+ Value used to control (OR change) the skewness of cell logits probabilities.
+ aggregation_temperature (`float`, *optional*, defaults to 1.0):
+ Scales aggregation logits to control the skewness of probabilities.
+ use_gumbel_for_cells (`bool`, *optional*, defaults to `False`):
+ Whether to apply Gumbel-Softmax to cell selection.
+ use_gumbel_for_aggregation (`bool`, *optional*, defaults to `False`):
+ Whether to apply Gumbel-Softmax to aggregation selection.
+ average_approximation_function (`string`, *optional*, defaults to `"ratio"`):
+ Method to calculate the expected average of cells in the weak supervision case. One of `"ratio"`,
+ `"first_order"` or `"second_order"`.
+ cell_selection_preference (`float`, *optional*):
+ Preference for cell selection in ambiguous cases. Only applicable in case of weak supervision for
+ aggregation (WTQ, WikiSQL). If the total mass of the aggregation probabilities (excluding the "NONE"
+ operator) is higher than this hyperparameter, then aggregation is predicted for an example.
+ answer_loss_cutoff (`float`, *optional*):
+ Ignore examples with answer loss larger than cutoff.
+ max_num_rows (`int`, *optional*, defaults to 64):
+ Maximum number of rows.
+ max_num_columns (`int`, *optional*, defaults to 32):
+ Maximum number of columns.
+ average_logits_per_cell (`bool`, *optional*, defaults to `False`):
+ Whether to average logits per cell.
+ select_one_column (`bool`, *optional*, defaults to `True`):
+ Whether to constrain the model to only select cells from a single column.
+ allow_empty_column_selection (`bool`, *optional*, defaults to `False`):
+ Whether to allow not to select any column.
+ init_cell_selection_weights_to_zero (`bool`, *optional*, defaults to `False`):
+ Whether to initialize cell selection weights to 0 so that the initial probabilities are 50%.
+ reset_position_index_per_cell (`bool`, *optional*, defaults to `True`):
+ Whether to restart position indexes at every cell (i.e. use relative position embeddings).
+ disable_per_token_loss (`bool`, *optional*, defaults to `False`):
+ Whether to disable any (strong or weak) supervision on cells.
+ aggregation_labels (`dict[int, label]`, *optional*):
+ The aggregation labels used to aggregate the results. For example, the WTQ models have the following
+ aggregation labels: `{0: "NONE", 1: "SUM", 2: "AVERAGE", 3: "COUNT"}`
+ no_aggregation_label_index (`int`, *optional*):
+ If the aggregation labels are defined and one of these labels represents "No aggregation", this should be
+ set to its index. For example, the WTQ models have the "NONE" aggregation label at index 0, so that value
+ should be set to 0 for these models.
+
+ Example:
+
+ ```python
+ >>> from transformers import TapasModel, TapasConfig
+
+ >>> # Initializing a default (SQA) Tapas configuration
+ >>> configuration = TapasConfig()
+ >>> # Initializing a model from the configuration
+ >>> model = TapasModel(configuration)
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "tapas"
+
+ vocab_size: int = 30522
+ hidden_size: int = 768
+ num_hidden_layers: int = 12
+ num_attention_heads: int = 12
+ intermediate_size: int = 3072
+ hidden_act: str = "gelu"
+ hidden_dropout_prob: float | int = 0.1
+ attention_probs_dropout_prob: float | int = 0.1
+ max_position_embeddings: int = 1024
+ type_vocab_sizes: list[int] | tuple[int, ...] = (3, 256, 256, 2, 256, 256, 10)
+ initializer_range: float = 0.02
+ layer_norm_eps: float = 1e-12
+ pad_token_id: int | None = 0
+ bos_token_id: int | None = None
+ eos_token_id: int | list[int] | None = None
+ positive_label_weight: float = 10.0
+ num_aggregation_labels: int = 0
+ aggregation_loss_weight: float = 1.0
+ use_answer_as_supervision: bool | None = None
+ answer_loss_importance: float = 1.0
+ use_normalized_answer_loss: bool = False
+ huber_loss_delta: float | None = None
+ temperature: float = 1.0
+ aggregation_temperature: float = 1.0
+ use_gumbel_for_cells: bool = False
+ use_gumbel_for_aggregation: bool = False
+ average_approximation_function: str = "ratio"
+ cell_selection_preference: float | None = None
+ answer_loss_cutoff: float | int | None = None
+ max_num_rows: int = 64
+ max_num_columns: int = 32
+ average_logits_per_cell: bool = False
+ select_one_column: bool = True
+ allow_empty_column_selection: bool = False
+ init_cell_selection_weights_to_zero: bool = False
+ reset_position_index_per_cell: bool = True
+ disable_per_token_loss: bool = False
+ aggregation_labels: dict | None = None
+ no_aggregation_label_index: int | None = None
+ is_decoder: bool = False
+ add_cross_attention: bool = False
+ tie_word_embeddings: bool = True
+
+ def __post_init__(self, **kwargs):
+ if isinstance(self.aggregation_labels, dict):
+ self.aggregation_labels = {int(k): v for k, v in self.aggregation_labels.items()}
+ super().__post_init__(**kwargs)
+
+
+__all__ = ["TapasConfig"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/tapas/modeling_tapas.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/tapas/modeling_tapas.py
new file mode 100644
index 0000000000000000000000000000000000000000..040fe7590371328b87ba2a19f3896fbada03fcdb
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/tapas/modeling_tapas.py
@@ -0,0 +1,2106 @@
+# Copyright 2020 Google Research and The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch TAPAS model."""
+
+import enum
+import math
+from dataclasses import dataclass
+
+import torch
+from torch import nn
+from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...cache_utils import Cache, DynamicCache, EncoderDecoderCache
+from ...masking_utils import create_bidirectional_mask
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling, MaskedLMOutput, SequenceClassifierOutput
+from ...modeling_utils import PreTrainedModel
+from ...pytorch_utils import apply_chunking_to_forward
+from ...utils import ModelOutput, auto_docstring, logging
+from .configuration_tapas import TapasConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+EPSILON_ZERO_DIVISION = 1e-10
+CLOSE_ENOUGH_TO_LOG_ZERO = -10000.0
+
+
+@auto_docstring(
+ custom_intro="""
+ Output type of [`TapasForQuestionAnswering`].
+ """
+)
+@dataclass
+class TableQuestionAnsweringOutput(ModelOutput):
+ r"""
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` (and possibly `answer`, `aggregation_labels`, `numeric_values` and `numeric_values_scale` are provided)):
+ Total loss as the sum of the hierarchical cell selection log-likelihood loss and (optionally) the
+ semi-supervised regression loss and (optionally) supervised loss for aggregations.
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
+ Prediction scores of the cell selection head, for every token.
+ logits_aggregation (`torch.FloatTensor`, *optional*, of shape `(batch_size, num_aggregation_labels)`):
+ Prediction scores of the aggregation head, for every aggregation operator.
+ """
+
+ loss: torch.FloatTensor | None = None
+ logits: torch.FloatTensor | None = None
+ logits_aggregation: torch.FloatTensor | None = None
+ hidden_states: tuple[torch.FloatTensor] | None = None
+ attentions: tuple[torch.FloatTensor] | None = None
+
+
+class TapasEmbeddings(nn.Module):
+ """
+ Construct the embeddings from word, position and token_type embeddings. Same as BertEmbeddings but with a number of
+ additional token type embeddings to encode tabular structure.
+ """
+
+ def __init__(self, config):
+ super().__init__()
+ # we do not include config.disabled_features and config.disable_position_embeddings from the original implementation
+ # word embeddings
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
+ # position embeddings
+ self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
+ # token type embeddings
+ for i, type_vocab_sizes in enumerate(config.type_vocab_sizes):
+ name = f"token_type_embeddings_{i}"
+ setattr(self, name, nn.Embedding(type_vocab_sizes, config.hidden_size))
+
+ self.number_of_token_type_embeddings = len(config.type_vocab_sizes)
+
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ self.config = config
+
+ def forward(self, input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None):
+ if input_ids is not None:
+ input_shape = input_ids.size()
+ else:
+ input_shape = inputs_embeds.size()[:-1]
+
+ seq_length = input_shape[1]
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
+
+ if position_ids is None:
+ # create absolute position embeddings
+ position_ids = torch.arange(seq_length, dtype=torch.long, device=device)
+ position_ids = position_ids.unsqueeze(0).expand(input_shape)
+ # when self.config.reset_position_index_per_cell is set to True, create relative position embeddings
+ if self.config.reset_position_index_per_cell:
+ # shape (batch_size, seq_len)
+ col_index = IndexMap(token_type_ids[:, :, 1], self.config.type_vocab_sizes[1], batch_dims=1)
+ # shape (batch_size, seq_len)
+ row_index = IndexMap(token_type_ids[:, :, 2], self.config.type_vocab_sizes[2], batch_dims=1)
+ # shape (batch_size, seq_len)
+ full_index = ProductIndexMap(col_index, row_index)
+ # shape (max_rows * max_columns,). First absolute position for every cell
+ first_position_per_segment = reduce_min(position_ids, full_index)[0]
+ # ? shape (batch_size, seq_len). First absolute position of the cell for every token
+ first_position = gather(first_position_per_segment, full_index)
+ # shape (1, seq_len)
+ position = torch.arange(seq_length, dtype=torch.long, device=device).unsqueeze(0)
+ position_ids = torch.min(
+ torch.as_tensor(self.config.max_position_embeddings - 1, device=device), position - first_position
+ )
+
+ if token_type_ids is None:
+ token_type_ids = torch.zeros(
+ (input_shape + self.number_of_token_type_embeddings), dtype=torch.long, device=device
+ )
+
+ if inputs_embeds is None:
+ inputs_embeds = self.word_embeddings(input_ids)
+
+ position_embeddings = self.position_embeddings(position_ids)
+
+ embeddings = inputs_embeds + position_embeddings
+
+ for i in range(self.number_of_token_type_embeddings):
+ name = f"token_type_embeddings_{i}"
+ embeddings += getattr(self, name)(token_type_ids[:, :, i])
+
+ embeddings = self.LayerNorm(embeddings)
+ embeddings = self.dropout(embeddings)
+ return embeddings
+
+
+class TapasSelfAttention(nn.Module):
+ def __init__(self, config, layer_idx=None):
+ super().__init__()
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
+ raise ValueError(
+ f"The hidden size {config.hidden_size} is not a multiple of the number of attention "
+ f"heads {config.num_attention_heads}"
+ )
+
+ self.num_attention_heads = config.num_attention_heads
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
+
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
+
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
+ self.is_decoder = config.is_decoder
+ self.layer_idx = layer_idx
+
+ def forward(
+ self,
+ hidden_states,
+ attention_mask=None,
+ encoder_hidden_states=None,
+ past_key_values=None,
+ output_attentions=False,
+ **kwargs,
+ ):
+ input_shape = hidden_states.shape[:-1]
+ hidden_shape = (*input_shape, -1, self.attention_head_size)
+ query_layer = self.query(hidden_states).view(hidden_shape).transpose(1, 2)
+
+ is_updated = False
+ is_cross_attention = encoder_hidden_states is not None
+ if past_key_values is not None:
+ if isinstance(past_key_values, EncoderDecoderCache):
+ is_updated = past_key_values.is_updated.get(self.layer_idx)
+ if is_cross_attention:
+ # after the first generated id, we can subsequently re-use all key/value_layer from cache
+ curr_past_key_values = past_key_values.cross_attention_cache
+ else:
+ curr_past_key_values = past_key_values.self_attention_cache
+ else:
+ curr_past_key_values = past_key_values
+
+ current_states = encoder_hidden_states if is_cross_attention else hidden_states
+ if is_cross_attention and past_key_values is not None and is_updated:
+ # reuse k,v, cross_attentions
+ key_layer = curr_past_key_values.layers[self.layer_idx].keys
+ value_layer = curr_past_key_values.layers[self.layer_idx].values
+ else:
+ key_layer = self.key(current_states).view(hidden_shape).transpose(1, 2)
+ value_layer = self.value(current_states).view(hidden_shape).transpose(1, 2)
+
+ if past_key_values is not None:
+ # save all key/value_layer to cache to be re-used for fast auto-regressive generation
+ key_layer, value_layer = curr_past_key_values.update(key_layer, value_layer, self.layer_idx)
+ # set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls
+ if is_cross_attention and isinstance(past_key_values, EncoderDecoderCache):
+ past_key_values.is_updated[self.layer_idx] = True
+
+ # Take the dot product between "query" and "key" to get the raw attention scores.
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
+ if attention_mask is not None:
+ # Apply the attention mask is (precomputed for all layers in TapasModel forward() function)
+ attention_scores = attention_scores + attention_mask
+
+ # Normalize the attention scores to probabilities.
+ attention_probs = nn.functional.softmax(attention_scores, dim=-1)
+
+ # This is actually dropping out entire tokens to attend to, which might
+ # seem a bit unusual, but is taken from the original Transformer paper.
+ attention_probs = self.dropout(attention_probs)
+
+ context_layer = torch.matmul(attention_probs, value_layer)
+
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
+ context_layer = context_layer.view(*new_context_layer_shape)
+
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
+ if self.is_decoder:
+ outputs = outputs + (past_key_values,)
+ return outputs
+
+
+# Copied from transformers.models.bert.modeling_bert.BertSelfOutput
+class TapasSelfOutput(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
+ return hidden_states
+
+
+class TapasAttention(nn.Module):
+ def __init__(self, config, layer_idx=None):
+ super().__init__()
+ self.self = TapasSelfAttention(config, layer_idx=layer_idx)
+ self.output = TapasSelfOutput(config)
+
+ # Copied from transformers.models.rembert.modeling_rembert.RemBertAttention.forward
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.FloatTensor | None = None,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ past_key_values: Cache | None = None,
+ output_attentions: bool | None = False,
+ **kwargs,
+ ) -> tuple[torch.Tensor]:
+ self_outputs = self.self(
+ hidden_states,
+ attention_mask=attention_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ past_key_values=past_key_values,
+ output_attentions=output_attentions,
+ )
+ attention_output = self.output(self_outputs[0], hidden_states)
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
+ return outputs
+
+
+# Copied from transformers.models.bert.modeling_bert.BertIntermediate
+class TapasIntermediate(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
+ if isinstance(config.hidden_act, str):
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
+ else:
+ self.intermediate_act_fn = config.hidden_act
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.intermediate_act_fn(hidden_states)
+ return hidden_states
+
+
+# Copied from transformers.models.bert.modeling_bert.BertOutput
+class TapasOutput(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
+ return hidden_states
+
+
+class TapasLayer(GradientCheckpointingLayer):
+ def __init__(self, config, layer_idx=None):
+ super().__init__()
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
+ self.seq_len_dim = 1
+ self.attention = TapasAttention(config, layer_idx=layer_idx)
+ self.is_decoder = config.is_decoder
+ self.add_cross_attention = config.add_cross_attention
+ if self.add_cross_attention:
+ if not self.is_decoder:
+ raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
+ self.crossattention = TapasAttention(config, layer_idx=layer_idx)
+ self.intermediate = TapasIntermediate(config)
+ self.output = TapasOutput(config)
+
+ # Copied from transformers.models.rembert.modeling_rembert.RemBertLayer.forward
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.FloatTensor | None = None,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ encoder_attention_mask: torch.FloatTensor | None = None,
+ past_key_values: Cache | None = None,
+ output_attentions: bool | None = False,
+ **kwargs,
+ ) -> tuple[torch.Tensor]:
+ self_attention_outputs = self.attention(
+ hidden_states,
+ attention_mask=attention_mask,
+ output_attentions=output_attentions,
+ past_key_values=past_key_values,
+ )
+ attention_output = self_attention_outputs[0]
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
+
+ if self.is_decoder and encoder_hidden_states is not None:
+ if not hasattr(self, "crossattention"):
+ raise ValueError(
+ f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
+ " by setting `config.add_cross_attention=True`"
+ )
+
+ cross_attention_outputs = self.crossattention(
+ attention_output,
+ attention_mask=encoder_attention_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ past_key_values=past_key_values,
+ output_attentions=output_attentions,
+ )
+ attention_output = cross_attention_outputs[0]
+ outputs = outputs + cross_attention_outputs[1:] # add cross attentions if we output attention weights
+
+ layer_output = apply_chunking_to_forward(
+ self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
+ )
+ outputs = (layer_output,) + outputs
+
+ return outputs
+
+ # Copied from transformers.models.bert.modeling_bert.BertLayer.feed_forward_chunk
+ def feed_forward_chunk(self, attention_output):
+ intermediate_output = self.intermediate(attention_output)
+ layer_output = self.output(intermediate_output, attention_output)
+ return layer_output
+
+
+class TapasEncoder(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.layer = nn.ModuleList([TapasLayer(config, layer_idx=i) for i in range(config.num_hidden_layers)])
+ self.gradient_checkpointing = False
+
+ def forward(
+ self,
+ hidden_states,
+ attention_mask=None,
+ encoder_hidden_states=None,
+ encoder_attention_mask=None,
+ past_key_values=None,
+ use_cache=None,
+ output_attentions=False,
+ output_hidden_states=False,
+ return_dict=True,
+ **kwargs,
+ ):
+ if use_cache and past_key_values is None:
+ past_key_values = EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache(config=self.config))
+
+ all_hidden_states = () if output_hidden_states else None
+ all_attentions = () if output_attentions else None
+ for i, layer_module in enumerate(self.layer):
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ layer_outputs = layer_module(
+ hidden_states,
+ attention_mask,
+ encoder_hidden_states, # as a positional argument for gradient checkpointing
+ encoder_attention_mask=encoder_attention_mask,
+ past_key_values=past_key_values,
+ output_attentions=output_attentions,
+ )
+ hidden_states = layer_outputs[0]
+ if output_attentions:
+ all_attentions = all_attentions + (layer_outputs[1],)
+
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ if not return_dict:
+ return tuple(v for v in [hidden_states, all_hidden_states, all_attentions] if v is not None)
+ return BaseModelOutput(
+ last_hidden_state=hidden_states, hidden_states=all_hidden_states, attentions=all_attentions
+ )
+
+
+# Copied from transformers.models.bert.modeling_bert.BertPooler
+class TapasPooler(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.activation = nn.Tanh()
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ # We "pool" the model by simply taking the hidden state corresponding
+ # to the first token.
+ first_token_tensor = hidden_states[:, 0]
+ pooled_output = self.dense(first_token_tensor)
+ pooled_output = self.activation(pooled_output)
+ return pooled_output
+
+
+# Copied from transformers.models.bert.modeling_bert.BertPredictionHeadTransform with Bert->Tapas
+class TapasPredictionHeadTransform(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ if isinstance(config.hidden_act, str):
+ self.transform_act_fn = ACT2FN[config.hidden_act]
+ else:
+ self.transform_act_fn = config.hidden_act
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.transform_act_fn(hidden_states)
+ hidden_states = self.LayerNorm(hidden_states)
+ return hidden_states
+
+
+# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->Tapas
+class TapasLMPredictionHead(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.transform = TapasPredictionHeadTransform(config)
+
+ # The output weights are the same as the input embeddings, but there is
+ # an output-only bias for each token.
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=True)
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
+
+ def forward(self, hidden_states):
+ hidden_states = self.transform(hidden_states)
+ hidden_states = self.decoder(hidden_states)
+ return hidden_states
+
+
+# Copied from transformers.models.bert.modeling_bert.BertOnlyMLMHead with Bert->Tapas
+class TapasOnlyMLMHead(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.predictions = TapasLMPredictionHead(config)
+
+ def forward(self, sequence_output: torch.Tensor) -> torch.Tensor:
+ prediction_scores = self.predictions(sequence_output)
+ return prediction_scores
+
+
+@auto_docstring
+class TapasPreTrainedModel(PreTrainedModel):
+ config: TapasConfig
+ base_model_prefix = "tapas"
+ supports_gradient_checkpointing = True
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ """Initialize the weights"""
+ super()._init_weights(module)
+ if isinstance(module, TapasLMPredictionHead):
+ init.zeros_(module.bias)
+ if isinstance(module, TapasForQuestionAnswering):
+ if module.config.init_cell_selection_weights_to_zero:
+ init.zeros_(module.output_weights)
+ init.zeros_(module.column_output_weights)
+ else:
+ init.normal_(module.output_weights, std=module.config.initializer_range)
+ init.normal_(module.column_output_weights, std=module.config.initializer_range)
+ init.zeros_(module.output_bias)
+ init.zeros_(module.column_output_bias)
+
+
+@auto_docstring
+class TapasModel(TapasPreTrainedModel):
+ """
+ This class is a small change compared to [`BertModel`], taking into account the additional token type ids.
+
+ The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
+ cross-attention is added between the self-attention layers, following the architecture described in [Attention is
+ all you need](https://huggingface.co/papers/1706.03762) by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
+ Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
+
+ """
+
+ def __init__(self, config, add_pooling_layer=True):
+ r"""
+ add_pooling_layer (bool, *optional*, defaults to `True`):
+ Whether to add a pooling layer
+ """
+ super().__init__(config)
+ self.config = config
+
+ self.embeddings = TapasEmbeddings(config)
+ self.encoder = TapasEncoder(config)
+
+ self.pooler = TapasPooler(config) if add_pooling_layer else None
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.embeddings.word_embeddings
+
+ def set_input_embeddings(self, value):
+ self.embeddings.word_embeddings = value
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ encoder_attention_mask: torch.FloatTensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple | BaseModelOutputWithPooling:
+ r"""
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length, 7)`, *optional*):
+ Token indices that encode tabular structure. Indices can be obtained using [`AutoTokenizer`]. See this
+ class for more info.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Indices of positions of each input sequence tokens in the position embeddings. If
+ `reset_position_index_per_cell` of [`TapasConfig`] is set to `True`, relative position embeddings will be
+ used. Selected in the range `[0, config.max_position_embeddings - 1]`.
+
+ [What are position IDs?](../glossary#position-ids)
+
+ Examples:
+
+ ```python
+ >>> from transformers import AutoTokenizer, TapasModel
+ >>> import pandas as pd
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/tapas-base")
+ >>> model = TapasModel.from_pretrained("google/tapas-base")
+
+ >>> data = {
+ ... "Actors": ["Brad Pitt", "Leonardo Di Caprio", "George Clooney"],
+ ... "Age": ["56", "45", "59"],
+ ... "Number of movies": ["87", "53", "69"],
+ ... }
+ >>> table = pd.DataFrame.from_dict(data)
+ >>> queries = ["How many movies has George Clooney played in?", "How old is Brad Pitt?"]
+
+ >>> inputs = tokenizer(table=table, queries=queries, padding="max_length", return_tensors="pt")
+ >>> outputs = model(**inputs)
+
+ >>> last_hidden_states = outputs.last_hidden_state
+ ```"""
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ if input_ids is not None and inputs_embeds is not None:
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
+ elif input_ids is not None:
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
+ input_shape = input_ids.size()
+ elif inputs_embeds is not None:
+ input_shape = inputs_embeds.size()[:-1]
+ else:
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
+
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
+
+ if attention_mask is None:
+ attention_mask = torch.ones(input_shape, device=device)
+ if token_type_ids is None:
+ token_type_ids = torch.zeros(
+ (*input_shape, len(self.config.type_vocab_sizes)), dtype=torch.long, device=device
+ )
+
+ embedding_output = self.embeddings(
+ input_ids=input_ids, position_ids=position_ids, token_type_ids=token_type_ids, inputs_embeds=inputs_embeds
+ )
+
+ attention_mask = create_bidirectional_mask(
+ config=self.config,
+ inputs_embeds=embedding_output,
+ attention_mask=attention_mask,
+ )
+
+ if encoder_attention_mask is not None:
+ encoder_attention_mask = create_bidirectional_mask(
+ config=self.config,
+ inputs_embeds=embedding_output,
+ attention_mask=encoder_attention_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ )
+
+ encoder_outputs = self.encoder(
+ embedding_output,
+ attention_mask=attention_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+ sequence_output = encoder_outputs[0]
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
+
+ if not return_dict:
+ return (sequence_output, pooled_output) + encoder_outputs[1:]
+
+ return BaseModelOutputWithPooling(
+ last_hidden_state=sequence_output,
+ pooler_output=pooled_output,
+ hidden_states=encoder_outputs.hidden_states,
+ attentions=encoder_outputs.attentions,
+ )
+
+
+@auto_docstring
+class TapasForMaskedLM(TapasPreTrainedModel):
+ _tied_weights_keys = {
+ "cls.predictions.decoder.bias": "cls.predictions.bias",
+ "cls.predictions.decoder.weight": "tapas.embeddings.word_embeddings.weight",
+ }
+ config: TapasConfig
+ base_model_prefix = "tapas"
+
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.tapas = TapasModel(config, add_pooling_layer=False)
+ self.cls = TapasOnlyMLMHead(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_output_embeddings(self):
+ return self.cls.predictions.decoder
+
+ def set_output_embeddings(self, new_embeddings):
+ self.cls.predictions.decoder = new_embeddings
+ self.cls.predictions.bias = new_embeddings.bias
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ encoder_hidden_states: torch.FloatTensor | None = None,
+ encoder_attention_mask: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple | MaskedLMOutput:
+ r"""
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length, 7)`, *optional*):
+ Token indices that encode tabular structure. Indices can be obtained using [`AutoTokenizer`]. See this
+ class for more info.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Indices of positions of each input sequence tokens in the position embeddings. If
+ `reset_position_index_per_cell` of [`TapasConfig`] is set to `True`, relative position embeddings will be
+ used. Selected in the range `[0, config.max_position_embeddings - 1]`.
+
+ [What are position IDs?](../glossary#position-ids)
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
+
+ Examples:
+
+ ```python
+ >>> from transformers import AutoTokenizer, TapasForMaskedLM
+ >>> import pandas as pd
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/tapas-base")
+ >>> model = TapasForMaskedLM.from_pretrained("google/tapas-base")
+
+ >>> data = {
+ ... "Actors": ["Brad Pitt", "Leonardo Di Caprio", "George Clooney"],
+ ... "Age": ["56", "45", "59"],
+ ... "Number of movies": ["87", "53", "69"],
+ ... }
+ >>> table = pd.DataFrame.from_dict(data)
+
+ >>> inputs = tokenizer(
+ ... table=table, queries="How many [MASK] has George [MASK] played in?", return_tensors="pt"
+ ... )
+ >>> labels = tokenizer(
+ ... table=table, queries="How many movies has George Clooney played in?", return_tensors="pt"
+ ... )["input_ids"]
+
+ >>> outputs = model(**inputs, labels=labels)
+ >>> logits = outputs.logits
+ ```"""
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ outputs = self.tapas(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ sequence_output = outputs[0]
+ prediction_scores = self.cls(sequence_output)
+
+ masked_lm_loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss() # -100 index = padding token
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
+
+ if not return_dict:
+ output = (prediction_scores,) + outputs[2:]
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
+
+ return MaskedLMOutput(
+ loss=masked_lm_loss,
+ logits=prediction_scores,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ Tapas Model with a cell selection head and optional aggregation head on top for question-answering tasks on tables
+ (linear layers on top of the hidden-states output to compute `logits` and optional `logits_aggregation`), e.g. for
+ SQA, WTQ or WikiSQL-supervised tasks.
+ """
+)
+class TapasForQuestionAnswering(TapasPreTrainedModel):
+ def __init__(self, config: TapasConfig):
+ super().__init__(config)
+
+ # base model
+ self.tapas = TapasModel(config)
+
+ # dropout (only used when training)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ # cell selection heads
+ self.output_weights = nn.Parameter(torch.empty(config.hidden_size))
+ self.column_output_weights = nn.Parameter(torch.empty(config.hidden_size))
+ self.output_bias = nn.Parameter(torch.empty([]))
+ self.column_output_bias = nn.Parameter(torch.empty([]))
+
+ # aggregation head
+ if config.num_aggregation_labels > 0:
+ self.aggregation_classifier = nn.Linear(config.hidden_size, config.num_aggregation_labels)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ table_mask: torch.LongTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ aggregation_labels: torch.LongTensor | None = None,
+ float_answer: torch.FloatTensor | None = None,
+ numeric_values: torch.FloatTensor | None = None,
+ numeric_values_scale: torch.FloatTensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple | TableQuestionAnsweringOutput:
+ r"""
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length, 7)`, *optional*):
+ Token indices that encode tabular structure. Indices can be obtained using [`AutoTokenizer`]. See this
+ class for more info.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Indices of positions of each input sequence tokens in the position embeddings. If
+ `reset_position_index_per_cell` of [`TapasConfig`] is set to `True`, relative position embeddings will be
+ used. Selected in the range `[0, config.max_position_embeddings - 1]`.
+
+ [What are position IDs?](../glossary#position-ids)
+ table_mask (`torch.LongTensor` of shape `(batch_size, seq_length)`, *optional*):
+ Mask for the table. Indicates which tokens belong to the table (1). Question tokens, table headers and
+ padding are 0.
+ labels (`torch.LongTensor` of shape `(batch_size, seq_length)`, *optional*):
+ Labels per token for computing the hierarchical cell selection loss. This encodes the positions of the
+ answer appearing in the table. Can be obtained using [`AutoTokenizer`].
+
+ - 1 for tokens that are **part of the answer**,
+ - 0 for tokens that are **not part of the answer**.
+ aggregation_labels (`torch.LongTensor` of shape `(batch_size, )`, *optional*):
+ Aggregation function index for every example in the batch for computing the aggregation loss. Indices
+ should be in `[0, ..., config.num_aggregation_labels - 1]`. Only required in case of strong supervision for
+ aggregation (WikiSQL-supervised).
+ float_answer (`torch.FloatTensor` of shape `(batch_size, )`, *optional*):
+ Float answer for every example in the batch. Set to *float('nan')* for cell selection questions. Only
+ required in case of weak supervision (WTQ) to calculate the aggregate mask and regression loss.
+ numeric_values (`torch.FloatTensor` of shape `(batch_size, seq_length)`, *optional*):
+ Numeric values of every token, NaN for tokens which are not numeric values. Can be obtained using
+ [`AutoTokenizer`]. Only required in case of weak supervision for aggregation (WTQ) to calculate the
+ regression loss.
+ numeric_values_scale (`torch.FloatTensor` of shape `(batch_size, seq_length)`, *optional*):
+ Scale of the numeric values of every token. Can be obtained using [`AutoTokenizer`]. Only required in case
+ of weak supervision for aggregation (WTQ) to calculate the regression loss.
+
+ Examples:
+
+ ```python
+ >>> from transformers import AutoTokenizer, TapasForQuestionAnswering
+ >>> import pandas as pd
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/tapas-base-finetuned-wtq")
+ >>> model = TapasForQuestionAnswering.from_pretrained("google/tapas-base-finetuned-wtq")
+
+ >>> data = {
+ ... "Actors": ["Brad Pitt", "Leonardo Di Caprio", "George Clooney"],
+ ... "Age": ["56", "45", "59"],
+ ... "Number of movies": ["87", "53", "69"],
+ ... }
+ >>> table = pd.DataFrame.from_dict(data)
+ >>> queries = ["How many movies has George Clooney played in?", "How old is Brad Pitt?"]
+
+ >>> inputs = tokenizer(table=table, queries=queries, padding="max_length", return_tensors="pt")
+ >>> outputs = model(**inputs)
+
+ >>> logits = outputs.logits
+ >>> logits_aggregation = outputs.logits_aggregation
+ ```"""
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ outputs = self.tapas(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ sequence_output = outputs[0]
+ pooled_output = outputs[1]
+
+ sequence_output = self.dropout(sequence_output)
+
+ if input_ids is not None:
+ input_shape = input_ids.size()
+ else:
+ input_shape = inputs_embeds.size()[:-1]
+
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
+
+ # Construct indices for the table.
+ if token_type_ids is None:
+ token_type_ids = torch.zeros(
+ (*input_shape, len(self.config.type_vocab_sizes)), dtype=torch.long, device=device
+ )
+
+ token_types = [
+ "segment_ids",
+ "column_ids",
+ "row_ids",
+ "prev_labels",
+ "column_ranks",
+ "inv_column_ranks",
+ "numeric_relations",
+ ]
+
+ row_ids = token_type_ids[:, :, token_types.index("row_ids")]
+ column_ids = token_type_ids[:, :, token_types.index("column_ids")]
+
+ row_index = IndexMap(
+ indices=torch.min(row_ids, torch.as_tensor(self.config.max_num_rows - 1, device=row_ids.device)),
+ num_segments=self.config.max_num_rows,
+ batch_dims=1,
+ )
+ col_index = IndexMap(
+ indices=torch.min(column_ids, torch.as_tensor(self.config.max_num_columns - 1, device=column_ids.device)),
+ num_segments=self.config.max_num_columns,
+ batch_dims=1,
+ )
+ cell_index = ProductIndexMap(row_index, col_index)
+
+ # Masks.
+ input_shape = input_ids.size() if input_ids is not None else inputs_embeds.size()[:-1]
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
+ if attention_mask is None:
+ attention_mask = torch.ones(input_shape, device=device)
+ # Table cells only, without question tokens and table headers.
+ if table_mask is None:
+ table_mask = torch.where(row_ids > 0, torch.ones_like(row_ids), torch.zeros_like(row_ids))
+ # torch.FloatTensor[batch_size, seq_length]
+ input_mask_float = attention_mask.to(device=device, dtype=torch.float)
+ table_mask_float = table_mask.to(device=device, dtype=torch.float)
+ # Mask for cells that exist in the table (i.e. that are not padding).
+ cell_mask, _ = reduce_mean(input_mask_float, cell_index)
+
+ # Compute logits per token. These are used to select individual cells.
+ logits = compute_token_logits(sequence_output, self.config.temperature, self.output_weights, self.output_bias)
+
+ # Compute logits per column. These are used to select a column.
+ column_logits = None
+ if self.config.select_one_column:
+ column_logits = compute_column_logits(
+ sequence_output,
+ self.column_output_weights,
+ self.column_output_bias,
+ cell_index,
+ cell_mask,
+ self.config.allow_empty_column_selection,
+ )
+
+ # Aggregation logits
+ logits_aggregation = None
+ if self.config.num_aggregation_labels > 0:
+ logits_aggregation = self.aggregation_classifier(pooled_output)
+
+ # Total loss calculation
+ total_loss = 0.0
+ calculate_loss = False
+ if labels is not None:
+ calculate_loss = True
+ is_supervised = not self.config.num_aggregation_labels > 0 or not self.config.use_answer_as_supervision
+
+ # Semi-supervised cell selection in case of no aggregation:
+ # If the answer (the denotation) appears directly in the table we might
+ # select the answer without applying any aggregation function. There are
+ # some ambiguous cases, see utils._calculate_aggregate_mask for more info.
+ # `aggregate_mask` is 1 for examples where we chose to aggregate and 0
+ # for examples where we chose to select the answer directly.
+ # `labels` encodes the positions of the answer appearing in the table.
+ if is_supervised:
+ aggregate_mask = None
+ else:
+ if float_answer is not None:
+ assert labels.shape[0] == float_answer.shape[0], (
+ "Make sure the answers are a FloatTensor of shape (batch_size,)"
+ )
+ # [batch_size]
+ aggregate_mask = _calculate_aggregate_mask(
+ float_answer,
+ pooled_output,
+ self.config.cell_selection_preference,
+ labels,
+ self.aggregation_classifier,
+ )
+ else:
+ raise ValueError("You have to specify float answers in order to calculate the aggregate mask")
+
+ # Cell selection log-likelihood
+ if self.config.average_logits_per_cell:
+ logits_per_cell, _ = reduce_mean(logits, cell_index)
+ logits = gather(logits_per_cell, cell_index)
+ dist_per_token = torch.distributions.Bernoulli(logits=logits)
+
+ # Compute cell selection loss per example.
+ selection_loss_per_example = None
+ if not self.config.select_one_column:
+ weight = torch.where(
+ labels == 0,
+ torch.ones_like(labels, dtype=torch.float32),
+ self.config.positive_label_weight * torch.ones_like(labels, dtype=torch.float32),
+ )
+ selection_loss_per_token = -dist_per_token.log_prob(labels) * weight
+ selection_loss_per_example = torch.sum(selection_loss_per_token * input_mask_float, dim=1) / (
+ torch.sum(input_mask_float, dim=1) + EPSILON_ZERO_DIVISION
+ )
+ else:
+ selection_loss_per_example, logits = _single_column_cell_selection_loss(
+ logits, column_logits, labels, cell_index, col_index, cell_mask
+ )
+ dist_per_token = torch.distributions.Bernoulli(logits=logits)
+
+ # Supervised cell selection
+ if self.config.disable_per_token_loss:
+ pass
+ elif is_supervised:
+ total_loss += torch.mean(selection_loss_per_example)
+ else:
+ # For the not supervised case, do not assign loss for cell selection
+ total_loss += torch.mean(selection_loss_per_example * (1.0 - aggregate_mask))
+
+ # Semi-supervised regression loss and supervised loss for aggregations
+ if self.config.num_aggregation_labels > 0:
+ if is_supervised:
+ # Note that `aggregate_mask` is None if the setting is supervised.
+ if aggregation_labels is not None:
+ assert labels.shape[0] == aggregation_labels.shape[0], (
+ "Make sure the aggregation labels are a LongTensor of shape (batch_size,)"
+ )
+ per_example_additional_loss = _calculate_aggregation_loss(
+ logits_aggregation,
+ aggregate_mask,
+ aggregation_labels,
+ self.config.use_answer_as_supervision,
+ self.config.num_aggregation_labels,
+ self.config.aggregation_loss_weight,
+ )
+ else:
+ raise ValueError(
+ "You have to specify aggregation labels in order to calculate the aggregation loss"
+ )
+ else:
+ # Set aggregation labels to zeros
+ aggregation_labels = torch.zeros(labels.shape[0], dtype=torch.long, device=labels.device)
+ per_example_additional_loss = _calculate_aggregation_loss(
+ logits_aggregation,
+ aggregate_mask,
+ aggregation_labels,
+ self.config.use_answer_as_supervision,
+ self.config.num_aggregation_labels,
+ self.config.aggregation_loss_weight,
+ )
+
+ if self.config.use_answer_as_supervision:
+ if numeric_values is not None and numeric_values_scale is not None:
+ assert numeric_values.shape == numeric_values_scale.shape
+ # Add regression loss for numeric answers which require aggregation.
+ answer_loss, large_answer_loss_mask = _calculate_regression_loss(
+ float_answer,
+ aggregate_mask,
+ dist_per_token,
+ numeric_values,
+ numeric_values_scale,
+ table_mask_float,
+ logits_aggregation,
+ self.config,
+ )
+ per_example_additional_loss += answer_loss
+ # Zero loss for examples with answer_loss > cutoff.
+ per_example_additional_loss *= large_answer_loss_mask
+ else:
+ raise ValueError(
+ "You have to specify numeric values and numeric values scale in order to calculate the"
+ " regression loss"
+ )
+
+ total_loss += torch.mean(per_example_additional_loss)
+
+ else:
+ # if no label ids are provided, set them to zeros in order to properly compute logits
+ labels = torch.zeros_like(logits)
+ _, logits = _single_column_cell_selection_loss(
+ logits, column_logits, labels, cell_index, col_index, cell_mask
+ )
+ if not return_dict:
+ output = (logits, logits_aggregation) + outputs[2:]
+ return ((total_loss,) + output) if calculate_loss else output
+
+ return TableQuestionAnsweringOutput(
+ loss=total_loss if calculate_loss else None,
+ logits=logits,
+ logits_aggregation=logits_aggregation,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ Tapas Model with a sequence classification head on top (a linear layer on top of the pooled output), e.g. for table
+ entailment tasks, such as TabFact (Chen et al., 2020).
+ """
+)
+class TapasForSequenceClassification(TapasPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+
+ self.tapas = TapasModel(config)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.FloatTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple[torch.Tensor] | SequenceClassifierOutput:
+ r"""
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length, 7)`, *optional*):
+ Token indices that encode tabular structure. Indices can be obtained using [`AutoTokenizer`]. See this
+ class for more info.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Indices of positions of each input sequence tokens in the position embeddings. If
+ `reset_position_index_per_cell` of [`TapasConfig`] is set to `True`, relative position embeddings will be
+ used. Selected in the range `[0, config.max_position_embeddings - 1]`.
+
+ [What are position IDs?](../glossary#position-ids)
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy). Note: this is called
+ "classification_class_index" in the original implementation.
+
+ Examples:
+
+ ```python
+ >>> from transformers import AutoTokenizer, TapasForSequenceClassification
+ >>> import torch
+ >>> import pandas as pd
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/tapas-base-finetuned-tabfact")
+ >>> model = TapasForSequenceClassification.from_pretrained("google/tapas-base-finetuned-tabfact")
+
+ >>> data = {
+ ... "Actors": ["Brad Pitt", "Leonardo Di Caprio", "George Clooney"],
+ ... "Age": ["56", "45", "59"],
+ ... "Number of movies": ["87", "53", "69"],
+ ... }
+ >>> table = pd.DataFrame.from_dict(data)
+ >>> queries = [
+ ... "There is only one actor who is 45 years old",
+ ... "There are 3 actors which played in more than 60 movies",
+ ... ]
+
+ >>> inputs = tokenizer(table=table, queries=queries, padding="max_length", return_tensors="pt")
+ >>> labels = torch.tensor([1, 0]) # 1 means entailed, 0 means refuted
+
+ >>> outputs = model(**inputs, labels=labels)
+ >>> loss = outputs.loss
+ >>> logits = outputs.logits
+ ```"""
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ outputs = self.tapas(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ pooled_output = outputs[1]
+
+ pooled_output = self.dropout(pooled_output)
+ logits = self.classifier(pooled_output)
+
+ loss = None
+ if labels is not None:
+ if self.config.problem_type is None:
+ if self.num_labels == 1:
+ self.config.problem_type = "regression"
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
+ self.config.problem_type = "single_label_classification"
+ else:
+ self.config.problem_type = "multi_label_classification"
+
+ if self.config.problem_type == "regression":
+ loss_fct = MSELoss()
+ if self.num_labels == 1:
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
+ else:
+ loss = loss_fct(logits, labels)
+ elif self.config.problem_type == "single_label_classification":
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+ elif self.config.problem_type == "multi_label_classification":
+ loss_fct = BCEWithLogitsLoss()
+ loss = loss_fct(logits, labels)
+ if not return_dict:
+ output = (logits,) + outputs[2:]
+ return ((loss,) + output) if loss is not None else output
+
+ return SequenceClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+""" TAPAS utilities."""
+
+
+class AverageApproximationFunction(str, enum.Enum):
+ RATIO = "ratio"
+ FIRST_ORDER = "first_order"
+ SECOND_ORDER = "second_order"
+
+
+# Beginning of everything related to segmented tensors
+
+
+class IndexMap:
+ """Index grouping entries within a tensor."""
+
+ def __init__(self, indices, num_segments, batch_dims=0):
+ """
+ Creates an index
+
+ Args:
+ indices (`torch.LongTensor`, same shape as a *values* Tensor to which the indices refer):
+ Tensor containing the indices.
+ num_segments (`torch.LongTensor`):
+ Scalar tensor, the number of segments. All elements in a batched segmented tensor must have the same
+ number of segments (although many segments can be empty).
+ batch_dims (`int`, *optional*, defaults to 0):
+ The number of batch dimensions. The first *batch_dims* dimensions of a SegmentedTensor are treated as
+ batch dimensions. Segments in different batch elements are always distinct even if they have the same
+ index.
+ """
+ self.indices = torch.as_tensor(indices, device=indices.device)
+ self.num_segments = torch.as_tensor(num_segments, device=indices.device)
+ self.batch_dims = batch_dims
+
+ def batch_shape(self):
+ return self.indices.size()[: self.batch_dims] # returns a torch.Size object
+
+
+class ProductIndexMap(IndexMap):
+ """The product of two indices."""
+
+ def __init__(self, outer_index, inner_index):
+ """
+ Combines indices i and j into pairs (i, j). The result is an index where each segment (i, j) is the
+ intersection of segments i and j. For example if the inputs represent table cells indexed by respectively rows
+ and columns the output will be a table indexed by (row, column) pairs, i.e. by cell. The implementation
+ combines indices {0, .., n - 1} and {0, .., m - 1} into {0, .., nm - 1}. The output has *num_segments* equal to
+ *outer_index.num_segments* * *inner_index.num_segments*
+
+ Args:
+ outer_index (`IndexMap`):
+ IndexMap.
+ inner_index (`IndexMap`):
+ IndexMap, must have the same shape as *outer_index*.
+ """
+ if outer_index.batch_dims != inner_index.batch_dims:
+ raise ValueError("outer_index.batch_dims and inner_index.batch_dims must be the same.")
+
+ super().__init__(
+ indices=(inner_index.indices + outer_index.indices * inner_index.num_segments),
+ num_segments=inner_index.num_segments * outer_index.num_segments,
+ batch_dims=inner_index.batch_dims,
+ )
+ self.outer_index = outer_index
+ self.inner_index = inner_index
+
+ def project_outer(self, index):
+ """Projects an index with the same index set onto the outer components."""
+ indices = torch.div(index.indices, self.inner_index.num_segments, rounding_mode="floor").type(torch.long)
+ return IndexMap(indices=indices, num_segments=self.outer_index.num_segments, batch_dims=index.batch_dims)
+
+ def project_inner(self, index):
+ """Projects an index with the same index set onto the inner components."""
+ return IndexMap(
+ indices=torch.fmod(index.indices, self.inner_index.num_segments)
+ .type(torch.float)
+ .floor()
+ .type(torch.long),
+ num_segments=self.inner_index.num_segments,
+ batch_dims=index.batch_dims,
+ )
+
+
+def gather(values, index, name="segmented_gather"):
+ """
+ Gathers from *values* using the index map. For each element in the domain of the index map this operation looks up
+ a value for that index in *values*. Two elements from the same segment always get assigned the same value.
+
+ Args:
+ values (`torch.Tensor` of shape (B1, ..., Bn, num_segments, V1, ...)):
+ Tensor with segment values.
+ index (`IndexMap` of shape (B1, ..., Bn, I1, ..., Ik)):
+ IndexMap.
+ name (`str`, *optional*, defaults to 'segmented_gather'):
+ Name for the operation. Currently not used
+
+ Returns:
+ `tuple(torch.Tensor)`: Tensor of shape (B1, ..., Bn, I1, ..., Ik, V1, ...) with the gathered values.
+ """
+ indices = index.indices
+ # first, check whether the indices of the index represent scalar values (i.e. not vectorized)
+ if len(values.shape[index.batch_dims :]) < 2:
+ return torch.gather(
+ values,
+ index.batch_dims,
+ indices.view(
+ values.size()[0], -1
+ ), # torch.gather expects index to have the same number of dimensions as values
+ ).view(indices.size())
+ else:
+ # this means we have a vectorized version
+ # we have to adjust the index
+ indices = indices.unsqueeze(-1).expand(values.shape)
+ return torch.gather(values, index.batch_dims, indices)
+
+
+def flatten(index, name="segmented_flatten"):
+ """
+ Flattens a batched index map (which is typically of shape batch_size, seq_length) to a 1d index map. This operation
+ relabels the segments to keep batch elements distinct. The k-th batch element will have indices shifted by
+ *num_segments* * (k - 1). The result is a tensor with *num_segments* multiplied by the number of elements in the
+ batch.
+
+ Args:
+ index (`IndexMap`):
+ IndexMap to flatten.
+ name (`str`, *optional*, defaults to 'segmented_flatten'):
+ Name for the operation. Currently not used
+
+ Returns:
+ (`IndexMap`): The flattened IndexMap.
+ """
+ # first, get batch_size as scalar tensor
+ batch_size = torch.prod(torch.tensor(list(index.batch_shape())))
+ # next, create offset as 1-D tensor of length batch_size,
+ # and multiply element-wise by num segments (to offset different elements in the batch) e.g. if batch size is 2: [0, 64]
+ offset = torch.arange(start=0, end=batch_size, device=index.num_segments.device) * index.num_segments
+ offset = offset.view(index.batch_shape())
+ for _ in range(index.batch_dims, len(index.indices.size())): # typically range(1,2)
+ offset = offset.unsqueeze(-1)
+
+ indices = offset + index.indices
+ return IndexMap(indices=indices.view(-1), num_segments=index.num_segments * batch_size, batch_dims=0)
+
+
+def range_index_map(batch_shape, num_segments, name="range_index_map"):
+ """
+ Constructs an index map equal to range(num_segments).
+
+ Args:
+ batch_shape (`torch.Size`):
+ Batch shape
+ num_segments (`int`):
+ Number of segments
+ name (`str`, *optional*, defaults to 'range_index_map'):
+ Name for the operation. Currently not used
+
+ Returns:
+ (`IndexMap`): IndexMap of shape batch_shape with elements equal to range(num_segments).
+ """
+ device = num_segments.device if torch.is_tensor(num_segments) else "cpu"
+ batch_shape = torch.as_tensor(
+ batch_shape, dtype=torch.long, device=device
+ ) # create a rank 1 tensor vector containing batch_shape (e.g. [2])
+ assert len(batch_shape.size()) == 1
+ num_segments = torch.as_tensor(
+ num_segments, device=device
+ ) # create a rank 0 tensor (scalar) containing num_segments (e.g. 64)
+ assert len(num_segments.size()) == 0
+
+ indices = torch.arange(
+ start=0, end=num_segments, device=num_segments.device
+ ) # create a rank 1 vector with num_segments elements
+ new_tensor = torch.cat(
+ [torch.ones_like(batch_shape, dtype=torch.long, device=num_segments.device), num_segments.unsqueeze(dim=0)],
+ dim=0,
+ )
+ # new_tensor is just a vector of [1 64] for example (assuming only 1 batch dimension)
+ new_shape = [int(x) for x in new_tensor.tolist()]
+ indices = indices.view(new_shape)
+
+ multiples = torch.cat([batch_shape, torch.as_tensor([1], device=device)], dim=0)
+ indices = indices.repeat(multiples.tolist())
+ # equivalent (in Numpy:)
+ # indices = torch.as_tensor(np.tile(indices.numpy(), multiples.tolist()))
+
+ return IndexMap(indices=indices, num_segments=num_segments, batch_dims=list(batch_shape.size())[0])
+
+
+def _segment_reduce(values, index, segment_reduce_fn, name):
+ """
+ Applies a segment reduction segment-wise.
+
+ Args:
+ values (`torch.Tensor`):
+ Tensor with segment values.
+ index (`IndexMap`):
+ IndexMap.
+ segment_reduce_fn (`str`):
+ Name for the reduce operation. One of "sum", "mean", "max" or "min".
+ name (`str`):
+ Name for the operation. Currently not used
+
+ Returns:
+ (`IndexMap`): IndexMap of shape batch_shape with elements equal to range(num_segments).
+ """
+ # Flatten the batch dimensions, as segments ops (scatter) do not support batching.
+ # However if `values` has extra dimensions to the right keep them
+ # unflattened. Segmented ops support vector-valued operations.
+ flat_index = flatten(index)
+ vector_shape = values.size()[len(index.indices.size()) :] # torch.Size object
+ flattened_shape = torch.cat(
+ [torch.as_tensor([-1], dtype=torch.long), torch.as_tensor(vector_shape, dtype=torch.long)], dim=0
+ )
+ # changed "view" by "reshape" in the following line
+ flat_values = values.reshape(flattened_shape.tolist())
+
+ out = torch.zeros(int(flat_index.num_segments), dtype=torch.float, device=flat_values.device)
+ segment_means = out.scatter_reduce(
+ dim=0, index=flat_index.indices.long(), src=flat_values.float(), reduce=segment_reduce_fn, include_self=False
+ )
+
+ device = index.num_segments.device
+ # Unflatten the values.
+ new_shape = torch.cat(
+ [
+ torch.as_tensor(index.batch_shape(), dtype=torch.long, device=device),
+ torch.as_tensor(index.num_segments, dtype=torch.long, device=device).unsqueeze(dim=0),
+ torch.as_tensor(vector_shape, dtype=torch.long, device=device),
+ ],
+ dim=0,
+ )
+
+ output_values = segment_means.clone().view(new_shape.tolist()).to(values.dtype)
+ output_index = range_index_map(index.batch_shape(), index.num_segments)
+ return output_values, output_index
+
+
+def reduce_sum(values, index, name="segmented_reduce_sum"):
+ """
+ Sums a tensor over its segments.
+
+ Outputs 0 for empty segments.
+
+ This operations computes the sum over segments, with support for:
+
+ - Batching using the first dimensions [B1, B2, ..., Bn]. Each element in a batch can have different indices.
+ - Vectorization using the last dimension [V1, V2, ...]. If they are present, the output will be a sum of
+ vectors rather than scalars. Only the middle dimensions [I1, ..., Ik] are reduced by the operation.
+
+ Args:
+ values (`torch.Tensor` of shape [B1, B2, ..., Bn, I1, .., Ik, V1, V2, ..]):
+ Tensor containing the values of which the sum must be taken segment-wise.
+ index (`IndexMap`, indices are of shape [B1, B2, ..., Bn, I1, .., Ik].):
+ Index defining the segments.
+ name (`str`, *optional*, defaults to 'segmented_reduce_sum'):
+ Name for the operation. Currently not used
+
+ Returns:
+ output_values (`torch.Tensor`of shape [B1, B2, ..., Bn, num_segments, V1, V2, ..]): Tensor containing the
+ output values. output_index (`IndexMap`): IndexMap with shape [B1, B2, ..., Bn, num_segments]. .
+ """
+ return _segment_reduce(values, index, "sum", name)
+
+
+def reduce_mean(values, index, name="segmented_reduce_mean"):
+ """
+ Averages a tensor over its segments.
+
+ Outputs 0 for empty segments.
+
+ This operations computes the mean over segments, with support for:
+
+ - Batching using the first dimensions [B1, B2, ..., Bn]. Each element in a batch can have different indices.
+ - Vectorization using the last dimension [V1, V2, ...]. If they are present, the output will be a mean of
+ vectors rather than scalars.
+
+ Only the middle dimensions [I1, ..., Ik] are reduced by the operation.
+
+ Args:
+ values (`torch.Tensor` of shape [B1, B2, ..., Bn, I1, .., Ik, V1, V2, ..]):
+ Tensor containing the values of which the mean must be taken segment-wise.
+ index (`IndexMap`, indices are of shape [B1, B2, ..., Bn, I1, .., Ik].):
+ Index defining the segments.
+ name (`str`, *optional*, defaults to 'segmented_reduce_sum'):
+ Name for the operation. Currently not used
+
+ Returns:
+ output_values (`torch.Tensor`of shape [B1, B2, ..., Bn, num_segments, V1, V2, ..]): Tensor containing the
+ output values. output_index (`IndexMap`): IndexMap with shape [B1, B2, ..., Bn, num_segments].
+ """
+ return _segment_reduce(values, index, "mean", name)
+
+
+def reduce_max(values, index, name="segmented_reduce_max"):
+ """
+ Computes the maximum over segments.
+
+ This operation computes the maximum over segments, with support for:
+
+ - Batching using the first dimensions [B1, B2, ..., Bn]. Each element in a batch can have different indices.
+ - Vectorization using the last dimension [V1, V2, ...]. If they are present, the output will be an element-wise
+ maximum of vectors rather than scalars.
+
+ Only the middle dimensions [I1, ..., Ik] are reduced by the operation.
+
+ Args:
+ values (`torch.Tensor` of shape [B1, B2, ..., Bn, I1, .., Ik, V1, V2, ..]):
+ Tensor containing the values of which the max must be taken segment-wise.
+ index (`IndexMap`, indices are of shape [B1, B2, ..., Bn, I1, .., Ik].):
+ Index defining the segments.
+ name (`str`, *optional*, defaults to 'segmented_reduce_sum'):
+ Name for the operation. Currently not used
+
+ Returns:
+ output_values (`torch.Tensor`of shape [B1, B2, ..., Bn, num_segments, V1, V2, ..]): Tensor containing the
+ output values. output_index (`IndexMap`): IndexMap with shape [B1, B2, ..., Bn, num_segments].
+ """
+ return _segment_reduce(values, index, "amax", name)
+
+
+def reduce_min(values, index, name="segmented_reduce_min"):
+ """
+ Computes the minimum over segments.
+
+ This operations computes the minimum over segments, with support for:
+
+ - Batching using the first dimensions [B1, B2, ..., Bn]. Each element in a batch can have different indices.
+ - Vectorization using the last dimension [V1, V2, ...]. If they are present, the output will be an element-wise
+ minimum of vectors rather than scalars.
+
+ Only the middle dimensions [I1, ..., Ik] are reduced by the operation.
+
+ Args:
+ values (`torch.Tensor` of shape [B1, B2, ..., Bn, I1, .., Ik, V1, V2, ..]):
+ Tensor containing the values of which the min must be taken segment-wise.
+ index (`IndexMap`, indices are of shape [B1, B2, ..., Bn, I1, .., Ik].):
+ Index defining the segments.
+ name (`str`, *optional*, defaults to 'segmented_reduce_sum'):
+ Name for the operation. Currently not used
+
+ Returns:
+ output_values (`torch.Tensor`of shape [B1, B2, ..., Bn, num_segments, V1, V2, ..]): Tensor containing the
+ output values. output_index (`IndexMap`): IndexMap with shape [B1, B2, ..., Bn, num_segments].
+ """
+ return _segment_reduce(values, index, "amin", name)
+
+
+# End of everything related to segmented tensors
+
+
+def compute_column_logits(
+ sequence_output, column_output_weights, column_output_bias, cell_index, cell_mask, allow_empty_column_selection
+):
+ """
+ Computes the column logits.
+
+ Args:
+ sequence_output (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
+ Also known as last_hidden_state. Sequence of hidden-states at the output of the last layer of the model.
+ column_output_weights (`torch.FloatTensor` of shape `(hidden_size)`):
+ Weights of the linear layer for column selection.
+ column_output_bias (`torch.FloatTensor` of shape `()`):
+ Bias of the linear layer for column selection.
+ cell_index (`ProductIndexMap`):
+ Index that groups tokens into cells.
+ cell_mask (`torch.FloatTensor` of shape `(batch_size, max_num_rows * max_num_cols)`):
+ Mask for cells that exist in the table (i.e. that are not padding).
+ allow_empty_column_selection (`bool`):
+ Whether to allow not to select any column
+
+ Returns:
+ column_logits (`torch.FloatTensor`of shape `(batch_size, max_num_cols)`): Tensor containing the column logits
+ for every example in the batch.
+ """
+
+ # First, compute the token logits (batch_size, seq_len) - without temperature
+ token_logits = torch.einsum("bsj,j->bs", sequence_output, column_output_weights) + column_output_bias
+
+ # Next, average the logits per cell (batch_size, max_num_cols*max_num_rows)
+ cell_logits, cell_logits_index = reduce_mean(token_logits, cell_index)
+
+ # Finally, average the logits per column (batch_size, max_num_cols)
+ column_index = cell_index.project_inner(cell_logits_index)
+ column_logits, out_index = reduce_sum(cell_logits * cell_mask, column_index)
+
+ cell_count, _ = reduce_sum(cell_mask, column_index)
+ column_logits /= cell_count + EPSILON_ZERO_DIVISION
+
+ # Mask columns that do not appear in the example.
+ is_padding = torch.logical_and(cell_count < 0.5, ~torch.eq(out_index.indices, 0))
+ column_logits += CLOSE_ENOUGH_TO_LOG_ZERO * torch.as_tensor(
+ is_padding, dtype=torch.float32, device=is_padding.device
+ )
+
+ if not allow_empty_column_selection:
+ column_logits += CLOSE_ENOUGH_TO_LOG_ZERO * torch.as_tensor(
+ torch.eq(out_index.indices, 0), dtype=torch.float32, device=out_index.indices.device
+ )
+
+ return column_logits
+
+
+def _single_column_cell_selection_loss(token_logits, column_logits, labels, cell_index, col_index, cell_mask):
+ """
+ Computes the loss for cell selection constrained to a single column. The loss is a hierarchical log-likelihood. The
+ model first predicts a column and then selects cells within that column (conditioned on the column). Cells outside
+ the selected column are never selected.
+
+ Args:
+ token_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
+ Tensor containing the logits per token.
+ column_logits (`torch.FloatTensor` of shape `(batch_size, max_num_cols)`):
+ Tensor containing the logits per column.
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ Labels per token.
+ cell_index (`ProductIndexMap`):
+ Index that groups tokens into cells.
+ col_index (`IndexMap`):
+ Index that groups tokens into columns.
+ cell_mask (`torch.FloatTensor` of shape `(batch_size, max_num_rows * max_num_cols)`):
+ Mask for cells that exist in the table (i.e. that are not padding).
+
+ Returns:
+ selection_loss_per_example (`torch.FloatTensor` of shape `(batch_size,)`): Loss for each example. logits
+ (`torch.FloatTensor` of shape `(batch_size, sequence_length)`): New logits which are only allowed to select
+ cells in a single column. Logits outside of the most likely column according to *column_logits* will be set to
+ a very low value (such that the probabilities are 0).
+ """
+ # Part 1: column loss
+
+ # First find the column we should select. We use the column with maximum number of selected cells.
+ labels_per_column, _ = reduce_sum(torch.as_tensor(labels, dtype=torch.float32, device=labels.device), col_index)
+ # shape of labels_per_column is (batch_size, max_num_cols). It contains the number of label ids for every column, for every example
+ column_label = torch.argmax(labels_per_column, dim=-1) # shape (batch_size,)
+ # Check if there are no selected cells in the column. In that case the model
+ # should predict the special column id 0, which means "select nothing".
+ no_cell_selected = torch.eq(
+ torch.max(labels_per_column, dim=-1)[0], 0
+ ) # no_cell_selected is of shape (batch_size,) and equals True
+ # if an example of the batch has no cells selected (i.e. if there are no labels set to 1 for that example)
+ column_label = torch.where(
+ no_cell_selected.view(column_label.size()), torch.zeros_like(column_label), column_label
+ )
+
+ column_dist = torch.distributions.Categorical(logits=column_logits) # shape (batch_size, max_num_cols)
+ column_loss_per_example = -column_dist.log_prob(column_label)
+
+ # Part 2: cell loss
+
+ # Reduce the labels and logits to per-cell from per-token.
+ # logits_per_cell: shape (batch_size, max_num_rows*max_num_cols) i.e. (batch_size, 64*32)
+ logits_per_cell, _ = reduce_mean(token_logits, cell_index)
+ # labels_per_cell: shape (batch_size, 64*32), indicating whether each cell should be selected (1) or not (0)
+ labels_per_cell, labels_index = reduce_max(
+ torch.as_tensor(labels, dtype=torch.long, device=labels.device), cell_index
+ )
+
+ # Mask for the selected column.
+ # column_id_for_cells: shape (batch_size, 64*32), indicating to which column each cell belongs
+ column_id_for_cells = cell_index.project_inner(labels_index).indices
+ # column_mask: shape (batch_size, 64*32), equal to 1 if cell belongs to column to be selected
+ column_mask = torch.as_tensor(
+ torch.eq(column_id_for_cells, torch.unsqueeze(column_label, dim=-1)),
+ dtype=torch.float32,
+ device=cell_mask.device,
+ )
+
+ # Compute the log-likelihood for cells, but only for the selected column.
+ cell_dist = torch.distributions.Bernoulli(logits=logits_per_cell) # shape (batch_size, 64*32)
+ cell_log_prob = cell_dist.log_prob(labels_per_cell.type(torch.float32)) # shape(batch_size, 64*32)
+
+ cell_loss = -torch.sum(cell_log_prob * column_mask * cell_mask, dim=1)
+
+ # We need to normalize the loss by the number of cells in the column.
+ cell_loss /= torch.sum(column_mask * cell_mask, dim=1) + EPSILON_ZERO_DIVISION
+
+ selection_loss_per_example = column_loss_per_example
+ selection_loss_per_example += torch.where(
+ no_cell_selected.view(selection_loss_per_example.size()),
+ torch.zeros_like(selection_loss_per_example),
+ cell_loss,
+ )
+
+ # Set the probs outside the selected column (selected by the *model*)
+ # to 0. This ensures backwards compatibility with models that select
+ # cells from multiple columns.
+ selected_column_id = torch.as_tensor(
+ torch.argmax(column_logits, dim=-1), dtype=torch.long, device=column_logits.device
+ ) # shape (batch_size,)
+
+ # selected_column_mask: shape (batch_size, 64*32), equal to 1 if cell belongs to column selected by the model
+ selected_column_mask = torch.as_tensor(
+ torch.eq(column_id_for_cells, torch.unsqueeze(selected_column_id, dim=-1)),
+ dtype=torch.float32,
+ device=selected_column_id.device,
+ )
+
+ # Never select cells with the special column id 0.
+ selected_column_mask = torch.where(
+ torch.eq(column_id_for_cells, 0).view(selected_column_mask.size()),
+ torch.zeros_like(selected_column_mask),
+ selected_column_mask,
+ )
+ new_logits_per_cell = logits_per_cell + CLOSE_ENOUGH_TO_LOG_ZERO * (1.0 - cell_mask * selected_column_mask)
+ logits = gather(new_logits_per_cell, cell_index)
+
+ return selection_loss_per_example, logits
+
+
+def compute_token_logits(sequence_output, temperature, output_weights, output_bias):
+ """
+ Computes logits per token
+
+ Args:
+ sequence_output (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
+ Also known as last_hidden_state. Sequence of hidden-states at the output of the last layer of the model.
+ temperature (`float`):
+ Temperature for the Bernoulli distribution.
+ output_weights (`torch.FloatTensor` of shape `(hidden_size,)`):
+ Weights of the linear layer for cell selection.
+ output_bias (`torch.FloatTensor` of shape `()`):
+ Bias of the linear layer for cell selection
+
+ Returns:
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length)`): Logits per token.
+ """
+ logits = (torch.einsum("bsj,j->bs", sequence_output, output_weights) + output_bias) / temperature
+
+ return logits
+
+
+def _calculate_aggregate_mask(answer, pooled_output, cell_selection_preference, labels, aggregation_classifier):
+ """
+ Finds examples where the model should select cells with no aggregation.
+
+ Returns a mask that determines for which examples should the model select answers directly from the table, without
+ any aggregation function. If the answer is a piece of text the case is unambiguous as aggregation functions only
+ apply to numbers. If the answer is a number but does not appear in the table then we must use some aggregation
+ case. The ambiguous case is when the answer is a number that also appears in the table. In this case we use the
+ aggregation function probabilities predicted by the model to decide whether to select or aggregate. The threshold
+ for this is a hyperparameter *cell_selection_preference*
+
+ Args:
+ answer (`torch.FloatTensor` of shape `(batch_size, )`):
+ Answer for every example in the batch. Nan if there is no scalar answer.
+ pooled_output (`torch.FloatTensor` of shape `(batch_size, hidden_size)`):
+ Output of the pooler (BertPooler) on top of the encoder layer.
+ cell_selection_preference (`float`):
+ Preference for cell selection in ambiguous cases.
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ Labels per token. aggregation_classifier (`torch.nn.Linear`): Aggregation head
+
+ Returns:
+ aggregate_mask (`torch.FloatTensor` of shape `(batch_size,)`): A mask set to 1 for examples that should use
+ aggregation functions.
+ """
+ # torch.FloatTensor(batch_size,)
+ aggregate_mask_init = torch.logical_not(torch.isnan(answer)).type(torch.FloatTensor).to(answer.device)
+ logits_aggregation = aggregation_classifier(pooled_output)
+ dist_aggregation = torch.distributions.categorical.Categorical(logits=logits_aggregation)
+ # Index 0 corresponds to "no aggregation".
+ aggregation_ops_total_mass = torch.sum(dist_aggregation.probs[:, 1:], dim=1)
+
+ # Cell selection examples according to current model.
+ is_pred_cell_selection = aggregation_ops_total_mass <= cell_selection_preference
+
+ # Examples with non-empty cell selection supervision.
+ is_cell_supervision_available = torch.sum(labels, dim=1) > 0
+
+ aggregate_mask = torch.where(
+ torch.logical_and(is_pred_cell_selection, is_cell_supervision_available).view(aggregate_mask_init.size()),
+ torch.zeros_like(aggregate_mask_init, dtype=torch.float32),
+ aggregate_mask_init,
+ )
+
+ aggregate_mask = aggregate_mask.detach()
+
+ return aggregate_mask
+
+
+def _calculate_aggregation_loss_known(
+ logits_aggregation, aggregate_mask, aggregation_labels, use_answer_as_supervision, num_aggregation_labels
+):
+ """
+ Calculates aggregation loss when its type is known during training.
+
+ In the weakly supervised setting, the only known information is that for cell selection examples, "no aggregation"
+ should be predicted. For other examples (those that require aggregation), no loss is accumulated. In the setting
+ where aggregation type is always known, standard cross entropy loss is accumulated for all examples
+
+ Args:
+ logits_aggregation (`torch.FloatTensor` of shape `(batch_size, num_aggregation_labels)`):
+ Logits per aggregation operation.
+ aggregate_mask (`torch.FloatTensor` of shape `(batch_size, )`):
+ A mask set to 1 for examples that should use aggregation functions.
+ aggregation_labels (`torch.LongTensor` of shape `(batch_size, )`):
+ Aggregation function id for every example in the batch.
+ use_answer_as_supervision (`bool`, *optional*):
+ Whether to use the answer as the only supervision for aggregation examples.
+ num_aggregation_labels (`int`, *optional*, defaults to 0):
+ The number of aggregation operators to predict.
+
+ Returns:
+ aggregation_loss_known (`torch.FloatTensor` of shape `(batch_size,)`): Aggregation loss (when its type is known
+ during training) per example.
+ """
+ if use_answer_as_supervision:
+ # Prepare "no aggregation" targets for cell selection examples.
+ target_aggregation = torch.zeros_like(aggregate_mask, dtype=torch.long)
+ else:
+ # Use aggregation supervision as the target.
+ target_aggregation = aggregation_labels
+
+ one_hot_labels = nn.functional.one_hot(target_aggregation, num_classes=num_aggregation_labels).type(torch.float32)
+ log_probs = nn.functional.log_softmax(logits_aggregation, dim=-1)
+
+ # torch.FloatTensor[batch_size]
+ per_example_aggregation_intermediate = -torch.sum(one_hot_labels * log_probs, dim=-1)
+ if use_answer_as_supervision:
+ # Accumulate loss only for examples requiring cell selection
+ # (no aggregation).
+ return per_example_aggregation_intermediate * (1 - aggregate_mask)
+ else:
+ return per_example_aggregation_intermediate
+
+
+def _calculate_aggregation_loss_unknown(logits_aggregation, aggregate_mask):
+ """
+ Calculates aggregation loss in the case of answer supervision.
+
+ Args:
+ logits_aggregation (`torch.FloatTensor` of shape `(batch_size, num_aggregation_labels)`):
+ Logits per aggregation operation.
+ aggregate_mask (`torch.FloatTensor` of shape `(batch_size, )`):
+ A mask set to 1 for examples that should use aggregation functions
+
+ Returns:
+ aggregation_loss_unknown (`torch.FloatTensor` of shape `(batch_size,)`): Aggregation loss (in case of answer
+ supervision) per example.
+ """
+ dist_aggregation = torch.distributions.categorical.Categorical(logits=logits_aggregation)
+ # Index 0 corresponds to "no aggregation".
+ aggregation_ops_total_mass = torch.sum(dist_aggregation.probs[:, 1:], dim=1)
+ # Predict some aggregation in case of an answer that needs aggregation.
+ # This increases the probability of all aggregation functions, in a way
+ # similar to MML, but without considering whether the function gives the
+ # correct answer.
+ return -torch.log(aggregation_ops_total_mass) * aggregate_mask
+
+
+def _calculate_aggregation_loss(
+ logits_aggregation,
+ aggregate_mask,
+ aggregation_labels,
+ use_answer_as_supervision,
+ num_aggregation_labels,
+ aggregation_loss_weight,
+):
+ """
+ Calculates the aggregation loss per example.
+
+ Args:
+ logits_aggregation (`torch.FloatTensor` of shape `(batch_size, num_aggregation_labels)`):
+ Logits per aggregation operation.
+ aggregate_mask (`torch.FloatTensor` of shape `(batch_size, )`):
+ A mask set to 1 for examples that should use aggregation functions.
+ aggregation_labels (`torch.LongTensor` of shape `(batch_size, )`):
+ Aggregation function id for every example in the batch.
+ use_answer_as_supervision (`bool`, *optional*):
+ Whether to use the answer as the only supervision for aggregation examples.
+ num_aggregation_labels (`int`, *optional*, defaults to 0):
+ The number of aggregation operators to predict.
+ aggregation_loss_weight (`float`, *optional*, defaults to 1.0):
+ Importance weight for the aggregation loss.
+
+ Returns:
+ aggregation_loss (`torch.FloatTensor` of shape `(batch_size,)`): Aggregation loss per example.
+ """
+ per_example_aggregation_loss = _calculate_aggregation_loss_known(
+ logits_aggregation, aggregate_mask, aggregation_labels, use_answer_as_supervision, num_aggregation_labels
+ )
+
+ if use_answer_as_supervision:
+ # Add aggregation loss for numeric answers that need aggregation.
+ per_example_aggregation_loss += _calculate_aggregation_loss_unknown(logits_aggregation, aggregate_mask)
+ return aggregation_loss_weight * per_example_aggregation_loss
+
+
+def _calculate_expected_result(
+ dist_per_cell, numeric_values, numeric_values_scale, input_mask_float, logits_aggregation, config
+):
+ """
+ Calculates the expected result given cell and aggregation probabilities.
+
+ Args:
+ dist_per_cell (`torch.distributions.Bernoulli`):
+ Cell selection distribution for each cell.
+ numeric_values (`torch.FloatTensor` of shape `(batch_size, seq_length)`):
+ Numeric values of every token. Nan for tokens which are not numeric values.
+ numeric_values_scale (`torch.FloatTensor` of shape `(batch_size, seq_length)`):
+ Scale of the numeric values of every token.
+ input_mask_float (`torch.FloatTensor` of shape `(batch_size, seq_length)`):
+ Mask for the table, without question tokens and table headers.
+ logits_aggregation (`torch.FloatTensor` of shape `(batch_size, num_aggregation_labels)`):
+ Logits per aggregation operation.
+ config ([`TapasConfig`]):
+ Model configuration class with all the hyperparameters of the model
+
+ Returns:
+ expected_result (`torch.FloatTensor` of shape `(batch_size,)`): The expected result per example.
+ """
+ if config.use_gumbel_for_cells:
+ gumbel_dist = torch.distributions.RelaxedBernoulli(
+ # The token logits where already divided by the temperature and used for
+ # computing cell selection errors so we need to multiply it again here
+ temperature=config.temperature,
+ logits=dist_per_cell.logits * config.temperature,
+ )
+ scaled_probability_per_cell = gumbel_dist.sample()
+ else:
+ scaled_probability_per_cell = dist_per_cell.probs
+
+ # [batch_size, seq_length]
+ scaled_probability_per_cell = (scaled_probability_per_cell / numeric_values_scale) * input_mask_float
+ count_result = torch.sum(scaled_probability_per_cell, dim=1)
+ numeric_values_masked = torch.where(
+ torch.isnan(numeric_values), torch.zeros_like(numeric_values), numeric_values
+ ) # Mask non-numeric table values to zero.
+ sum_result = torch.sum(scaled_probability_per_cell * numeric_values_masked, dim=1)
+ avg_approximation = config.average_approximation_function
+ if avg_approximation == AverageApproximationFunction.RATIO:
+ average_result = sum_result / (count_result + EPSILON_ZERO_DIVISION)
+ elif avg_approximation == AverageApproximationFunction.FIRST_ORDER:
+ # The sum of all probabilities except that correspond to other cells
+ # Ex here stands for expectation, more explicitly the expectation of the sum of N-1 Bernoulli random variables plus
+ # the constant 1, which is computed as adding all N expected values and subtracting the extra one. It corresponds to X_c
+ # in Appendix D of the original TAPAS paper which is trying to approximate the average of a random set.
+ ex = torch.sum(scaled_probability_per_cell, dim=1, keepdim=True) - scaled_probability_per_cell + 1
+ average_result = torch.sum(numeric_values_masked * scaled_probability_per_cell / ex, dim=1)
+ elif avg_approximation == AverageApproximationFunction.SECOND_ORDER:
+ # The sum of all probabilities except that correspond to other cells
+ ex = torch.sum(scaled_probability_per_cell, dim=1, keepdim=True) - scaled_probability_per_cell + 1
+ pointwise_var = scaled_probability_per_cell * (1 - scaled_probability_per_cell)
+ var = torch.sum(pointwise_var, dim=1, keepdim=True) - pointwise_var
+
+ multiplier = (var / torch.square(ex) + 1) / ex
+ average_result = torch.sum(numeric_values_masked * scaled_probability_per_cell * multiplier, dim=1)
+ else:
+ raise ValueError(f"Invalid average_approximation_function: {config.average_approximation_function}")
+
+ if config.use_gumbel_for_aggregation:
+ gumbel_dist = torch.distributions.RelaxedOneHotCategorical(
+ config.aggregation_temperature, logits=logits_aggregation[:, 1:]
+ )
+ # [batch_size, num_aggregation_labels - 1]
+ aggregation_op_only_probs = gumbel_dist.sample()
+ else:
+ # [batch_size, num_aggregation_labels - 1]
+ aggregation_op_only_probs = nn.functional.softmax(
+ logits_aggregation[:, 1:] / config.aggregation_temperature, dim=-1
+ )
+
+ all_results = torch.cat(
+ [
+ torch.unsqueeze(sum_result, dim=1),
+ torch.unsqueeze(average_result, dim=1),
+ torch.unsqueeze(count_result, dim=1),
+ ],
+ dim=1,
+ )
+
+ expected_result = torch.sum(all_results * aggregation_op_only_probs, dim=1)
+ return expected_result
+
+
+# PyTorch does not currently support Huber loss with custom delta so we define it ourself
+def huber_loss(input, target, delta: float = 1.0):
+ errors = torch.abs(input - target) # shape (batch_size,)
+ return torch.where(errors < delta, 0.5 * errors**2, errors * delta - (0.5 * delta**2))
+
+
+def _calculate_regression_loss(
+ answer,
+ aggregate_mask,
+ dist_per_cell,
+ numeric_values,
+ numeric_values_scale,
+ input_mask_float,
+ logits_aggregation,
+ config,
+):
+ """
+ Calculates the regression loss per example.
+
+ Args:
+ answer (`torch.FloatTensor` of shape `(batch_size,)`):
+ Answer for every example in the batch. Nan if there is no scalar answer.
+ aggregate_mask (`torch.FloatTensor` of shape `(batch_size,)`):
+ A mask set to 1 for examples that should use aggregation functions.
+ dist_per_cell (`torch.distributions.Bernoulli`):
+ Cell selection distribution for each cell.
+ numeric_values (`torch.FloatTensor` of shape `(batch_size, seq_length)`):
+ Numeric values of every token. Nan for tokens which are not numeric values.
+ numeric_values_scale (`torch.FloatTensor` of shape `(batch_size, seq_length)`):
+ Scale of the numeric values of every token.
+ input_mask_float (`torch.FloatTensor` of shape `(batch_size, seq_length)`):
+ Mask for the table, without question tokens and table headers.
+ logits_aggregation (`torch.FloatTensor` of shape `(batch_size, num_aggregation_labels)`):
+ Logits per aggregation operation.
+ config ([`TapasConfig`]):
+ Model configuration class with all the parameters of the model
+
+ Returns:
+ per_example_answer_loss_scaled (`torch.FloatTensor` of shape `(batch_size,)`): Scales answer loss for each
+ example in the batch. large_answer_loss_mask (`torch.FloatTensor` of shape `(batch_size,)`): A mask which is 1
+ for examples for which their answer loss is larger than the answer_loss_cutoff.
+ """
+ # float32 (batch_size,)
+ expected_result = _calculate_expected_result(
+ dist_per_cell, numeric_values, numeric_values_scale, input_mask_float, logits_aggregation, config
+ )
+
+ # float32 (batch_size,)
+ answer_masked = torch.where(torch.isnan(answer), torch.zeros_like(answer), answer)
+
+ if config.use_normalized_answer_loss:
+ normalizer = (torch.max(torch.abs(expected_result), torch.abs(answer_masked)) + EPSILON_ZERO_DIVISION).detach()
+
+ normalized_answer_masked = answer_masked / normalizer
+ normalized_expected_result = expected_result / normalizer
+ per_example_answer_loss = huber_loss(
+ normalized_expected_result * aggregate_mask, normalized_answer_masked * aggregate_mask
+ )
+ else:
+ per_example_answer_loss = huber_loss(
+ expected_result * aggregate_mask, answer_masked * aggregate_mask, delta=config.huber_loss_delta
+ )
+
+ if config.answer_loss_cutoff is None:
+ large_answer_loss_mask = torch.ones_like(per_example_answer_loss, dtype=torch.float32)
+
+ else:
+ large_answer_loss_mask = torch.where(
+ per_example_answer_loss > config.answer_loss_cutoff,
+ torch.zeros_like(per_example_answer_loss, dtype=torch.float32),
+ torch.ones_like(per_example_answer_loss, dtype=torch.float32),
+ )
+ per_example_answer_loss_scaled = config.answer_loss_importance * (per_example_answer_loss * aggregate_mask)
+
+ return per_example_answer_loss_scaled, large_answer_loss_mask
+
+
+__all__ = [
+ "TapasForMaskedLM",
+ "TapasForQuestionAnswering",
+ "TapasForSequenceClassification",
+ "TapasModel",
+ "TapasPreTrainedModel",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/tapas/tokenization_tapas.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/tapas/tokenization_tapas.py
new file mode 100644
index 0000000000000000000000000000000000000000..5d100c8f6f4dad3ceb44d4252ca6ab5c712fd7eb
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/tapas/tokenization_tapas.py
@@ -0,0 +1,2786 @@
+# Copyright 2020 Google Research and The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Tokenization class for TAPAS model."""
+
+import collections
+import datetime
+import enum
+import itertools
+import math
+import os
+import re
+import unicodedata
+from collections.abc import Callable, Generator
+from dataclasses import dataclass
+from typing import Union
+
+import numpy as np
+
+from ...tokenization_python import PreTrainedTokenizer, Trie, _is_control, _is_punctuation, _is_whitespace
+from ...tokenization_utils_base import (
+ ENCODE_KWARGS_DOCSTRING,
+ VERY_LARGE_INTEGER,
+ BatchEncoding,
+ EncodedInput,
+ PreTokenizedInput,
+ TextInput,
+)
+from ...utils import ExplicitEnum, PaddingStrategy, TensorType, add_end_docstrings, is_pandas_available, logging
+
+
+if is_pandas_available():
+ import pandas as pd
+
+logger = logging.get_logger(__name__)
+
+
+VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt"}
+
+
+class TapasTruncationStrategy(ExplicitEnum):
+ """
+ Possible values for the `truncation` argument in [`~TapasTokenizer.__call__`]. Useful for tab-completion in an IDE.
+ """
+
+ DROP_ROWS_TO_FIT = "drop_rows_to_fit"
+ DO_NOT_TRUNCATE = "do_not_truncate"
+
+
+TableValue = collections.namedtuple("TokenValue", ["token", "column_id", "row_id"])
+
+
+@dataclass(frozen=True)
+class TokenCoordinates:
+ column_index: int
+ row_index: int
+ token_index: int
+
+
+@dataclass
+class TokenizedTable:
+ rows: list[list[list[str]]]
+ selected_tokens: list[TokenCoordinates]
+
+
+@dataclass(frozen=True)
+class SerializedExample:
+ tokens: list[str]
+ column_ids: list[int]
+ row_ids: list[int]
+ segment_ids: list[int]
+
+
+def _is_inner_wordpiece(token: str):
+ return token.startswith("##")
+
+
+def load_vocab(vocab_file):
+ """Loads a vocabulary file into a dictionary."""
+ vocab = collections.OrderedDict()
+ with open(vocab_file, "r", encoding="utf-8") as reader:
+ tokens = reader.readlines()
+ for index, token in enumerate(tokens):
+ token = token.rstrip("\n")
+ vocab[token] = index
+ return vocab
+
+
+def whitespace_tokenize(text):
+ """Runs basic whitespace cleaning and splitting on a piece of text."""
+ text = text.strip()
+ if not text:
+ return []
+ tokens = text.split()
+ return tokens
+
+
+TAPAS_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING = r"""
+ add_special_tokens (`bool`, *optional*, defaults to `True`):
+ Whether or not to encode the sequences with the special tokens relative to their model.
+ padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`):
+ Activates and controls padding. Accepts the following values:
+
+ - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
+ sequence if provided).
+ - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
+ acceptable input length for the model if that argument is not provided.
+ - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
+ lengths).
+ truncation (`bool`, `str` or [`TapasTruncationStrategy`], *optional*, defaults to `False`):
+ Activates and controls truncation. Accepts the following values:
+
+ - `True` or `'drop_rows_to_fit'`: Truncate to a maximum length specified with the argument `max_length`
+ or to the maximum acceptable input length for the model if that argument is not provided. This will
+ truncate row by row, removing rows from the table.
+ - `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths
+ greater than the model maximum admissible input size).
+ max_length (`int`, *optional*):
+ Controls the maximum length to use by one of the truncation/padding parameters.
+
+ If left unset or set to `None`, this will use the predefined model maximum length if a maximum length
+ is required by one of the truncation/padding parameters. If the model has no specific maximum input
+ length (like XLNet) truncation/padding to a maximum length will be deactivated.
+ is_split_into_words (`bool`, *optional*, defaults to `False`):
+ Whether or not the input is already pre-tokenized (e.g., split into words). If set to `True`, the
+ tokenizer assumes the input is already split into words (for instance, by splitting it on whitespace)
+ which it will tokenize. This is useful for NER or token classification.
+ pad_to_multiple_of (`int`, *optional*):
+ If set will pad the sequence to a multiple of the provided value. This is especially useful to enable
+ the use of Tensor Cores on NVIDIA hardware with compute capability `>= 7.5` (Volta).
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
+ If set, will return tensors instead of list of python integers. Acceptable values are:
+
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
+ - `'np'`: Return Numpy `np.ndarray` objects.
+"""
+
+
+class TapasTokenizer(PreTrainedTokenizer):
+ r"""
+ Construct a TAPAS tokenizer. Based on WordPiece. Flattens a table and one or more related sentences to be used by
+ TAPAS models.
+
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
+ this superclass for more information regarding those methods. [`TapasTokenizer`] creates several token type ids to
+ encode tabular structure. To be more precise, it adds 7 token type ids, in the following order: `segment_ids`,
+ `column_ids`, `row_ids`, `prev_labels`, `column_ranks`, `inv_column_ranks` and `numeric_relations`:
+
+ - segment_ids: indicate whether a token belongs to the question (0) or the table (1). 0 for special tokens and
+ padding.
+ - column_ids: indicate to which column of the table a token belongs (starting from 1). Is 0 for all question
+ tokens, special tokens and padding.
+ - row_ids: indicate to which row of the table a token belongs (starting from 1). Is 0 for all question tokens,
+ special tokens and padding. Tokens of column headers are also 0.
+ - prev_labels: indicate whether a token was (part of) an answer to the previous question (1) or not (0). Useful in
+ a conversational setup (such as SQA).
+ - column_ranks: indicate the rank of a table token relative to a column, if applicable. For example, if you have a
+ column "number of movies" with values 87, 53 and 69, then the column ranks of these tokens are 3, 1 and 2
+ respectively. 0 for all question tokens, special tokens and padding.
+ - inv_column_ranks: indicate the inverse rank of a table token relative to a column, if applicable. For example, if
+ you have a column "number of movies" with values 87, 53 and 69, then the inverse column ranks of these tokens are
+ 1, 3 and 2 respectively. 0 for all question tokens, special tokens and padding.
+ - numeric_relations: indicate numeric relations between the question and the tokens of the table. 0 for all
+ question tokens, special tokens and padding.
+
+ [`TapasTokenizer`] runs end-to-end tokenization on a table and associated sentences: punctuation splitting and
+ wordpiece.
+
+ Args:
+ vocab_file (`str`):
+ File containing the vocabulary.
+ do_lower_case (`bool`, *optional*, defaults to `True`):
+ Whether or not to lowercase the input when tokenizing.
+ do_basic_tokenize (`bool`, *optional*, defaults to `True`):
+ Whether or not to do basic tokenization before WordPiece.
+ never_split (`Iterable`, *optional*):
+ Collection of tokens which will never be split during tokenization. Only has an effect when
+ `do_basic_tokenize=True`
+ unk_token (`str`, *optional*, defaults to `"[UNK]"`):
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
+ token instead.
+ sep_token (`str`, *optional*, defaults to `"[SEP]"`):
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
+ sequence classification or for a text and a question for question answering. It is also used as the last
+ token of a sequence built with special tokens.
+ pad_token (`str`, *optional*, defaults to `"[PAD]"`):
+ The token used for padding, for example when batching sequences of different lengths.
+ cls_token (`str`, *optional*, defaults to `"[CLS]"`):
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
+ mask_token (`str`, *optional*, defaults to `"[MASK]"`):
+ The token used for masking values. This is the token used when training this model with masked language
+ modeling. This is the token which the model will try to predict.
+ empty_token (`str`, *optional*, defaults to `"[EMPTY]"`):
+ The token used for empty cell values in a table. Empty cell values include "", "n/a", "nan" and "?".
+ tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
+ Whether or not to tokenize Chinese characters. This should likely be deactivated for Japanese (see this
+ [issue](https://github.com/huggingface/transformers/issues/328)).
+ strip_accents (`bool`, *optional*):
+ Whether or not to strip all accents. If this option is not specified, then it will be determined by the
+ value for `lowercase` (as in the original BERT).
+ cell_trim_length (`int`, *optional*, defaults to -1):
+ If > 0: Trim cells so that the length is <= this value. Also disables further cell trimming, should thus be
+ used with `truncation` set to `True`.
+ max_column_id (`int`, *optional*):
+ Max column id to extract.
+ max_row_id (`int`, *optional*):
+ Max row id to extract.
+ strip_column_names (`bool`, *optional*, defaults to `False`):
+ Whether to add empty strings instead of column names.
+ update_answer_coordinates (`bool`, *optional*, defaults to `False`):
+ Whether to recompute the answer coordinates from the answer text.
+ min_question_length (`int`, *optional*):
+ Minimum length of each question in terms of tokens (will be skipped otherwise).
+ max_question_length (`int`, *optional*):
+ Maximum length of each question in terms of tokens (will be skipped otherwise).
+ clean_up_tokenization_spaces (`bool`, *optional*, defaults to `True`):
+ Whether or not to cleanup spaces after decoding, cleanup consists in removing potential artifacts like
+ extra spaces.
+ """
+
+ model_input_names = ["input_ids", "attention_mask", "token_type_ids"]
+ vocab_files_names = VOCAB_FILES_NAMES
+
+ def __init__(
+ self,
+ vocab_file,
+ do_lower_case=True,
+ do_basic_tokenize=True,
+ never_split=None,
+ unk_token="[UNK]",
+ sep_token="[SEP]",
+ pad_token="[PAD]",
+ cls_token="[CLS]",
+ mask_token="[MASK]",
+ empty_token="[EMPTY]",
+ tokenize_chinese_chars=True,
+ strip_accents=None,
+ cell_trim_length: int = -1,
+ max_column_id: int | None = None,
+ max_row_id: int | None = None,
+ strip_column_names: bool = False,
+ update_answer_coordinates: bool = False,
+ min_question_length=None,
+ max_question_length=None,
+ model_max_length: int = 512,
+ additional_special_tokens: list[str] | None = None,
+ clean_up_tokenization_spaces=True,
+ **kwargs,
+ ):
+ if not is_pandas_available():
+ raise ImportError("Pandas is required for the TAPAS tokenizer.")
+
+ if additional_special_tokens is not None:
+ if empty_token not in additional_special_tokens:
+ additional_special_tokens.append(empty_token)
+ else:
+ additional_special_tokens = [empty_token]
+
+ if not os.path.isfile(vocab_file):
+ raise ValueError(
+ f"Can't find a vocabulary file at path '{vocab_file}'. To load the vocabulary from a Google pretrained"
+ " model use `tokenizer = BertTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`"
+ )
+ self.vocab = load_vocab(vocab_file)
+ self.ids_to_tokens = collections.OrderedDict([(ids, tok) for tok, ids in self.vocab.items()])
+ self.do_basic_tokenize = do_basic_tokenize
+ if do_basic_tokenize:
+ self.basic_tokenizer = BasicTokenizer(
+ do_lower_case=do_lower_case,
+ never_split=never_split,
+ tokenize_chinese_chars=tokenize_chinese_chars,
+ strip_accents=strip_accents,
+ )
+ self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab, unk_token=str(unk_token))
+
+ # Additional properties
+ self.cell_trim_length = cell_trim_length
+ self.max_column_id = (
+ max_column_id
+ if max_column_id is not None
+ else model_max_length
+ if model_max_length is not None
+ else VERY_LARGE_INTEGER
+ )
+ self.max_row_id = (
+ max_row_id
+ if max_row_id is not None
+ else model_max_length
+ if model_max_length is not None
+ else VERY_LARGE_INTEGER
+ )
+ self.strip_column_names = strip_column_names
+ self.update_answer_coordinates = update_answer_coordinates
+ self.min_question_length = min_question_length
+ self.max_question_length = max_question_length
+
+ super().__init__(
+ do_lower_case=do_lower_case,
+ do_basic_tokenize=do_basic_tokenize,
+ never_split=never_split,
+ unk_token=unk_token,
+ sep_token=sep_token,
+ pad_token=pad_token,
+ cls_token=cls_token,
+ mask_token=mask_token,
+ empty_token=empty_token,
+ tokenize_chinese_chars=tokenize_chinese_chars,
+ strip_accents=strip_accents,
+ cell_trim_length=cell_trim_length,
+ max_column_id=max_column_id,
+ max_row_id=max_row_id,
+ strip_column_names=strip_column_names,
+ update_answer_coordinates=update_answer_coordinates,
+ min_question_length=min_question_length,
+ max_question_length=max_question_length,
+ model_max_length=model_max_length,
+ additional_special_tokens=additional_special_tokens,
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
+ **kwargs,
+ )
+
+ # Tests override the vocab while reusing a tokenizer_config.json coming from a pretrained model.
+ # This can register base vocab tokens (like [UNK]) as added tokens with mismatched ids (e.g. 100)
+ # and breaks assumptions on token ordering. Drop any added-token entry that overlaps with the vocab
+ # so these tokens rely on the vocab-provided ids.
+ removed_overlap = False
+ for token, added_id in list(self._added_tokens_encoder.items()):
+ if token in self.vocab:
+ self._added_tokens_encoder.pop(token, None)
+ self._added_tokens_decoder.pop(added_id, None)
+ removed_overlap = True
+ if removed_overlap:
+ self.tokens_trie = Trie()
+ self._update_trie()
+
+ @property
+ def do_lower_case(self):
+ return self.basic_tokenizer.do_lower_case
+
+ @property
+ def vocab_size(self):
+ return len(self.vocab)
+
+ def get_vocab(self):
+ return dict(self.vocab, **self.added_tokens_encoder)
+
+ def _tokenize(self, text):
+ if format_text(text) == EMPTY_TEXT:
+ return [self.extra_special_tokens[0]]
+ split_tokens = []
+ if self.do_basic_tokenize:
+ for token in self.basic_tokenizer.tokenize(text, never_split=self.all_special_tokens):
+ # If the token is part of the never_split set
+ if token in self.basic_tokenizer.never_split:
+ split_tokens.append(token)
+ else:
+ split_tokens += self.wordpiece_tokenizer.tokenize(token)
+ else:
+ split_tokens = self.wordpiece_tokenizer.tokenize(text)
+ return split_tokens
+
+ def _convert_token_to_id(self, token):
+ """Converts a token (str) in an id using the vocab."""
+ return self.vocab.get(token, self.vocab.get(self.unk_token))
+
+ def _convert_id_to_token(self, index):
+ """Converts an index (integer) in a token (str) using the vocab."""
+ return self.ids_to_tokens.get(index, self.unk_token)
+
+ def convert_tokens_to_string(self, tokens):
+ """Converts a sequence of tokens (string) in a single string."""
+ out_string = " ".join(tokens).replace(" ##", "").strip()
+ return out_string
+
+ def save_vocabulary(self, save_directory: str, filename_prefix: str | None = None) -> tuple[str]:
+ index = 0
+ if os.path.isdir(save_directory):
+ vocab_file = os.path.join(
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
+ )
+ else:
+ vocab_file = (filename_prefix + "-" if filename_prefix else "") + save_directory
+ with open(vocab_file, "w", encoding="utf-8") as writer:
+ for token, token_index in sorted(self.vocab.items(), key=lambda kv: kv[1]):
+ if index != token_index:
+ logger.warning(
+ f"Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive."
+ " Please check that the vocabulary is not corrupted!"
+ )
+ index = token_index
+ writer.write(token + "\n")
+ index += 1
+ return (vocab_file,)
+
+ def create_attention_mask_from_sequences(self, query_ids: list[int], table_values: list[TableValue]) -> list[int]:
+ """
+ Creates the attention mask according to the query token IDs and a list of table values.
+
+ Args:
+ query_ids (`list[int]`): list of token IDs corresponding to the ID.
+ table_values (`list[TableValue]`): lift of table values, which are named tuples containing the
+ token value, the column ID and the row ID of said token.
+
+ Returns:
+ `list[int]`: List of ints containing the attention mask values.
+ """
+ return [1] * (1 + len(query_ids) + 1 + len(table_values))
+
+ def create_segment_token_type_ids_from_sequences(
+ self, query_ids: list[int], table_values: list[TableValue]
+ ) -> list[int]:
+ """
+ Creates the segment token type IDs according to the query token IDs and a list of table values.
+
+ Args:
+ query_ids (`list[int]`): list of token IDs corresponding to the ID.
+ table_values (`list[TableValue]`): lift of table values, which are named tuples containing the
+ token value, the column ID and the row ID of said token.
+
+ Returns:
+ `list[int]`: List of ints containing the segment token type IDs values.
+ """
+ table_ids = list(zip(*table_values))[0] if table_values else []
+ return [0] * (1 + len(query_ids) + 1) + [1] * len(table_ids)
+
+ def create_column_token_type_ids_from_sequences(
+ self, query_ids: list[int], table_values: list[TableValue]
+ ) -> list[int]:
+ """
+ Creates the column token type IDs according to the query token IDs and a list of table values.
+
+ Args:
+ query_ids (`list[int]`): list of token IDs corresponding to the ID.
+ table_values (`list[TableValue]`): lift of table values, which are named tuples containing the
+ token value, the column ID and the row ID of said token.
+
+ Returns:
+ `list[int]`: List of ints containing the column token type IDs values.
+ """
+ table_column_ids = list(zip(*table_values))[1] if table_values else []
+ return [0] * (1 + len(query_ids) + 1) + list(table_column_ids)
+
+ def create_row_token_type_ids_from_sequences(
+ self, query_ids: list[int], table_values: list[TableValue]
+ ) -> list[int]:
+ """
+ Creates the row token type IDs according to the query token IDs and a list of table values.
+
+ Args:
+ query_ids (`list[int]`): list of token IDs corresponding to the ID.
+ table_values (`list[TableValue]`): lift of table values, which are named tuples containing the
+ token value, the column ID and the row ID of said token.
+
+ Returns:
+ `list[int]`: List of ints containing the row token type IDs values.
+ """
+ table_row_ids = list(zip(*table_values))[2] if table_values else []
+ return [0] * (1 + len(query_ids) + 1) + list(table_row_ids)
+
+ def build_inputs_with_special_tokens(
+ self, token_ids_0: list[int], token_ids_1: list[int] | None = None
+ ) -> list[int]:
+ """
+ Build model inputs from a question and flattened table for question answering or sequence classification tasks
+ by concatenating and adding special tokens.
+
+ Args:
+ token_ids_0 (`list[int]`): The ids of the question.
+ token_ids_1 (`list[int]`, *optional*): The ids of the flattened table.
+
+ Returns:
+ `list[int]`: The model input with special tokens.
+ """
+ if token_ids_1 is None:
+ raise ValueError("With TAPAS, you must provide both question IDs and table IDs.")
+
+ return [self.cls_token_id] + token_ids_0 + [self.sep_token_id] + token_ids_1
+
+ def get_special_tokens_mask(
+ self, token_ids_0: list[int], token_ids_1: list[int] | None = None, already_has_special_tokens: bool = False
+ ) -> list[int]:
+ """
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
+ special tokens using the tokenizer `prepare_for_model` method.
+
+ Args:
+ token_ids_0 (`list[int]`):
+ List of question IDs.
+ token_ids_1 (`list[int]`, *optional*):
+ List of flattened table IDs.
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
+ Whether or not the token list is already formatted with special tokens for the model.
+
+ Returns:
+ `list[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
+ """
+
+ if already_has_special_tokens:
+ return super().get_special_tokens_mask(
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
+ )
+
+ if token_ids_1 is not None:
+ return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1))
+ return [1] + ([0] * len(token_ids_0)) + [1]
+
+ @add_end_docstrings(TAPAS_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
+ def __call__(
+ self,
+ table: Union["pd.DataFrame", TextInput, list[TextInput], None],
+ queries: TextInput
+ | PreTokenizedInput
+ | EncodedInput
+ | list[TextInput]
+ | list[PreTokenizedInput]
+ | list[EncodedInput]
+ | None = None,
+ answer_coordinates: list[tuple] | list[list[tuple]] | None = None,
+ answer_text: list[TextInput] | list[list[TextInput]] | None = None,
+ add_special_tokens: bool = True,
+ padding: bool | str | PaddingStrategy = False,
+ truncation: bool | str | TapasTruncationStrategy = False,
+ max_length: int | None = None,
+ pad_to_multiple_of: int | None = None,
+ padding_side: str | None = None,
+ return_tensors: str | TensorType | None = None,
+ return_token_type_ids: bool | None = None,
+ return_attention_mask: bool | None = None,
+ return_overflowing_tokens: bool = False,
+ return_special_tokens_mask: bool = False,
+ return_offsets_mapping: bool = False,
+ return_length: bool = False,
+ verbose: bool = True,
+ **kwargs,
+ ) -> BatchEncoding:
+ """
+ Main method to tokenize and prepare for the model one or several sequence(s) related to a table.
+
+ Args:
+ table (`pd.DataFrame` or `str` or `list[str]`):
+ Table containing tabular data. Note that all cell values must be text. Use *.astype(str)* on a Pandas
+ dataframe to convert it to string. When passing a string or list of strings, those will be interpreted
+ as queries with an empty table (to support generic tokenizer tests).
+ queries (`str` or `list[str]`):
+ Question or batch of questions related to a table to be encoded. Note that in case of a batch, all
+ questions must refer to the **same** table.
+ answer_coordinates (`list[Tuple]` or `list[list[Tuple]]`, *optional*):
+ Answer coordinates of each table-question pair in the batch. In case only a single table-question pair
+ is provided, then the answer_coordinates must be a single list of one or more tuples. Each tuple must
+ be a (row_index, column_index) pair. The first data row (not the column header row) has index 0. The
+ first column has index 0. In case a batch of table-question pairs is provided, then the
+ answer_coordinates must be a list of lists of tuples (each list corresponding to a single
+ table-question pair).
+ answer_text (`list[str]` or `list[list[str]]`, *optional*):
+ Answer text of each table-question pair in the batch. In case only a single table-question pair is
+ provided, then the answer_text must be a single list of one or more strings. Each string must be the
+ answer text of a corresponding answer coordinate. In case a batch of table-question pairs is provided,
+ then the answer_coordinates must be a list of lists of strings (each list corresponding to a single
+ table-question pair).
+ """
+ if not isinstance(table, pd.DataFrame):
+ if queries is not None:
+ raise AssertionError("Table must be of type pd.DataFrame when queries are provided separately.")
+ inferred_queries = table
+ table = pd.DataFrame.from_dict({})
+ queries = inferred_queries
+
+ # Input type checking for clearer error
+ valid_query = False
+
+ # Check that query has a valid type
+ if queries is None or isinstance(queries, str):
+ valid_query = True
+ elif isinstance(queries, (list, tuple)):
+ if len(queries) == 0 or isinstance(queries[0], str):
+ valid_query = True
+
+ if not valid_query:
+ raise ValueError(
+ "queries input must of type `str` (single example), `list[str]` (batch or single pretokenized"
+ " example). "
+ )
+ is_batched = isinstance(queries, (list, tuple))
+
+ if is_batched:
+ return self.batch_encode_plus(
+ table=table,
+ queries=queries,
+ answer_coordinates=answer_coordinates,
+ answer_text=answer_text,
+ add_special_tokens=add_special_tokens,
+ padding=padding,
+ truncation=truncation,
+ max_length=max_length,
+ pad_to_multiple_of=pad_to_multiple_of,
+ padding_side=padding_side,
+ return_tensors=return_tensors,
+ return_token_type_ids=return_token_type_ids,
+ return_attention_mask=return_attention_mask,
+ return_overflowing_tokens=return_overflowing_tokens,
+ return_special_tokens_mask=return_special_tokens_mask,
+ return_offsets_mapping=return_offsets_mapping,
+ return_length=return_length,
+ verbose=verbose,
+ **kwargs,
+ )
+ else:
+ return self.encode_plus(
+ table=table,
+ query=queries,
+ answer_coordinates=answer_coordinates,
+ answer_text=answer_text,
+ add_special_tokens=add_special_tokens,
+ padding=padding,
+ truncation=truncation,
+ max_length=max_length,
+ pad_to_multiple_of=pad_to_multiple_of,
+ padding_side=padding_side,
+ return_tensors=return_tensors,
+ return_token_type_ids=return_token_type_ids,
+ return_attention_mask=return_attention_mask,
+ return_overflowing_tokens=return_overflowing_tokens,
+ return_special_tokens_mask=return_special_tokens_mask,
+ return_offsets_mapping=return_offsets_mapping,
+ return_length=return_length,
+ verbose=verbose,
+ **kwargs,
+ )
+
+ @add_end_docstrings(ENCODE_KWARGS_DOCSTRING, TAPAS_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
+ def batch_encode_plus(
+ self,
+ table: "pd.DataFrame",
+ queries: list[TextInput] | list[PreTokenizedInput] | list[EncodedInput] | None = None,
+ answer_coordinates: list[list[tuple]] | None = None,
+ answer_text: list[list[TextInput]] | None = None,
+ add_special_tokens: bool = True,
+ padding: bool | str | PaddingStrategy = False,
+ truncation: bool | str | TapasTruncationStrategy = False,
+ max_length: int | None = None,
+ pad_to_multiple_of: int | None = None,
+ padding_side: str | None = None,
+ return_tensors: str | TensorType | None = None,
+ return_token_type_ids: bool | None = None,
+ return_attention_mask: bool | None = None,
+ return_overflowing_tokens: bool = False,
+ return_special_tokens_mask: bool = False,
+ return_offsets_mapping: bool = False,
+ return_length: bool = False,
+ verbose: bool = True,
+ **kwargs,
+ ) -> BatchEncoding:
+ """
+ Prepare a table and a list of strings for the model.
+
+
+
+ This method is deprecated, `__call__` should be used instead.
+
+
+
+ Args:
+ table (`pd.DataFrame`):
+ Table containing tabular data. Note that all cell values must be text. Use *.astype(str)* on a Pandas
+ dataframe to convert it to string.
+ queries (`list[str]`):
+ Batch of questions related to a table to be encoded. Note that all questions must refer to the **same**
+ table.
+ answer_coordinates (`list[Tuple]` or `list[list[Tuple]]`, *optional*):
+ Answer coordinates of each table-question pair in the batch. Each tuple must be a (row_index,
+ column_index) pair. The first data row (not the column header row) has index 0. The first column has
+ index 0. The answer_coordinates must be a list of lists of tuples (each list corresponding to a single
+ table-question pair).
+ answer_text (`list[str]` or `list[list[str]]`, *optional*):
+ Answer text of each table-question pair in the batch. In case a batch of table-question pairs is
+ provided, then the answer_coordinates must be a list of lists of strings (each list corresponding to a
+ single table-question pair). Each string must be the answer text of a corresponding answer coordinate.
+ """
+ if return_token_type_ids is not None and not add_special_tokens:
+ raise ValueError(
+ "Asking to return token_type_ids while setting add_special_tokens to False "
+ "results in an undefined behavior. Please set add_special_tokens to True or "
+ "set return_token_type_ids to None."
+ )
+
+ if (answer_coordinates and not answer_text) or (not answer_coordinates and answer_text):
+ raise ValueError("In case you provide answers, both answer_coordinates and answer_text should be provided")
+ elif answer_coordinates is None and answer_text is None:
+ answer_coordinates = answer_text = [None] * len(queries)
+
+ if "is_split_into_words" in kwargs:
+ raise NotImplementedError("Currently TapasTokenizer only supports questions as strings.")
+
+ if return_offsets_mapping:
+ raise NotImplementedError(
+ "return_offset_mapping is not available when using Python tokenizers. "
+ "To use this feature, change your tokenizer to one deriving from "
+ "transformers.PreTrainedTokenizerFast."
+ )
+
+ return self._batch_encode_plus(
+ table=table,
+ queries=queries,
+ answer_coordinates=answer_coordinates,
+ answer_text=answer_text,
+ add_special_tokens=add_special_tokens,
+ padding=padding,
+ truncation=truncation,
+ max_length=max_length,
+ pad_to_multiple_of=pad_to_multiple_of,
+ padding_side=padding_side,
+ return_tensors=return_tensors,
+ return_token_type_ids=return_token_type_ids,
+ return_attention_mask=return_attention_mask,
+ return_overflowing_tokens=return_overflowing_tokens,
+ return_special_tokens_mask=return_special_tokens_mask,
+ return_offsets_mapping=return_offsets_mapping,
+ return_length=return_length,
+ verbose=verbose,
+ **kwargs,
+ )
+
+ def _get_question_tokens(self, query):
+ """Tokenizes the query, taking into account the max and min question length."""
+
+ query_tokens = self.tokenize(query)
+ if self.max_question_length is not None and len(query_tokens) > self.max_question_length:
+ logger.warning("Skipping query as its tokens are longer than the max question length")
+ return "", []
+ if self.min_question_length is not None and len(query_tokens) < self.min_question_length:
+ logger.warning("Skipping query as its tokens are shorter than the min question length")
+ return "", []
+
+ return query, query_tokens
+
+ def _batch_encode_plus(
+ self,
+ table,
+ queries: list[TextInput] | list[PreTokenizedInput] | list[EncodedInput],
+ answer_coordinates: list[list[tuple]] | None = None,
+ answer_text: list[list[TextInput]] | None = None,
+ add_special_tokens: bool = True,
+ padding: bool | str | PaddingStrategy = False,
+ truncation: bool | str | TapasTruncationStrategy = False,
+ max_length: int | None = None,
+ pad_to_multiple_of: int | None = None,
+ padding_side: str | None = None,
+ return_tensors: str | TensorType | None = None,
+ return_token_type_ids: bool | None = True,
+ return_attention_mask: bool | None = None,
+ return_overflowing_tokens: bool = False,
+ return_special_tokens_mask: bool = False,
+ return_offsets_mapping: bool = False,
+ return_length: bool = False,
+ verbose: bool = True,
+ **kwargs,
+ ) -> BatchEncoding:
+ table_tokens = self._tokenize_table(table)
+
+ queries_tokens = []
+ for idx, query in enumerate(queries):
+ query, query_tokens = self._get_question_tokens(query)
+ queries[idx] = query
+ queries_tokens.append(query_tokens)
+
+ batch_outputs = self._batch_prepare_for_model(
+ table,
+ queries,
+ tokenized_table=table_tokens,
+ queries_tokens=queries_tokens,
+ answer_coordinates=answer_coordinates,
+ padding=padding,
+ truncation=truncation,
+ answer_text=answer_text,
+ add_special_tokens=add_special_tokens,
+ max_length=max_length,
+ pad_to_multiple_of=pad_to_multiple_of,
+ padding_side=padding_side,
+ return_tensors=return_tensors,
+ prepend_batch_axis=True,
+ return_attention_mask=return_attention_mask,
+ return_token_type_ids=return_token_type_ids,
+ return_overflowing_tokens=return_overflowing_tokens,
+ return_special_tokens_mask=return_special_tokens_mask,
+ return_length=return_length,
+ verbose=verbose,
+ )
+
+ return BatchEncoding(batch_outputs)
+
+ def _batch_prepare_for_model(
+ self,
+ raw_table: "pd.DataFrame",
+ raw_queries: list[TextInput] | list[PreTokenizedInput] | list[EncodedInput],
+ tokenized_table: TokenizedTable | None = None,
+ queries_tokens: list[list[str]] | None = None,
+ answer_coordinates: list[list[tuple]] | None = None,
+ answer_text: list[list[TextInput]] | None = None,
+ add_special_tokens: bool = True,
+ padding: bool | str | PaddingStrategy = False,
+ truncation: bool | str | TapasTruncationStrategy = False,
+ max_length: int | None = None,
+ pad_to_multiple_of: int | None = None,
+ padding_side: str | None = None,
+ return_tensors: str | TensorType | None = None,
+ return_token_type_ids: bool | None = True,
+ return_attention_mask: bool | None = True,
+ return_special_tokens_mask: bool = False,
+ return_offsets_mapping: bool = False,
+ return_length: bool = False,
+ verbose: bool = True,
+ prepend_batch_axis: bool = False,
+ **kwargs,
+ ) -> BatchEncoding:
+ batch_outputs = {}
+
+ for index, example in enumerate(zip(raw_queries, queries_tokens, answer_coordinates, answer_text)):
+ raw_query, query_tokens, answer_coords, answer_txt = example
+ outputs = self.prepare_for_model(
+ raw_table,
+ raw_query,
+ tokenized_table=tokenized_table,
+ query_tokens=query_tokens,
+ answer_coordinates=answer_coords,
+ answer_text=answer_txt,
+ add_special_tokens=add_special_tokens,
+ padding=PaddingStrategy.DO_NOT_PAD.value, # we pad in batch afterwards
+ truncation=truncation,
+ max_length=max_length,
+ pad_to_multiple_of=None, # we pad in batch afterwards
+ padding_side=None, # we pad in batch afterward
+ return_attention_mask=False, # we pad in batch afterwards
+ return_token_type_ids=return_token_type_ids,
+ return_special_tokens_mask=return_special_tokens_mask,
+ return_length=return_length,
+ return_tensors=None, # We convert the whole batch to tensors at the end
+ prepend_batch_axis=False,
+ verbose=verbose,
+ prev_answer_coordinates=answer_coordinates[index - 1] if index != 0 else None,
+ prev_answer_text=answer_text[index - 1] if index != 0 else None,
+ )
+
+ for key, value in outputs.items():
+ if key not in batch_outputs:
+ batch_outputs[key] = []
+ batch_outputs[key].append(value)
+
+ batch_outputs = self.pad(
+ batch_outputs,
+ padding=padding,
+ max_length=max_length,
+ pad_to_multiple_of=pad_to_multiple_of,
+ padding_side=padding_side,
+ return_attention_mask=return_attention_mask,
+ )
+
+ batch_outputs = BatchEncoding(batch_outputs, tensor_type=return_tensors)
+
+ return batch_outputs
+
+ @add_end_docstrings(ENCODE_KWARGS_DOCSTRING)
+ def encode(
+ self,
+ table: Union["pd.DataFrame", TextInput, list[TextInput]],
+ query: TextInput | PreTokenizedInput | EncodedInput | None = None,
+ add_special_tokens: bool = True,
+ padding: bool | str | PaddingStrategy = False,
+ truncation: bool | str | TapasTruncationStrategy = False,
+ max_length: int | None = None,
+ return_tensors: str | TensorType | None = None,
+ **kwargs,
+ ) -> list[int]:
+ """
+ Prepare a table and a string for the model. This method does not return token type IDs, attention masks, etc.
+ which are necessary for the model to work correctly. Use that method if you want to build your processing on
+ your own, otherwise refer to `__call__`.
+
+ Args:
+ table (`pd.DataFrame` or `str` or `list[str]`):
+ Table containing tabular data. When passing a string or list of strings, those will be interpreted as
+ queries with an empty table (to support generic tokenizer tests).
+ query (`str` or `list[str]`):
+ Question related to a table to be encoded.
+ """
+ if not isinstance(table, pd.DataFrame):
+ if query is not None:
+ raise AssertionError("Table must be of type pd.DataFrame when queries are provided separately.")
+ inferred_query = table
+ table = pd.DataFrame.from_dict({})
+ query = inferred_query
+
+ encoded_inputs = self.encode_plus(
+ table,
+ query=query,
+ add_special_tokens=add_special_tokens,
+ padding=padding,
+ truncation=truncation,
+ max_length=max_length,
+ return_tensors=return_tensors,
+ **kwargs,
+ )
+
+ return encoded_inputs["input_ids"]
+
+ @add_end_docstrings(ENCODE_KWARGS_DOCSTRING, TAPAS_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
+ def encode_plus(
+ self,
+ table: Union["pd.DataFrame", TextInput, list[TextInput]],
+ query: TextInput | PreTokenizedInput | EncodedInput | None = None,
+ answer_coordinates: list[tuple] | None = None,
+ answer_text: list[TextInput] | None = None,
+ add_special_tokens: bool = True,
+ padding: bool | str | PaddingStrategy = False,
+ truncation: bool | str | TapasTruncationStrategy = False,
+ max_length: int | None = None,
+ pad_to_multiple_of: int | None = None,
+ padding_side: str | None = None,
+ return_tensors: str | TensorType | None = None,
+ return_token_type_ids: bool | None = None,
+ return_attention_mask: bool | None = None,
+ return_special_tokens_mask: bool = False,
+ return_offsets_mapping: bool = False,
+ return_length: bool = False,
+ verbose: bool = True,
+ **kwargs,
+ ) -> BatchEncoding:
+ """
+ Prepare a table and a string for the model.
+
+ Args:
+ table (`pd.DataFrame` or `str` or `list[str]`):
+ Table containing tabular data. When passing a string or list of strings, those will be interpreted as
+ queries with an empty table (to support generic tokenizer tests).
+ query (`str` or `list[str]`):
+ Question related to a table to be encoded.
+ answer_coordinates (`list[Tuple]` or `list[list[Tuple]]`, *optional*):
+ Answer coordinates of each table-question pair in the batch. The answer_coordinates must be a single
+ list of one or more tuples. Each tuple must be a (row_index, column_index) pair. The first data row
+ (not the column header row) has index 0. The first column has index 0.
+ answer_text (`list[str]` or `list[list[str]]`, *optional*):
+ Answer text of each table-question pair in the batch. The answer_text must be a single list of one or
+ more strings. Each string must be the answer text of a corresponding answer coordinate.
+ """
+ if return_token_type_ids is not None and not add_special_tokens:
+ raise ValueError(
+ "Asking to return token_type_ids while setting add_special_tokens to False "
+ "results in an undefined behavior. Please set add_special_tokens to True or "
+ "set return_token_type_ids to None."
+ )
+
+ if (answer_coordinates and not answer_text) or (not answer_coordinates and answer_text):
+ raise ValueError("In case you provide answers, both answer_coordinates and answer_text should be provided")
+
+ if "is_split_into_words" in kwargs:
+ raise NotImplementedError("Currently TapasTokenizer only supports questions as strings.")
+
+ if return_offsets_mapping:
+ raise NotImplementedError(
+ "return_offset_mapping is not available when using Python tokenizers. "
+ "To use this feature, change your tokenizer to one deriving from "
+ "transformers.PreTrainedTokenizerFast."
+ )
+
+ if not isinstance(table, pd.DataFrame):
+ if query is not None:
+ raise AssertionError("Table must be of type pd.DataFrame when queries are provided separately.")
+ inferred_query = table
+ table = pd.DataFrame.from_dict({})
+ query = inferred_query
+
+ return self._encode_plus(
+ table=table,
+ query=query,
+ answer_coordinates=answer_coordinates,
+ answer_text=answer_text,
+ add_special_tokens=add_special_tokens,
+ truncation=truncation,
+ padding=padding,
+ max_length=max_length,
+ pad_to_multiple_of=pad_to_multiple_of,
+ padding_side=padding_side,
+ return_tensors=return_tensors,
+ return_token_type_ids=return_token_type_ids,
+ return_attention_mask=return_attention_mask,
+ return_special_tokens_mask=return_special_tokens_mask,
+ return_offsets_mapping=return_offsets_mapping,
+ return_length=return_length,
+ verbose=verbose,
+ **kwargs,
+ )
+
+ def _encode_plus(
+ self,
+ table: "pd.DataFrame",
+ query: TextInput | PreTokenizedInput | EncodedInput,
+ answer_coordinates: list[tuple] | None = None,
+ answer_text: list[TextInput] | None = None,
+ add_special_tokens: bool = True,
+ padding: bool | str | PaddingStrategy = False,
+ truncation: bool | str | TapasTruncationStrategy = False,
+ max_length: int | None = None,
+ pad_to_multiple_of: int | None = None,
+ padding_side: str | None = None,
+ return_tensors: str | TensorType | None = None,
+ return_token_type_ids: bool | None = True,
+ return_attention_mask: bool | None = True,
+ return_special_tokens_mask: bool = False,
+ return_offsets_mapping: bool = False,
+ return_length: bool = False,
+ verbose: bool = True,
+ **kwargs,
+ ):
+ if query is None:
+ query = ""
+ logger.warning(
+ "TAPAS is a question answering model but you have not passed a query. Please be aware that the "
+ "model will probably not behave correctly."
+ )
+
+ table_tokens = self._tokenize_table(table)
+ query, query_tokens = self._get_question_tokens(query)
+
+ return self.prepare_for_model(
+ table,
+ query,
+ tokenized_table=table_tokens,
+ query_tokens=query_tokens,
+ answer_coordinates=answer_coordinates,
+ answer_text=answer_text,
+ add_special_tokens=add_special_tokens,
+ truncation=truncation,
+ padding=padding,
+ max_length=max_length,
+ pad_to_multiple_of=pad_to_multiple_of,
+ padding_side=padding_side,
+ return_tensors=return_tensors,
+ prepend_batch_axis=True,
+ return_attention_mask=return_attention_mask,
+ return_token_type_ids=return_token_type_ids,
+ return_special_tokens_mask=return_special_tokens_mask,
+ return_length=return_length,
+ verbose=verbose,
+ )
+
+ @add_end_docstrings(ENCODE_KWARGS_DOCSTRING, TAPAS_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
+ def prepare_for_model(
+ self,
+ raw_table: "pd.DataFrame",
+ raw_query: TextInput | PreTokenizedInput | EncodedInput,
+ tokenized_table: TokenizedTable | None = None,
+ query_tokens: TokenizedTable | None = None,
+ answer_coordinates: list[tuple] | None = None,
+ answer_text: list[TextInput] | None = None,
+ add_special_tokens: bool = True,
+ padding: bool | str | PaddingStrategy = False,
+ truncation: bool | str | TapasTruncationStrategy = False,
+ max_length: int | None = None,
+ pad_to_multiple_of: int | None = None,
+ padding_side: str | None = None,
+ return_tensors: str | TensorType | None = None,
+ return_token_type_ids: bool | None = True,
+ return_attention_mask: bool | None = True,
+ return_special_tokens_mask: bool = False,
+ return_offsets_mapping: bool = False,
+ return_length: bool = False,
+ verbose: bool = True,
+ prepend_batch_axis: bool = False,
+ **kwargs,
+ ) -> BatchEncoding:
+ """
+ Prepares a sequence of input id so that it can be used by the model. It adds special tokens, truncates
+ sequences if overflowing while taking into account the special tokens.
+
+ Args:
+ raw_table (`pd.DataFrame`):
+ The original table before any transformation (like tokenization) was applied to it.
+ raw_query (`TextInput` or `PreTokenizedInput` or `EncodedInput`):
+ The original query before any transformation (like tokenization) was applied to it.
+ tokenized_table (`TokenizedTable`):
+ The table after tokenization.
+ query_tokens (`list[str]`):
+ The query after tokenization.
+ answer_coordinates (`list[Tuple]` or `list[list[Tuple]]`, *optional*):
+ Answer coordinates of each table-question pair in the batch. The answer_coordinates must be a single
+ list of one or more tuples. Each tuple must be a (row_index, column_index) pair. The first data row
+ (not the column header row) has index 0. The first column has index 0.
+ answer_text (`list[str]` or `list[list[str]]`, *optional*):
+ Answer text of each table-question pair in the batch. The answer_text must be a single list of one or
+ more strings. Each string must be the answer text of a corresponding answer coordinate.
+ """
+ if isinstance(padding, bool):
+ if padding and (max_length is not None or pad_to_multiple_of is not None):
+ padding = PaddingStrategy.MAX_LENGTH
+ else:
+ padding = PaddingStrategy.DO_NOT_PAD
+ elif not isinstance(padding, PaddingStrategy):
+ padding = PaddingStrategy(padding)
+
+ if isinstance(truncation, bool):
+ if truncation:
+ truncation = TapasTruncationStrategy.DROP_ROWS_TO_FIT
+ else:
+ truncation = TapasTruncationStrategy.DO_NOT_TRUNCATE
+ elif not isinstance(truncation, TapasTruncationStrategy):
+ truncation = TapasTruncationStrategy(truncation)
+
+ encoded_inputs = {}
+
+ is_part_of_batch = False
+ prev_answer_coordinates, prev_answer_text = None, None
+ if "prev_answer_coordinates" in kwargs and "prev_answer_text" in kwargs:
+ is_part_of_batch = True
+ prev_answer_coordinates = kwargs["prev_answer_coordinates"]
+ prev_answer_text = kwargs["prev_answer_text"]
+
+ num_rows = self._get_num_rows(raw_table, truncation != TapasTruncationStrategy.DO_NOT_TRUNCATE)
+ num_columns = self._get_num_columns(raw_table)
+ _, _, num_tokens = self._get_table_boundaries(tokenized_table)
+
+ if truncation != TapasTruncationStrategy.DO_NOT_TRUNCATE:
+ num_rows, num_tokens = self._get_truncated_table_rows(
+ query_tokens, tokenized_table, num_rows, num_columns, max_length, truncation_strategy=truncation
+ )
+ table_data = list(self._get_table_values(tokenized_table, num_columns, num_rows, num_tokens))
+
+ query_ids = self.convert_tokens_to_ids(query_tokens)
+ table_ids = list(zip(*table_data))[0] if len(table_data) > 0 else list(zip(*table_data))
+ table_ids = self.convert_tokens_to_ids(list(table_ids))
+
+ if "return_overflowing_tokens" in kwargs and kwargs["return_overflowing_tokens"]:
+ raise ValueError("TAPAS does not return overflowing tokens as it works on tables.")
+
+ if add_special_tokens:
+ input_ids = self.build_inputs_with_special_tokens(query_ids, table_ids)
+ else:
+ input_ids = query_ids + table_ids
+
+ if max_length is not None and len(input_ids) > max_length:
+ raise ValueError(
+ "Could not encode the query and table header given the maximum length. Encoding the query and table "
+ f"header results in a length of {len(input_ids)} which is higher than the max_length of {max_length}"
+ )
+
+ encoded_inputs["input_ids"] = input_ids
+
+ segment_ids = self.create_segment_token_type_ids_from_sequences(query_ids, table_data)
+ column_ids = self.create_column_token_type_ids_from_sequences(query_ids, table_data)
+ row_ids = self.create_row_token_type_ids_from_sequences(query_ids, table_data)
+ if not is_part_of_batch or (prev_answer_coordinates is None and prev_answer_text is None):
+ # simply set the prev_labels to zeros
+ prev_labels = [0] * len(row_ids)
+ else:
+ prev_labels = self.get_answer_ids(
+ column_ids, row_ids, table_data, prev_answer_text, prev_answer_coordinates
+ )
+
+ # FIRST: parse both the table and question in terms of numeric values
+
+ raw_table = add_numeric_table_values(raw_table)
+ raw_query = add_numeric_values_to_question(raw_query)
+
+ # SECOND: add numeric-related features (and not parse them in these functions):
+
+ column_ranks, inv_column_ranks = self._get_numeric_column_ranks(column_ids, row_ids, raw_table)
+ numeric_relations = self._get_numeric_relations(raw_query, column_ids, row_ids, raw_table)
+
+ # Load from model defaults
+ if return_token_type_ids is None:
+ return_token_type_ids = "token_type_ids" in self.model_input_names
+ if return_attention_mask is None:
+ return_attention_mask = "attention_mask" in self.model_input_names
+
+ if return_attention_mask:
+ attention_mask = self.create_attention_mask_from_sequences(query_ids, table_data)
+ encoded_inputs["attention_mask"] = attention_mask
+
+ if answer_coordinates is not None and answer_text is not None:
+ labels = self.get_answer_ids(column_ids, row_ids, table_data, answer_text, answer_coordinates)
+ numeric_values = self._get_numeric_values(raw_table, column_ids, row_ids)
+ numeric_values_scale = self._get_numeric_values_scale(raw_table, column_ids, row_ids)
+
+ encoded_inputs["labels"] = labels
+ encoded_inputs["numeric_values"] = numeric_values
+ encoded_inputs["numeric_values_scale"] = numeric_values_scale
+
+ if return_token_type_ids:
+ token_type_ids = [
+ segment_ids,
+ column_ids,
+ row_ids,
+ prev_labels,
+ column_ranks,
+ inv_column_ranks,
+ numeric_relations,
+ ]
+
+ token_type_ids = [list(ids) for ids in list(zip(*token_type_ids))]
+ encoded_inputs["token_type_ids"] = token_type_ids
+
+ if return_special_tokens_mask:
+ if add_special_tokens:
+ encoded_inputs["special_tokens_mask"] = self.get_special_tokens_mask(query_ids, table_ids)
+ else:
+ encoded_inputs["special_tokens_mask"] = [0] * len(input_ids)
+
+ # Check lengths
+ if max_length is None and len(encoded_inputs["input_ids"]) > self.model_max_length and verbose:
+ if not self.deprecation_warnings.get("sequence-length-is-longer-than-the-specified-maximum", False):
+ logger.warning(
+ "Token indices sequence length is longer than the specified maximum sequence length "
+ f"for this model ({len(encoded_inputs['input_ids'])} > {self.model_max_length}). Running this "
+ "sequence through the model will result in indexing errors."
+ )
+ self.deprecation_warnings["sequence-length-is-longer-than-the-specified-maximum"] = True
+
+ # Padding
+ if padding != PaddingStrategy.DO_NOT_PAD or return_attention_mask:
+ encoded_inputs = self.pad(
+ encoded_inputs,
+ max_length=max_length,
+ padding=padding.value,
+ pad_to_multiple_of=pad_to_multiple_of,
+ padding_side=padding_side,
+ return_attention_mask=return_attention_mask,
+ )
+
+ if return_length:
+ encoded_inputs["length"] = len(encoded_inputs["input_ids"])
+
+ batch_outputs = BatchEncoding(
+ encoded_inputs, tensor_type=return_tensors, prepend_batch_axis=prepend_batch_axis
+ )
+
+ return batch_outputs
+
+ def _get_truncated_table_rows(
+ self,
+ query_tokens: list[str],
+ tokenized_table: TokenizedTable,
+ num_rows: int,
+ num_columns: int,
+ max_length: int,
+ truncation_strategy: str | TapasTruncationStrategy,
+ ) -> tuple[int, int]:
+ """
+ Truncates a sequence pair in-place following the strategy.
+
+ Args:
+ query_tokens (`list[str]`):
+ List of strings corresponding to the tokenized query.
+ tokenized_table (`TokenizedTable`):
+ Tokenized table
+ num_rows (`int`):
+ Total number of table rows
+ num_columns (`int`):
+ Total number of table columns
+ max_length (`int`):
+ Total maximum length.
+ truncation_strategy (`str` or [`TapasTruncationStrategy]`):
+ Truncation strategy to use. Seeing as this method should only be called when truncating, the only
+ available strategy is the `"drop_rows_to_fit"` strategy.
+
+ Returns:
+ `Tuple(int, int)`: tuple containing the number of rows after truncation, and the number of tokens available
+ for each table element.
+ """
+ if not isinstance(truncation_strategy, TapasTruncationStrategy):
+ truncation_strategy = TapasTruncationStrategy(truncation_strategy)
+
+ if max_length is None:
+ max_length = self.model_max_length
+
+ if truncation_strategy == TapasTruncationStrategy.DROP_ROWS_TO_FIT:
+ while True:
+ num_tokens = self._get_max_num_tokens(
+ query_tokens, tokenized_table, num_rows=num_rows, num_columns=num_columns, max_length=max_length
+ )
+
+ if num_tokens is not None:
+ # We could fit the table.
+ break
+
+ # Try to drop a row to fit the table.
+ num_rows -= 1
+
+ if num_rows < 1:
+ break
+ elif truncation_strategy != TapasTruncationStrategy.DO_NOT_TRUNCATE:
+ raise ValueError(f"Unknown truncation strategy {truncation_strategy}.")
+
+ return num_rows, num_tokens or 1
+
+ def _tokenize_table(
+ self,
+ table=None,
+ ):
+ """
+ Tokenizes column headers and cell texts of a table.
+
+ Args:
+ table (`pd.Dataframe`):
+ Table. Returns: `TokenizedTable`: TokenizedTable object.
+ """
+ tokenized_rows = []
+ tokenized_row = []
+ # tokenize column headers
+ for column in table:
+ if self.strip_column_names:
+ tokenized_row.append(self.tokenize(""))
+ else:
+ tokenized_row.append(self.tokenize(column))
+ tokenized_rows.append(tokenized_row)
+
+ # tokenize cell values
+ for idx, row in table.iterrows():
+ tokenized_row = []
+ for cell in row:
+ tokenized_row.append(self.tokenize(cell))
+ tokenized_rows.append(tokenized_row)
+
+ token_coordinates = []
+ for row_index, row in enumerate(tokenized_rows):
+ for column_index, cell in enumerate(row):
+ for token_index, _ in enumerate(cell):
+ token_coordinates.append(
+ TokenCoordinates(
+ row_index=row_index,
+ column_index=column_index,
+ token_index=token_index,
+ )
+ )
+
+ return TokenizedTable(
+ rows=tokenized_rows,
+ selected_tokens=token_coordinates,
+ )
+
+ def _question_encoding_cost(self, question_tokens):
+ # Two extra spots of SEP and CLS.
+ return len(question_tokens) + 2
+
+ def _get_token_budget(self, question_tokens, max_length=None):
+ """
+ Computes the number of tokens left for the table after tokenizing a question, taking into account the max
+ sequence length of the model.
+
+ Args:
+ question_tokens (`list[String]`):
+ List of question tokens. Returns: `int`: the number of tokens left for the table, given the model max
+ length.
+ """
+ return (max_length if max_length is not None else self.model_max_length) - self._question_encoding_cost(
+ question_tokens
+ )
+
+ def _get_table_values(self, table, num_columns, num_rows, num_tokens) -> Generator[TableValue, None, None]:
+ """Iterates over partial table and returns token, column and row indexes."""
+ for tc in table.selected_tokens:
+ # First row is header row.
+ if tc.row_index >= num_rows + 1:
+ continue
+ if tc.column_index >= num_columns:
+ continue
+ cell = table.rows[tc.row_index][tc.column_index]
+ token = cell[tc.token_index]
+ word_begin_index = tc.token_index
+ # Don't add partial words. Find the starting word piece and check if it
+ # fits in the token budget.
+ while word_begin_index >= 0 and _is_inner_wordpiece(cell[word_begin_index]):
+ word_begin_index -= 1
+ if word_begin_index >= num_tokens:
+ continue
+ yield TableValue(token, tc.column_index + 1, tc.row_index)
+
+ def _get_table_boundaries(self, table):
+ """Return maximal number of rows, columns and tokens."""
+ max_num_tokens = 0
+ max_num_columns = 0
+ max_num_rows = 0
+ for tc in table.selected_tokens:
+ max_num_columns = max(max_num_columns, tc.column_index + 1)
+ max_num_rows = max(max_num_rows, tc.row_index + 1)
+ max_num_tokens = max(max_num_tokens, tc.token_index + 1)
+ max_num_columns = min(self.max_column_id, max_num_columns)
+ max_num_rows = min(self.max_row_id, max_num_rows)
+ return max_num_rows, max_num_columns, max_num_tokens
+
+ def _get_table_cost(self, table, num_columns, num_rows, num_tokens):
+ return sum(1 for _ in self._get_table_values(table, num_columns, num_rows, num_tokens))
+
+ def _get_max_num_tokens(self, question_tokens, tokenized_table, num_columns, num_rows, max_length):
+ """Computes max number of tokens that can be squeezed into the budget."""
+ token_budget = self._get_token_budget(question_tokens, max_length)
+ _, _, max_num_tokens = self._get_table_boundaries(tokenized_table)
+ if self.cell_trim_length >= 0 and max_num_tokens > self.cell_trim_length:
+ max_num_tokens = self.cell_trim_length
+ num_tokens = 0
+ for num_tokens in range(max_num_tokens + 1):
+ cost = self._get_table_cost(tokenized_table, num_columns, num_rows, num_tokens + 1)
+ if cost > token_budget:
+ break
+ if num_tokens < max_num_tokens:
+ if self.cell_trim_length >= 0:
+ # We don't allow dynamic trimming if a cell_trim_length is set.
+ return None
+ if num_tokens == 0:
+ return None
+ return num_tokens
+
+ def _get_num_columns(self, table):
+ num_columns = table.shape[1]
+ if num_columns >= self.max_column_id:
+ raise ValueError("Too many columns")
+ return num_columns
+
+ def _get_num_rows(self, table, drop_rows_to_fit):
+ num_rows = table.shape[0]
+ if num_rows >= self.max_row_id:
+ if drop_rows_to_fit:
+ num_rows = self.max_row_id - 1
+ else:
+ raise ValueError("Too many rows")
+ return num_rows
+
+ def _serialize_text(self, question_tokens):
+ """Serializes texts in index arrays."""
+ tokens = []
+ segment_ids = []
+ column_ids = []
+ row_ids = []
+
+ # add [CLS] token at the beginning
+ tokens.append(self.cls_token)
+ segment_ids.append(0)
+ column_ids.append(0)
+ row_ids.append(0)
+
+ for token in question_tokens:
+ tokens.append(token)
+ segment_ids.append(0)
+ column_ids.append(0)
+ row_ids.append(0)
+
+ return tokens, segment_ids, column_ids, row_ids
+
+ def _serialize(
+ self,
+ question_tokens,
+ table,
+ num_columns,
+ num_rows,
+ num_tokens,
+ ):
+ """Serializes table and text."""
+ tokens, segment_ids, column_ids, row_ids = self._serialize_text(question_tokens)
+
+ # add [SEP] token between question and table tokens
+ tokens.append(self.sep_token)
+ segment_ids.append(0)
+ column_ids.append(0)
+ row_ids.append(0)
+
+ for token, column_id, row_id in self._get_table_values(table, num_columns, num_rows, num_tokens):
+ tokens.append(token)
+ segment_ids.append(1)
+ column_ids.append(column_id)
+ row_ids.append(row_id)
+
+ return SerializedExample(
+ tokens=tokens,
+ segment_ids=segment_ids,
+ column_ids=column_ids,
+ row_ids=row_ids,
+ )
+
+ def _get_column_values(self, table, col_index):
+ table_numeric_values = {}
+ for row_index, row in table.iterrows():
+ cell = row[col_index]
+ if cell.numeric_value is not None:
+ table_numeric_values[row_index] = cell.numeric_value
+ return table_numeric_values
+
+ def _get_cell_token_indexes(self, column_ids, row_ids, column_id, row_id):
+ for index in range(len(column_ids)):
+ if column_ids[index] - 1 == column_id and row_ids[index] - 1 == row_id:
+ yield index
+
+ def _get_numeric_column_ranks(self, column_ids, row_ids, table):
+ """Returns column ranks for all numeric columns."""
+
+ ranks = [0] * len(column_ids)
+ inv_ranks = [0] * len(column_ids)
+
+ # original code from tf_example_utils.py of the original implementation
+ if table is not None:
+ for col_index in range(len(table.columns)):
+ table_numeric_values = self._get_column_values(table, col_index)
+
+ if not table_numeric_values:
+ continue
+
+ try:
+ key_fn = get_numeric_sort_key_fn(table_numeric_values.values())
+ except ValueError:
+ continue
+
+ table_numeric_values = {row_index: key_fn(value) for row_index, value in table_numeric_values.items()}
+
+ table_numeric_values_inv = collections.defaultdict(list)
+ for row_index, value in table_numeric_values.items():
+ table_numeric_values_inv[value].append(row_index)
+
+ unique_values = sorted(table_numeric_values_inv.keys())
+
+ for rank, value in enumerate(unique_values):
+ for row_index in table_numeric_values_inv[value]:
+ for index in self._get_cell_token_indexes(column_ids, row_ids, col_index, row_index):
+ ranks[index] = rank + 1
+ inv_ranks[index] = len(unique_values) - rank
+
+ return ranks, inv_ranks
+
+ def _get_numeric_sort_key_fn(self, table_numeric_values, value):
+ """
+ Returns the sort key function for comparing value to table values. The function returned will be a suitable
+ input for the key param of the sort(). See number_annotation_utils._get_numeric_sort_key_fn for details
+
+ Args:
+ table_numeric_values: Numeric values of a column
+ value: Numeric value in the question
+
+ Returns:
+ A function key function to compare column and question values.
+ """
+ if not table_numeric_values:
+ return None
+ all_values = list(table_numeric_values.values())
+ all_values.append(value)
+ try:
+ return get_numeric_sort_key_fn(all_values)
+ except ValueError:
+ return None
+
+ def _get_numeric_relations(self, question, column_ids, row_ids, table):
+ """
+ Returns numeric relations embeddings
+
+ Args:
+ question: Question object.
+ column_ids: Maps word piece position to column id.
+ row_ids: Maps word piece position to row id.
+ table: The table containing the numeric cell values.
+ """
+
+ numeric_relations = [0] * len(column_ids)
+
+ # first, we add any numeric value spans to the question:
+ # Create a dictionary that maps a table cell to the set of all relations
+ # this cell has with any value in the question.
+ cell_indices_to_relations = collections.defaultdict(set)
+ if question is not None and table is not None:
+ for numeric_value_span in question.numeric_spans:
+ for value in numeric_value_span.values:
+ for column_index in range(len(table.columns)):
+ table_numeric_values = self._get_column_values(table, column_index)
+ sort_key_fn = self._get_numeric_sort_key_fn(table_numeric_values, value)
+ if sort_key_fn is None:
+ continue
+ for row_index, cell_value in table_numeric_values.items():
+ relation = get_numeric_relation(value, cell_value, sort_key_fn)
+ if relation is not None:
+ cell_indices_to_relations[column_index, row_index].add(relation)
+
+ # For each cell add a special feature for all its word pieces.
+ for (column_index, row_index), relations in cell_indices_to_relations.items():
+ relation_set_index = 0
+ for relation in relations:
+ assert relation.value >= Relation.EQ.value
+ relation_set_index += 2 ** (relation.value - Relation.EQ.value)
+ for cell_token_index in self._get_cell_token_indexes(column_ids, row_ids, column_index, row_index):
+ numeric_relations[cell_token_index] = relation_set_index
+
+ return numeric_relations
+
+ def _get_numeric_values(self, table, column_ids, row_ids):
+ """Returns numeric values for computation of answer loss."""
+
+ numeric_values = [float("nan")] * len(column_ids)
+
+ if table is not None:
+ num_rows = table.shape[0]
+ num_columns = table.shape[1]
+
+ for col_index in range(num_columns):
+ for row_index in range(num_rows):
+ numeric_value = table.iloc[row_index, col_index].numeric_value
+ if numeric_value is not None:
+ if numeric_value.float_value is None:
+ continue
+ float_value = numeric_value.float_value
+ if float_value == float("inf"):
+ continue
+ for index in self._get_cell_token_indexes(column_ids, row_ids, col_index, row_index):
+ numeric_values[index] = float_value
+
+ return numeric_values
+
+ def _get_numeric_values_scale(self, table, column_ids, row_ids):
+ """Returns a scale to each token to down weigh the value of long words."""
+
+ numeric_values_scale = [1.0] * len(column_ids)
+
+ if table is None:
+ return numeric_values_scale
+
+ num_rows = table.shape[0]
+ num_columns = table.shape[1]
+
+ for col_index in range(num_columns):
+ for row_index in range(num_rows):
+ indices = list(self._get_cell_token_indexes(column_ids, row_ids, col_index, row_index))
+ num_indices = len(indices)
+ if num_indices > 1:
+ for index in indices:
+ numeric_values_scale[index] = float(num_indices)
+
+ return numeric_values_scale
+
+ def _pad_to_seq_length(self, inputs):
+ while len(inputs) > self.model_max_length:
+ inputs.pop()
+ while len(inputs) < self.model_max_length:
+ inputs.append(0)
+
+ def _get_all_answer_ids_from_coordinates(
+ self,
+ column_ids,
+ row_ids,
+ answers_list,
+ ):
+ """Maps lists of answer coordinates to token indexes."""
+ answer_ids = [0] * len(column_ids)
+ found_answers = set()
+ all_answers = set()
+ for answers in answers_list:
+ column_index, row_index = answers
+ all_answers.add((column_index, row_index))
+ for index in self._get_cell_token_indexes(column_ids, row_ids, column_index, row_index):
+ found_answers.add((column_index, row_index))
+ answer_ids[index] = 1
+
+ missing_count = len(all_answers) - len(found_answers)
+ return answer_ids, missing_count
+
+ def _get_all_answer_ids(self, column_ids, row_ids, answer_coordinates):
+ """
+ Maps answer coordinates of a question to token indexes.
+
+ In the SQA format (TSV), the coordinates are given as (row, column) tuples. Here, we first swap them to
+ (column, row) format before calling _get_all_answer_ids_from_coordinates.
+ """
+
+ def _to_coordinates(answer_coordinates_question):
+ return [(coords[1], coords[0]) for coords in answer_coordinates_question]
+
+ return self._get_all_answer_ids_from_coordinates(
+ column_ids, row_ids, answers_list=(_to_coordinates(answer_coordinates))
+ )
+
+ def _find_tokens(self, text, segment):
+ """Return start index of segment in text or None."""
+ logging.info(f"text: {text} {segment}")
+ for index in range(1 + len(text) - len(segment)):
+ for seg_index, seg_token in enumerate(segment):
+ if text[index + seg_index].piece != seg_token.piece:
+ break
+ else:
+ return index
+ return None
+
+ def _find_answer_coordinates_from_answer_text(
+ self,
+ tokenized_table,
+ answer_text,
+ ):
+ """Returns all occurrences of answer_text in the table."""
+ logging.info(f"answer text: {answer_text}")
+ for row_index, row in enumerate(tokenized_table.rows):
+ if row_index == 0:
+ # We don't search for answers in the header.
+ continue
+ for col_index, cell in enumerate(row):
+ token_index = self._find_tokens(cell, answer_text)
+ if token_index is not None:
+ yield TokenCoordinates(
+ row_index=row_index,
+ column_index=col_index,
+ token_index=token_index,
+ )
+
+ def _find_answer_ids_from_answer_texts(
+ self,
+ column_ids,
+ row_ids,
+ tokenized_table,
+ answer_texts,
+ ):
+ """Maps question with answer texts to the first matching token indexes."""
+ answer_ids = [0] * len(column_ids)
+ for answer_text in answer_texts:
+ for coordinates in self._find_answer_coordinates_from_answer_text(
+ tokenized_table,
+ answer_text,
+ ):
+ # Maps answer coordinates to indexes this can fail if tokens / rows have
+ # been pruned.
+ indexes = list(
+ self._get_cell_token_indexes(
+ column_ids,
+ row_ids,
+ column_id=coordinates.column_index,
+ row_id=coordinates.row_index - 1,
+ )
+ )
+ indexes.sort()
+ coordinate_answer_ids = []
+ if indexes:
+ begin_index = coordinates.token_index + indexes[0]
+ end_index = begin_index + len(answer_text)
+ for index in indexes:
+ if index >= begin_index and index < end_index:
+ coordinate_answer_ids.append(index)
+ if len(coordinate_answer_ids) == len(answer_text):
+ for index in coordinate_answer_ids:
+ answer_ids[index] = 1
+ break
+ return answer_ids
+
+ def _get_answer_ids(self, column_ids, row_ids, answer_coordinates):
+ """Maps answer coordinates of a question to token indexes."""
+ answer_ids, missing_count = self._get_all_answer_ids(column_ids, row_ids, answer_coordinates)
+
+ if missing_count:
+ raise ValueError("Couldn't find all answers")
+ return answer_ids
+
+ def get_answer_ids(self, column_ids, row_ids, tokenized_table, answer_texts_question, answer_coordinates_question):
+ if self.update_answer_coordinates:
+ return self._find_answer_ids_from_answer_texts(
+ column_ids,
+ row_ids,
+ tokenized_table,
+ answer_texts=[self.tokenize(at) for at in answer_texts_question],
+ )
+ return self._get_answer_ids(column_ids, row_ids, answer_coordinates_question)
+
+ def _pad(
+ self,
+ encoded_inputs: dict[str, EncodedInput] | BatchEncoding,
+ max_length: int | None = None,
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
+ pad_to_multiple_of: int | None = None,
+ padding_side: str | None = None,
+ return_attention_mask: bool | None = None,
+ ) -> dict:
+ """
+ Pad encoded inputs (on left/right and up to predefined length or max length in the batch)
+
+ Args:
+ encoded_inputs:
+ Dictionary of tokenized inputs (`list[int]`) or batch of tokenized inputs (`list[list[int]]`).
+ max_length: maximum length of the returned list and optionally padding length (see below).
+ Will truncate by taking into account the special tokens.
+ padding_strategy: PaddingStrategy to use for padding.
+
+ - PaddingStrategy.LONGEST Pad to the longest sequence in the batch
+ - PaddingStrategy.MAX_LENGTH: Pad to the max length (default)
+ - PaddingStrategy.DO_NOT_PAD: Do not pad
+ The tokenizer padding sides are defined in self.padding_side:
+
+ - 'left': pads on the left of the sequences
+ - 'right': pads on the right of the sequences
+ pad_to_multiple_of: (optional) Integer if set will pad the sequence to a multiple of the provided value.
+ This is especially useful to enable the use of Tensor Core on NVIDIA hardware with compute capability
+ `>= 7.5` (Volta).
+ padding_side:
+ The side on which the model should have padding applied. Should be selected between ['right', 'left'].
+ Default value is picked from the class attribute of the same name.
+ return_attention_mask:
+ (optional) Set to False to avoid returning attention mask (default: set to model specifics)
+ """
+ # Load from model defaults
+ if return_attention_mask is None:
+ return_attention_mask = "attention_mask" in self.model_input_names
+
+ if padding_strategy == PaddingStrategy.LONGEST:
+ max_length = len(encoded_inputs["input_ids"])
+
+ if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
+ max_length = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of
+
+ needs_to_be_padded = (
+ padding_strategy != PaddingStrategy.DO_NOT_PAD and len(encoded_inputs["input_ids"]) != max_length
+ )
+
+ # Initialize attention mask if not present.
+ if return_attention_mask and "attention_mask" not in encoded_inputs:
+ encoded_inputs["attention_mask"] = [1] * len(encoded_inputs["input_ids"])
+
+ if needs_to_be_padded:
+ difference = max_length - len(encoded_inputs["input_ids"])
+ padding_side = padding_side if padding_side is not None else self.padding_side
+ if padding_side == "right":
+ if return_attention_mask:
+ encoded_inputs["attention_mask"] = encoded_inputs["attention_mask"] + [0] * difference
+ if "token_type_ids" in encoded_inputs:
+ encoded_inputs["token_type_ids"] = (
+ encoded_inputs["token_type_ids"] + [[self.pad_token_type_id] * 7] * difference
+ )
+ if "labels" in encoded_inputs:
+ encoded_inputs["labels"] = encoded_inputs["labels"] + [0] * difference
+ if "numeric_values" in encoded_inputs:
+ encoded_inputs["numeric_values"] = encoded_inputs["numeric_values"] + [float("nan")] * difference
+ if "numeric_values_scale" in encoded_inputs:
+ encoded_inputs["numeric_values_scale"] = (
+ encoded_inputs["numeric_values_scale"] + [1.0] * difference
+ )
+ if "special_tokens_mask" in encoded_inputs:
+ encoded_inputs["special_tokens_mask"] = encoded_inputs["special_tokens_mask"] + [1] * difference
+ encoded_inputs["input_ids"] = encoded_inputs["input_ids"] + [self.pad_token_id] * difference
+ elif padding_side == "left":
+ if return_attention_mask:
+ encoded_inputs["attention_mask"] = [0] * difference + encoded_inputs["attention_mask"]
+ if "token_type_ids" in encoded_inputs:
+ encoded_inputs["token_type_ids"] = [[self.pad_token_type_id] * 7] * difference + encoded_inputs[
+ "token_type_ids"
+ ]
+ if "labels" in encoded_inputs:
+ encoded_inputs["labels"] = [0] * difference + encoded_inputs["labels"]
+ if "numeric_values" in encoded_inputs:
+ encoded_inputs["numeric_values"] = [float("nan")] * difference + encoded_inputs["numeric_values"]
+ if "numeric_values_scale" in encoded_inputs:
+ encoded_inputs["numeric_values_scale"] = [1.0] * difference + encoded_inputs[
+ "numeric_values_scale"
+ ]
+ if "special_tokens_mask" in encoded_inputs:
+ encoded_inputs["special_tokens_mask"] = [1] * difference + encoded_inputs["special_tokens_mask"]
+ encoded_inputs["input_ids"] = [self.pad_token_id] * difference + encoded_inputs["input_ids"]
+ else:
+ raise ValueError("Invalid padding strategy:" + str(padding_side))
+
+ return encoded_inputs
+
+ # Everything related to converting logits to predictions
+
+ def _get_cell_token_probs(self, probabilities, segment_ids, row_ids, column_ids):
+ for i, p in enumerate(probabilities):
+ segment_id = segment_ids[i]
+ col = column_ids[i] - 1
+ row = row_ids[i] - 1
+ if col >= 0 and row >= 0 and segment_id == 1:
+ yield i, p
+
+ def _get_mean_cell_probs(self, probabilities, segment_ids, row_ids, column_ids):
+ """Computes average probability per cell, aggregating over tokens."""
+ coords_to_probs = collections.defaultdict(list)
+ for i, prob in self._get_cell_token_probs(probabilities, segment_ids, row_ids, column_ids):
+ col = column_ids[i] - 1
+ row = row_ids[i] - 1
+ coords_to_probs[(col, row)].append(prob)
+ return {coords: np.array(cell_probs).mean() for coords, cell_probs in coords_to_probs.items()}
+
+ def convert_logits_to_predictions(self, data, logits, logits_agg=None, cell_classification_threshold=0.5):
+ """
+ Converts logits of [`TapasForQuestionAnswering`] to actual predicted answer coordinates and optional
+ aggregation indices.
+
+ The original implementation, on which this function is based, can be found
+ [here](https://github.com/google-research/tapas/blob/4908213eb4df7aa988573350278b44c4dbe3f71b/tapas/experiments/prediction_utils.py#L288).
+
+ Args:
+ data (`dict`):
+ Dictionary mapping features to actual values. Should be created using [`TapasTokenizer`].
+ logits (`torch.Tensor` of shape `(batch_size, sequence_length)`):
+ Tensor containing the logits at the token level.
+ logits_agg (`torch.Tensor` of shape `(batch_size, num_aggregation_labels)`, *optional*):
+ Tensor containing the aggregation logits.
+ cell_classification_threshold (`float`, *optional*, defaults to 0.5):
+ Threshold to be used for cell selection. All table cells for which their probability is larger than
+ this threshold will be selected.
+
+ Returns:
+ `tuple` comprising various elements depending on the inputs:
+
+ - predicted_answer_coordinates (`list[list[[tuple]]` of length `batch_size`): Predicted answer coordinates
+ as a list of lists of tuples. Each element in the list contains the predicted answer coordinates of a
+ single example in the batch, as a list of tuples. Each tuple is a cell, i.e. (row index, column index).
+ - predicted_aggregation_indices (`list[int]`of length `batch_size`, *optional*, returned when
+ `logits_aggregation` is provided): Predicted aggregation operator indices of the aggregation head.
+ """
+ logits = logits.numpy()
+ if logits_agg is not None:
+ logits_agg = logits_agg.numpy()
+ data = {key: value.numpy() for key, value in data.items() if key != "training"}
+ # input data is of type float32
+ # np.log(np.finfo(np.float32).max) = 88.72284
+ # Any value over 88.72284 will overflow when passed through the exponential, sending a warning
+ # We disable this warning by truncating the logits.
+ logits[logits < -88.7] = -88.7
+
+ # Compute probabilities from token logits
+ probabilities = 1 / (1 + np.exp(-logits)) * data["attention_mask"]
+ token_types = [
+ "segment_ids",
+ "column_ids",
+ "row_ids",
+ "prev_labels",
+ "column_ranks",
+ "inv_column_ranks",
+ "numeric_relations",
+ ]
+
+ # collect input_ids, segment ids, row ids and column ids of batch. Shape (batch_size, seq_len)
+ input_ids = data["input_ids"]
+ segment_ids = data["token_type_ids"][:, :, token_types.index("segment_ids")]
+ row_ids = data["token_type_ids"][:, :, token_types.index("row_ids")]
+ column_ids = data["token_type_ids"][:, :, token_types.index("column_ids")]
+
+ # next, get answer coordinates for every example in the batch
+ num_batch = input_ids.shape[0]
+ predicted_answer_coordinates = []
+ for i in range(num_batch):
+ probabilities_example = probabilities[i].tolist()
+ segment_ids_example = segment_ids[i]
+ row_ids_example = row_ids[i]
+ column_ids_example = column_ids[i]
+
+ max_width = column_ids_example.max()
+ max_height = row_ids_example.max()
+
+ if max_width == 0 and max_height == 0:
+ continue
+
+ cell_coords_to_prob = self._get_mean_cell_probs(
+ probabilities_example,
+ segment_ids_example.tolist(),
+ row_ids_example.tolist(),
+ column_ids_example.tolist(),
+ )
+
+ # Select the answers above the classification threshold.
+ answer_coordinates = []
+ for col in range(max_width):
+ for row in range(max_height):
+ cell_prob = cell_coords_to_prob.get((col, row), None)
+ if cell_prob is not None:
+ if cell_prob > cell_classification_threshold:
+ answer_coordinates.append((row, col))
+ answer_coordinates = sorted(answer_coordinates)
+ predicted_answer_coordinates.append(answer_coordinates)
+
+ output = (predicted_answer_coordinates,)
+
+ if logits_agg is not None:
+ predicted_aggregation_indices = logits_agg.argmax(axis=-1)
+ output = (predicted_answer_coordinates, predicted_aggregation_indices.tolist())
+
+ return output
+
+ # End of everything related to converting logits to predictions
+
+
+class BasicTokenizer:
+ """
+ Constructs a BasicTokenizer that will run basic tokenization (punctuation splitting, lower casing, etc.).
+
+ Args:
+ do_lower_case (`bool`, *optional*, defaults to `True`):
+ Whether or not to lowercase the input when tokenizing.
+ never_split (`Iterable`, *optional*):
+ Collection of tokens which will never be split during tokenization. Only has an effect when
+ `do_basic_tokenize=True`
+ tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
+ Whether or not to tokenize Chinese characters.
+
+ This should likely be deactivated for Japanese (see this
+ [issue](https://github.com/huggingface/transformers/issues/328)).
+ strip_accents (`bool`, *optional*):
+ Whether or not to strip all accents. If this option is not specified, then it will be determined by the
+ value for `lowercase` (as in the original BERT).
+ do_split_on_punc (`bool`, *optional*, defaults to `True`):
+ In some instances we want to skip the basic punctuation splitting so that later tokenization can capture
+ the full context of the words, such as contractions.
+ """
+
+ def __init__(
+ self,
+ do_lower_case=True,
+ never_split=None,
+ tokenize_chinese_chars=True,
+ strip_accents=None,
+ do_split_on_punc=True,
+ ):
+ if never_split is None:
+ never_split = []
+ self.do_lower_case = do_lower_case
+ self.never_split = set(never_split)
+ self.tokenize_chinese_chars = tokenize_chinese_chars
+ self.strip_accents = strip_accents
+ self.do_split_on_punc = do_split_on_punc
+
+ def tokenize(self, text, never_split=None):
+ """
+ Basic Tokenization of a piece of text. For sub-word tokenization, see WordPieceTokenizer.
+
+ Args:
+ never_split (`List[str]`, *optional*)
+ Kept for backward compatibility purposes. Now implemented directly at the base class level (see
+ [`PreTrainedTokenizer.tokenize`]) List of token not to split.
+ """
+ # union() returns a new set by concatenating the two sets.
+ never_split = self.never_split.union(set(never_split)) if never_split else self.never_split
+ text = self._clean_text(text)
+
+ # This was added on November 1st, 2018 for the multilingual and Chinese
+ # models. This is also applied to the English models now, but it doesn't
+ # matter since the English models were not trained on any Chinese data
+ # and generally don't have any Chinese data in them (there are Chinese
+ # characters in the vocabulary because Wikipedia does have some Chinese
+ # words in the English Wikipedia.).
+ if self.tokenize_chinese_chars:
+ text = self._tokenize_chinese_chars(text)
+ # prevents treating the same character with different unicode codepoints as different characters
+ unicode_normalized_text = unicodedata.normalize("NFC", text)
+ orig_tokens = whitespace_tokenize(unicode_normalized_text)
+ split_tokens = []
+ for token in orig_tokens:
+ if token not in never_split:
+ if self.do_lower_case:
+ token = token.lower()
+ if self.strip_accents is not False:
+ token = self._run_strip_accents(token)
+ elif self.strip_accents:
+ token = self._run_strip_accents(token)
+ split_tokens.extend(self._run_split_on_punc(token, never_split))
+
+ output_tokens = whitespace_tokenize(" ".join(split_tokens))
+ return output_tokens
+
+ def _run_strip_accents(self, text):
+ """Strips accents from a piece of text."""
+ text = unicodedata.normalize("NFD", text)
+ output = []
+ for char in text:
+ cat = unicodedata.category(char)
+ if cat == "Mn":
+ continue
+ output.append(char)
+ return "".join(output)
+
+ def _run_split_on_punc(self, text, never_split=None):
+ """Splits punctuation on a piece of text."""
+ if not self.do_split_on_punc or (never_split is not None and text in never_split):
+ return [text]
+ chars = list(text)
+ i = 0
+ start_new_word = True
+ output = []
+ while i < len(chars):
+ char = chars[i]
+ if _is_punctuation(char):
+ output.append([char])
+ start_new_word = True
+ else:
+ if start_new_word:
+ output.append([])
+ start_new_word = False
+ output[-1].append(char)
+ i += 1
+
+ return ["".join(x) for x in output]
+
+ def _tokenize_chinese_chars(self, text):
+ """Adds whitespace around any CJK character."""
+ output = []
+ for char in text:
+ cp = ord(char)
+ if self._is_chinese_char(cp):
+ output.append(" ")
+ output.append(char)
+ output.append(" ")
+ else:
+ output.append(char)
+ return "".join(output)
+
+ def _is_chinese_char(self, cp):
+ """Checks whether CP is the codepoint of a CJK character."""
+ # This defines a "chinese character" as anything in the CJK Unicode block:
+ # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
+ #
+ # Note that the CJK Unicode block is NOT all Japanese and Korean characters,
+ # despite its name. The modern Korean Hangul alphabet is a different block,
+ # as is Japanese Hiragana and Katakana. Those alphabets are used to write
+ # space-separated words, so they are not treated specially and handled
+ # like the all of the other languages.
+ if (
+ (cp >= 0x4E00 and cp <= 0x9FFF)
+ or (cp >= 0x3400 and cp <= 0x4DBF)
+ or (cp >= 0x20000 and cp <= 0x2A6DF)
+ or (cp >= 0x2A700 and cp <= 0x2B73F)
+ or (cp >= 0x2B740 and cp <= 0x2B81F)
+ or (cp >= 0x2B820 and cp <= 0x2CEAF)
+ or (cp >= 0xF900 and cp <= 0xFAFF)
+ or (cp >= 0x2F800 and cp <= 0x2FA1F)
+ ):
+ return True
+
+ return False
+
+ def _clean_text(self, text):
+ """Performs invalid character removal and whitespace cleanup on text."""
+ output = []
+ for char in text:
+ cp = ord(char)
+ if cp == 0 or cp == 0xFFFD or _is_control(char):
+ continue
+ if _is_whitespace(char):
+ output.append(" ")
+ else:
+ output.append(char)
+ return "".join(output)
+
+
+class WordpieceTokenizer:
+ """Runs WordPiece tokenization."""
+
+ def __init__(self, vocab, unk_token, max_input_chars_per_word=100):
+ self.vocab = vocab
+ self.unk_token = unk_token
+ self.max_input_chars_per_word = max_input_chars_per_word
+
+ def tokenize(self, text):
+ """
+ Tokenizes a piece of text into its word pieces. This uses a greedy longest-match-first algorithm to perform
+ tokenization using the given vocabulary.
+
+ For example, `input = "unaffable"` will return as output `["un", "##aff", "##able"]`.
+
+ Args:
+ text: A single token or whitespace separated tokens. This should have
+ already been passed through *BasicTokenizer*.
+
+ Returns:
+ A list of wordpiece tokens.
+ """
+
+ output_tokens = []
+ for token in whitespace_tokenize(text):
+ chars = list(token)
+ if len(chars) > self.max_input_chars_per_word:
+ output_tokens.append(self.unk_token)
+ continue
+
+ is_bad = False
+ start = 0
+ sub_tokens = []
+ while start < len(chars):
+ end = len(chars)
+ cur_substr = None
+ while start < end:
+ substr = "".join(chars[start:end])
+ if start > 0:
+ substr = "##" + substr
+ if substr in self.vocab:
+ cur_substr = substr
+ break
+ end -= 1
+ if cur_substr is None:
+ is_bad = True
+ break
+ sub_tokens.append(cur_substr)
+ start = end
+
+ if is_bad:
+ output_tokens.append(self.unk_token)
+ else:
+ output_tokens.extend(sub_tokens)
+ return output_tokens
+
+
+# Below: utilities for TAPAS tokenizer
+# This includes functions to parse numeric values (dates and numbers) from both the table and questions in order
+# to create the column_ranks, inv_column_ranks, numeric_values, numeric values_scale and numeric_relations in
+# prepare_for_model of TapasTokenizer.
+# These are meant to be used in an academic setup, for production use cases Gold mine or Aqua should be used.
+
+
+# taken from constants.py of the original implementation
+# URL: https://github.com/google-research/tapas/blob/master/tapas/utils/constants.py
+class Relation(enum.Enum):
+ HEADER_TO_CELL = 1 # Connects header to cell.
+ CELL_TO_HEADER = 2 # Connects cell to header.
+ QUERY_TO_HEADER = 3 # Connects query to headers.
+ QUERY_TO_CELL = 4 # Connects query to cells.
+ ROW_TO_CELL = 5 # Connects row to cells.
+ CELL_TO_ROW = 6 # Connects cells to row.
+ EQ = 7 # Annotation value is same as cell value
+ LT = 8 # Annotation value is less than cell value
+ GT = 9 # Annotation value is greater than cell value
+
+
+@dataclass
+class Date:
+ year: int | None = None
+ month: int | None = None
+ day: int | None = None
+
+
+@dataclass
+class NumericValue:
+ float_value: float | None = None
+ date: Date | None = None
+
+
+@dataclass
+class NumericValueSpan:
+ begin_index: int | None = None
+ end_index: int | None = None
+ values: list[NumericValue] = None
+
+
+@dataclass
+class Cell:
+ text: str
+ numeric_value: NumericValue | None = None
+
+
+@dataclass
+class Question:
+ original_text: str # The original raw question string.
+ text: str # The question string after normalization.
+ numeric_spans: list[NumericValueSpan] | None = None
+
+
+# Below: all functions from number_utils.py as well as 2 functions (namely get_all_spans and normalize_for_match)
+# from text_utils.py of the original implementation. URL's:
+# - https://github.com/google-research/tapas/blob/master/tapas/utils/number_utils.py
+# - https://github.com/google-research/tapas/blob/master/tapas/utils/text_utils.py
+
+
+# Constants for parsing date expressions.
+# Masks that specify (by a bool) which of (year, month, day) will be populated.
+_DateMask = collections.namedtuple("_DateMask", ["year", "month", "day"])
+
+_YEAR = _DateMask(True, False, False)
+_YEAR_MONTH = _DateMask(True, True, False)
+_YEAR_MONTH_DAY = _DateMask(True, True, True)
+_MONTH = _DateMask(False, True, False)
+_MONTH_DAY = _DateMask(False, True, True)
+
+# Pairs of patterns to pass to 'datetime.strptime' and masks specifying which
+# fields will be set by the corresponding pattern.
+_DATE_PATTERNS = (
+ ("%B", _MONTH),
+ ("%Y", _YEAR),
+ ("%Ys", _YEAR),
+ ("%b %Y", _YEAR_MONTH),
+ ("%B %Y", _YEAR_MONTH),
+ ("%B %d", _MONTH_DAY),
+ ("%b %d", _MONTH_DAY),
+ ("%d %b", _MONTH_DAY),
+ ("%d %B", _MONTH_DAY),
+ ("%B %d, %Y", _YEAR_MONTH_DAY),
+ ("%d %B %Y", _YEAR_MONTH_DAY),
+ ("%m-%d-%Y", _YEAR_MONTH_DAY),
+ ("%Y-%m-%d", _YEAR_MONTH_DAY),
+ ("%Y-%m", _YEAR_MONTH),
+ ("%B %Y", _YEAR_MONTH),
+ ("%d %b %Y", _YEAR_MONTH_DAY),
+ ("%Y-%m-%d", _YEAR_MONTH_DAY),
+ ("%b %d, %Y", _YEAR_MONTH_DAY),
+ ("%d.%m.%Y", _YEAR_MONTH_DAY),
+ ("%A, %b %d", _MONTH_DAY),
+ ("%A, %B %d", _MONTH_DAY),
+)
+
+# This mapping is used to convert date patterns to regex patterns.
+_FIELD_TO_REGEX = (
+ ("%A", r"\w+"), # Weekday as locale’s full name.
+ ("%B", r"\w+"), # Month as locale’s full name.
+ ("%Y", r"\d{4}"), # Year with century as a decimal number.
+ ("%b", r"\w{3}"), # Month as locale’s abbreviated name.
+ ("%d", r"\d{1,2}"), # Day of the month as a zero-padded decimal number.
+ ("%m", r"\d{1,2}"), # Month as a zero-padded decimal number.
+)
+
+
+def _process_date_pattern(dp):
+ """Compute a regex for each date pattern to use as a prefilter."""
+ pattern, mask = dp
+ regex = pattern
+ regex = regex.replace(".", re.escape("."))
+ regex = regex.replace("-", re.escape("-"))
+ regex = regex.replace(" ", r"\s+")
+ for field, field_regex in _FIELD_TO_REGEX:
+ regex = regex.replace(field, field_regex)
+ # Make sure we didn't miss any of the fields.
+ assert "%" not in regex, regex
+ return pattern, mask, re.compile("^" + regex + "$")
+
+
+def _process_date_patterns():
+ return tuple(_process_date_pattern(dp) for dp in _DATE_PATTERNS)
+
+
+_PROCESSED_DATE_PATTERNS = _process_date_patterns()
+
+_MAX_DATE_NGRAM_SIZE = 5
+
+# Following DynSp:
+# https://github.com/Microsoft/DynSP/blob/master/util.py#L414.
+_NUMBER_WORDS = [
+ "zero",
+ "one",
+ "two",
+ "three",
+ "four",
+ "five",
+ "six",
+ "seven",
+ "eight",
+ "nine",
+ "ten",
+ "eleven",
+ "twelve",
+]
+
+_ORDINAL_WORDS = [
+ "zeroth",
+ "first",
+ "second",
+ "third",
+ "fourth",
+ "fifth",
+ "sixth",
+ "seventh",
+ "eighth",
+ "ninth",
+ "tenth",
+ "eleventh",
+ "twelfth",
+]
+
+_ORDINAL_SUFFIXES = ["st", "nd", "rd", "th"]
+
+_NUMBER_PATTERN = re.compile(r"((^|\s)[+-])?((\.\d+)|(\d+(,\d\d\d)*(\.\d*)?))")
+
+# Following DynSp:
+# https://github.com/Microsoft/DynSP/blob/master/util.py#L293.
+_MIN_YEAR = 1700
+_MAX_YEAR = 2016
+
+_INF = float("INF")
+
+
+def _get_numeric_value_from_date(date, mask):
+ """Converts date (datetime Python object) to a NumericValue object with a Date object value."""
+ if date.year < _MIN_YEAR or date.year > _MAX_YEAR:
+ raise ValueError(f"Invalid year: {date.year}")
+
+ new_date = Date()
+ if mask.year:
+ new_date.year = date.year
+ if mask.month:
+ new_date.month = date.month
+ if mask.day:
+ new_date.day = date.day
+ return NumericValue(date=new_date)
+
+
+def _get_span_length_key(span):
+ """Sorts span by decreasing length first and increasing first index second."""
+ return span[1] - span[0], -span[0]
+
+
+def _get_numeric_value_from_float(value):
+ """Converts float (Python) to a NumericValue object with a float value."""
+ return NumericValue(float_value=value)
+
+
+# Doesn't parse ordinal expressions such as '18th of february 1655'.
+def _parse_date(text):
+ """Attempts to format a text as a standard date string (yyyy-mm-dd)."""
+ text = re.sub(r"Sept\b", "Sep", text)
+ for in_pattern, mask, regex in _PROCESSED_DATE_PATTERNS:
+ if not regex.match(text):
+ continue
+ try:
+ date = datetime.datetime.strptime(text, in_pattern).date()
+ except ValueError:
+ continue
+ try:
+ return _get_numeric_value_from_date(date, mask)
+ except ValueError:
+ continue
+ return None
+
+
+def _parse_number(text):
+ """Parses simple cardinal and ordinals numbers."""
+ for suffix in _ORDINAL_SUFFIXES:
+ if text.endswith(suffix):
+ text = text[: -len(suffix)]
+ break
+ text = text.replace(",", "")
+ try:
+ value = float(text)
+ except ValueError:
+ return None
+ if math.isnan(value):
+ return None
+ if value == _INF:
+ return None
+ return value
+
+
+def get_all_spans(text, max_ngram_length):
+ """
+ Split a text into all possible ngrams up to 'max_ngram_length'. Split points are white space and punctuation.
+
+ Args:
+ text: Text to split.
+ max_ngram_length: maximal ngram length.
+ Yields:
+ Spans, tuples of begin-end index.
+ """
+ start_indexes = []
+ for index, char in enumerate(text):
+ if not char.isalnum():
+ continue
+ if index == 0 or not text[index - 1].isalnum():
+ start_indexes.append(index)
+ if index + 1 == len(text) or not text[index + 1].isalnum():
+ for start_index in start_indexes[-max_ngram_length:]:
+ yield start_index, index + 1
+
+
+def normalize_for_match(text):
+ return " ".join(text.lower().split())
+
+
+def format_text(text):
+ """Lowercases and strips punctuation."""
+ text = text.lower().strip()
+ if text == "n/a" or text == "?" or text == "nan":
+ text = EMPTY_TEXT
+
+ text = re.sub(r"[^\w\d]+", " ", text).replace("_", " ")
+ text = " ".join(text.split())
+ text = text.strip()
+ if text:
+ return text
+ return EMPTY_TEXT
+
+
+def parse_text(text):
+ """
+ Extracts longest number and date spans.
+
+ Args:
+ text: text to annotate
+
+ Returns:
+ List of longest numeric value spans.
+ """
+ span_dict = collections.defaultdict(list)
+ for match in _NUMBER_PATTERN.finditer(text):
+ span_text = text[match.start() : match.end()]
+ number = _parse_number(span_text)
+ if number is not None:
+ span_dict[match.span()].append(_get_numeric_value_from_float(number))
+
+ for begin_index, end_index in get_all_spans(text, max_ngram_length=1):
+ if (begin_index, end_index) in span_dict:
+ continue
+ span_text = text[begin_index:end_index]
+
+ number = _parse_number(span_text)
+ if number is not None:
+ span_dict[begin_index, end_index].append(_get_numeric_value_from_float(number))
+ for number, word in enumerate(_NUMBER_WORDS):
+ if span_text == word:
+ span_dict[begin_index, end_index].append(_get_numeric_value_from_float(float(number)))
+ break
+ for number, word in enumerate(_ORDINAL_WORDS):
+ if span_text == word:
+ span_dict[begin_index, end_index].append(_get_numeric_value_from_float(float(number)))
+ break
+
+ for begin_index, end_index in get_all_spans(text, max_ngram_length=_MAX_DATE_NGRAM_SIZE):
+ span_text = text[begin_index:end_index]
+ date = _parse_date(span_text)
+ if date is not None:
+ span_dict[begin_index, end_index].append(date)
+
+ spans = sorted(span_dict.items(), key=lambda span_value: _get_span_length_key(span_value[0]), reverse=True)
+ selected_spans = []
+ for span, value in spans:
+ for selected_span, _ in selected_spans:
+ if selected_span[0] <= span[0] and span[1] <= selected_span[1]:
+ break
+ else:
+ selected_spans.append((span, value))
+
+ selected_spans.sort(key=lambda span_value: span_value[0][0])
+
+ numeric_value_spans = []
+ for span, values in selected_spans:
+ numeric_value_spans.append(NumericValueSpan(begin_index=span[0], end_index=span[1], values=values))
+ return numeric_value_spans
+
+
+# Below: all functions from number_annotation_utils.py and 2 functions (namely filter_invalid_unicode
+# and filter_invalid_unicode_from_table) from text_utils.py of the original implementation. URL's:
+# - https://github.com/google-research/tapas/blob/master/tapas/utils/number_annotation_utils.py
+# - https://github.com/google-research/tapas/blob/master/tapas/utils/text_utils.py
+
+
+_PrimitiveNumericValue = float | tuple[float | None]
+_SortKeyFn = Callable[[NumericValue], tuple[float, Ellipsis]]
+
+_DATE_TUPLE_SIZE = 3
+
+EMPTY_TEXT = "EMPTY"
+
+NUMBER_TYPE = "number"
+DATE_TYPE = "date"
+
+
+def _get_value_type(numeric_value):
+ if numeric_value.float_value is not None:
+ return NUMBER_TYPE
+ elif numeric_value.date is not None:
+ return DATE_TYPE
+ raise ValueError(f"Unknown type: {numeric_value}")
+
+
+def _get_value_as_primitive_value(numeric_value):
+ """Maps a NumericValue proto to a float or tuple of float."""
+ if numeric_value.float_value is not None:
+ return numeric_value.float_value
+ if numeric_value.date is not None:
+ date = numeric_value.date
+ value_tuple = [None, None, None]
+ # All dates fields are cased to float to produce a simple primitive value.
+ if date.year is not None:
+ value_tuple[0] = float(date.year)
+ if date.month is not None:
+ value_tuple[1] = float(date.month)
+ if date.day is not None:
+ value_tuple[2] = float(date.day)
+ return tuple(value_tuple)
+ raise ValueError(f"Unknown type: {numeric_value}")
+
+
+def _get_all_types(numeric_values):
+ return {_get_value_type(value) for value in numeric_values}
+
+
+def get_numeric_sort_key_fn(numeric_values):
+ """
+ Creates a function that can be used as a sort key or to compare the values. Maps to primitive types and finds the
+ biggest common subset. Consider the values "05/05/2010" and "August 2007". With the corresponding primitive values
+ (2010.,5.,5.) and (2007.,8., None). These values can be compared by year and date so we map to the sequence (2010.,
+ 5.), (2007., 8.). If we added a third value "2006" with primitive value (2006., None, None), we could only compare
+ by the year so we would map to (2010.,), (2007.,) and (2006.,).
+
+ Args:
+ numeric_values: Values to compare
+
+ Returns:
+ A function that can be used as a sort key function (mapping numeric values to a comparable tuple)
+
+ Raises:
+ ValueError if values don't have a common type or are not comparable.
+ """
+ value_types = _get_all_types(numeric_values)
+ if len(value_types) != 1:
+ raise ValueError(f"No common value type in {numeric_values}")
+
+ value_type = next(iter(value_types))
+ if value_type == NUMBER_TYPE:
+ # Primitive values are simple floats, nothing to do here.
+ return _get_value_as_primitive_value
+
+ # The type can only be Date at this point which means the primitive type
+ # is a float triple.
+ valid_indexes = set(range(_DATE_TUPLE_SIZE))
+
+ for numeric_value in numeric_values:
+ value = _get_value_as_primitive_value(numeric_value)
+ assert isinstance(value, tuple)
+ for tuple_index, inner_value in enumerate(value):
+ if inner_value is None:
+ valid_indexes.discard(tuple_index)
+
+ if not valid_indexes:
+ raise ValueError(f"No common value in {numeric_values}")
+
+ def _sort_key_fn(numeric_value):
+ value = _get_value_as_primitive_value(numeric_value)
+ return tuple(value[index] for index in valid_indexes)
+
+ return _sort_key_fn
+
+
+def _consolidate_numeric_values(row_index_to_values, min_consolidation_fraction, debug_info):
+ """
+ Finds the most common numeric values in a column and returns them
+
+ Args:
+ row_index_to_values:
+ For each row index all the values in that cell.
+ min_consolidation_fraction:
+ Fraction of cells that need to have consolidated value.
+ debug_info:
+ Additional information only used for logging
+
+ Returns:
+ For each row index the first value that matches the most common value. Rows that don't have a matching value
+ are dropped. Empty list if values can't be consolidated.
+ """
+ type_counts = collections.Counter()
+ for numeric_values in row_index_to_values.values():
+ type_counts.update(_get_all_types(numeric_values))
+ if not type_counts:
+ return {}
+ max_count = max(type_counts.values())
+ if max_count < len(row_index_to_values) * min_consolidation_fraction:
+ # logging.log_every_n(logging.INFO, f'Can\'t consolidate types: {debug_info} {row_index_to_values} {max_count}', 100)
+ return {}
+
+ valid_types = set()
+ for value_type, count in type_counts.items():
+ if count == max_count:
+ valid_types.add(value_type)
+ if len(valid_types) > 1:
+ assert DATE_TYPE in valid_types
+ max_type = DATE_TYPE
+ else:
+ max_type = next(iter(valid_types))
+
+ new_row_index_to_value = {}
+ for index, values in row_index_to_values.items():
+ # Extract the first matching value.
+ for value in values:
+ if _get_value_type(value) == max_type:
+ new_row_index_to_value[index] = value
+ break
+
+ return new_row_index_to_value
+
+
+def _get_numeric_values(text):
+ """Parses text and returns numeric values."""
+ numeric_spans = parse_text(text)
+ return itertools.chain(*(span.values for span in numeric_spans))
+
+
+def _get_column_values(table, col_index):
+ """
+ Parses text in column and returns a dict mapping row_index to values. This is the _get_column_values function from
+ number_annotation_utils.py of the original implementation
+
+ Args:
+ table: Pandas dataframe
+ col_index: integer, indicating the index of the column to get the numeric values of
+ """
+ index_to_values = {}
+ for row_index, row in table.iterrows():
+ text = normalize_for_match(row[col_index].text)
+ index_to_values[row_index] = list(_get_numeric_values(text))
+ return index_to_values
+
+
+def get_numeric_relation(value, other_value, sort_key_fn):
+ """Compares two values and returns their relation or None."""
+ value = sort_key_fn(value)
+ other_value = sort_key_fn(other_value)
+ if value == other_value:
+ return Relation.EQ
+ if value < other_value:
+ return Relation.LT
+ if value > other_value:
+ return Relation.GT
+ return None
+
+
+def add_numeric_values_to_question(question):
+ """Adds numeric value spans to a question."""
+ original_text = question
+ question = normalize_for_match(question)
+ numeric_spans = parse_text(question)
+ return Question(original_text=original_text, text=question, numeric_spans=numeric_spans)
+
+
+def filter_invalid_unicode(text):
+ """Return an empty string and True if 'text' is in invalid unicode."""
+ return ("", True) if isinstance(text, bytes) else (text, False)
+
+
+def filter_invalid_unicode_from_table(table):
+ """
+ Removes invalid unicode from table. Checks whether a table cell text contains an invalid unicode encoding. If yes,
+ reset the table cell text to an empty str and log a warning for each invalid cell
+
+ Args:
+ table: table to clean.
+ """
+ # to do: add table id support
+ if not hasattr(table, "table_id"):
+ table.table_id = 0
+
+ for row_index, row in table.iterrows():
+ for col_index, cell in enumerate(row):
+ cell, is_invalid = filter_invalid_unicode(cell)
+ if is_invalid:
+ logging.warning(
+ f"Scrub an invalid table body @ table_id: {table.table_id}, row_index: {row_index}, "
+ f"col_index: {col_index}",
+ )
+ for col_index, column in enumerate(table.columns):
+ column, is_invalid = filter_invalid_unicode(column)
+ if is_invalid:
+ logging.warning(f"Scrub an invalid table header @ table_id: {table.table_id}, col_index: {col_index}")
+
+
+def add_numeric_table_values(table, min_consolidation_fraction=0.7, debug_info=None):
+ """
+ Parses text in table column-wise and adds the consolidated values. Consolidation refers to finding values with a
+ common types (date or number)
+
+ Args:
+ table:
+ Table to annotate.
+ min_consolidation_fraction:
+ Fraction of cells in a column that need to have consolidated value.
+ debug_info:
+ Additional information used for logging.
+ """
+ table = table.copy()
+ # First, filter table on invalid unicode
+ filter_invalid_unicode_from_table(table)
+
+ # Second, replace cell values by Cell objects
+ for row_index, row in table.iterrows():
+ for col_index, cell in enumerate(row):
+ table.iloc[row_index, col_index] = Cell(text=cell)
+
+ # Third, add numeric_value attributes to these Cell objects
+ for col_index, column in enumerate(table.columns):
+ column_values = _consolidate_numeric_values(
+ _get_column_values(table, col_index),
+ min_consolidation_fraction=min_consolidation_fraction,
+ debug_info=(debug_info, column),
+ )
+
+ for row_index, numeric_value in column_values.items():
+ table.iloc[row_index, col_index].numeric_value = numeric_value
+
+ return table
+
+
+__all__ = ["TapasTokenizer"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/time_series_transformer/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/time_series_transformer/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9f00ba5a9381dd98355e801099d84c31fe0f85a1
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/time_series_transformer/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/time_series_transformer/__pycache__/configuration_time_series_transformer.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/time_series_transformer/__pycache__/configuration_time_series_transformer.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8d278c77202b10faac0558fa4fcc7ed12219a5dc
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/time_series_transformer/__pycache__/configuration_time_series_transformer.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/time_series_transformer/__pycache__/modeling_time_series_transformer.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/time_series_transformer/__pycache__/modeling_time_series_transformer.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..af10971df8e070e1b80b99a36dee97474314a2e9
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/time_series_transformer/__pycache__/modeling_time_series_transformer.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/timesfm/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/timesfm/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1e756a54bc7b1d90ff86493de7d34d1e0d35e8da
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/timesfm/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/timesfm/__pycache__/configuration_timesfm.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/timesfm/__pycache__/configuration_timesfm.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..386054e28ed5a1c4909ad2703a326c722da95946
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/timesfm/__pycache__/configuration_timesfm.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/timesfm/__pycache__/modeling_timesfm.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/timesfm/__pycache__/modeling_timesfm.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dacf47396fee57a88660b44c4489fe418b88efa8
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/timesfm/__pycache__/modeling_timesfm.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/timesfm/__pycache__/modular_timesfm.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/timesfm/__pycache__/modular_timesfm.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e9681ef0610d6b2a116fdfab6bea4483978268c2
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/timesfm/__pycache__/modular_timesfm.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/timesformer/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/timesformer/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c0cc9d3d6a68569b0e0e94c94573d7191b153a68
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/timesformer/__init__.py
@@ -0,0 +1,27 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_timesformer import *
+ from .modeling_timesformer import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/timesformer/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/timesformer/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6379981e61d5bb0c44f4f892c39093ba137179ea
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/timesformer/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/timesformer/__pycache__/configuration_timesformer.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/timesformer/__pycache__/configuration_timesformer.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fce93b5bcd8cca1370bbeaa707c8c94febefca90
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/timesformer/__pycache__/configuration_timesformer.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/timesformer/__pycache__/modeling_timesformer.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/timesformer/__pycache__/modeling_timesformer.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e2245453aa5138f4418c1af4a6213a086ea5d1a9
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/timesformer/__pycache__/modeling_timesformer.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/timesformer/configuration_timesformer.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/timesformer/configuration_timesformer.py
new file mode 100644
index 0000000000000000000000000000000000000000..554d0e02531e394e21f83d72af4665e1b0728bb2
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/timesformer/configuration_timesformer.py
@@ -0,0 +1,66 @@
+# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""TimeSformer model configuration"""
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring
+
+
+@auto_docstring(checkpoint="facebook/timesformer-base-finetuned-k600")
+@strict
+class TimesformerConfig(PreTrainedConfig):
+ r"""
+ num_frames (`int`, *optional*, defaults to 8):
+ The number of frames in each video.
+ attention_type (`str`, *optional*, defaults to `"divided_space_time"`):
+ The attention type to use. Must be one of `"divided_space_time"`, `"space_only"`, `"joint_space_time"`.
+
+ Example:
+
+ ```python
+ >>> from transformers import TimesformerConfig, TimesformerModel
+
+ >>> # Initializing a TimeSformer timesformer-base style configuration
+ >>> configuration = TimesformerConfig()
+
+ >>> # Initializing a model from the configuration
+ >>> model = TimesformerModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "timesformer"
+
+ image_size: int | list[int] | tuple[int, int] = 224
+ patch_size: int | list[int] | tuple[int, int] = 16
+ num_channels: int = 3
+ num_frames: int = 8
+ hidden_size: int = 768
+ num_hidden_layers: int = 12
+ num_attention_heads: int = 12
+ intermediate_size: int = 3072
+ hidden_act: str = "gelu"
+ hidden_dropout_prob: float | int = 0.0
+ attention_probs_dropout_prob: float | int = 0.0
+ initializer_range: float = 0.02
+ layer_norm_eps: float = 1e-6
+ qkv_bias: bool = True
+ attention_type: str = "divided_space_time"
+ drop_path_rate: int = 0
+
+
+__all__ = ["TimesformerConfig"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/timesformer/modeling_timesformer.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/timesformer/modeling_timesformer.py
new file mode 100644
index 0000000000000000000000000000000000000000..cf2a7632a49b9e8e0c71860aeb151b1a26737888
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/timesformer/modeling_timesformer.py
@@ -0,0 +1,751 @@
+# Copyright 2022 Meta and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch TimeSformer model."""
+
+import collections
+
+import torch
+from torch import nn
+from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import BaseModelOutput, ImageClassifierOutput
+from ...modeling_utils import PreTrainedModel
+from ...utils import (
+ auto_docstring,
+ logging,
+)
+from .configuration_timesformer import TimesformerConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+# Adapted from https://github.com/facebookresearch/TimeSformer/blob/a5ef29a7b7264baff199a30b3306ac27de901133/timesformer/models/vit.py#L155
+class TimesformerPatchEmbeddings(nn.Module):
+ """Image to Patch Embedding"""
+
+ def __init__(self, config):
+ super().__init__()
+
+ image_size = config.image_size
+ patch_size = config.patch_size
+
+ image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
+ patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
+
+ num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
+ self.image_size = image_size
+ self.patch_size = patch_size
+ self.num_patches = num_patches
+
+ self.projection = nn.Conv2d(config.num_channels, config.hidden_size, kernel_size=patch_size, stride=patch_size)
+
+ def forward(self, pixel_values):
+ batch_size, num_frames, num_channels, height, width = pixel_values.shape
+ pixel_values = pixel_values.reshape(batch_size * num_frames, num_channels, height, width)
+
+ embeddings = self.projection(pixel_values)
+ patch_width = embeddings.size(-1)
+ embeddings = embeddings.flatten(2).transpose(1, 2)
+ return embeddings, num_frames, patch_width
+
+
+class TimesformerEmbeddings(nn.Module):
+ """
+ Construct the patch and position embeddings.
+ """
+
+ def __init__(self, config):
+ super().__init__()
+
+ embed_dim = config.hidden_size
+ num_frames = config.num_frames
+ drop_rate = config.hidden_dropout_prob
+ attention_type = config.attention_type
+
+ self.attention_type = attention_type
+ self.patch_embeddings = TimesformerPatchEmbeddings(config)
+ self.num_patches = self.patch_embeddings.num_patches
+
+ # Positional Embeddings
+ self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
+ self.position_embeddings = nn.Parameter(torch.zeros(1, self.num_patches + 1, embed_dim))
+ self.pos_drop = nn.Dropout(p=drop_rate)
+ if attention_type != "space_only":
+ self.time_embeddings = nn.Parameter(torch.zeros(1, num_frames, embed_dim))
+ self.time_drop = nn.Dropout(p=drop_rate)
+
+ def forward(self, pixel_values):
+ batch_size = pixel_values.shape[0]
+
+ # create patch embeddings
+ embeddings, num_frames, patch_width = self.patch_embeddings(pixel_values)
+
+ cls_tokens = self.cls_token.expand(embeddings.size(0), -1, -1)
+ embeddings = torch.cat((cls_tokens, embeddings), dim=1)
+
+ # resizing the positional embeddings in case they don't match the input at inference
+ if embeddings.size(1) != self.position_embeddings.size(1):
+ position_embeddings = self.position_embeddings
+ cls_pos_embed = position_embeddings[0, 0, :].unsqueeze(0).unsqueeze(1)
+ other_pos_embed = position_embeddings[0, 1:, :].unsqueeze(0).transpose(1, 2)
+ patch_num = int(other_pos_embed.size(2) ** 0.5)
+ patch_height = embeddings.size(1) // patch_width
+ other_pos_embed = other_pos_embed.reshape(1, embeddings.size(2), patch_num, patch_num)
+ new_pos_embed = nn.functional.interpolate(
+ other_pos_embed, size=(patch_height, patch_width), mode="nearest"
+ )
+ new_pos_embed = new_pos_embed.flatten(2)
+ new_pos_embed = new_pos_embed.transpose(1, 2)
+ new_pos_embed = torch.cat((cls_pos_embed, new_pos_embed), 1)
+ embeddings = embeddings + new_pos_embed
+ else:
+ embeddings = embeddings + self.position_embeddings
+ embeddings = self.pos_drop(embeddings)
+
+ # Time Embeddings
+ if self.attention_type != "space_only":
+ cls_tokens = embeddings[:batch_size, 0, :].unsqueeze(1)
+ embeddings = embeddings[:, 1:]
+ _, patch_height, patch_width = embeddings.shape
+ embeddings = (
+ embeddings.reshape(batch_size, num_frames, patch_height, patch_width)
+ .permute(0, 2, 1, 3)
+ .reshape(batch_size * patch_height, num_frames, patch_width)
+ )
+ # Resizing time embeddings in case they don't match
+ if num_frames != self.time_embeddings.size(1):
+ time_embeddings = self.time_embeddings.transpose(1, 2)
+ new_time_embeddings = nn.functional.interpolate(time_embeddings, size=(num_frames), mode="nearest")
+ new_time_embeddings = new_time_embeddings.transpose(1, 2)
+ embeddings = embeddings + new_time_embeddings
+ else:
+ embeddings = embeddings + self.time_embeddings
+ embeddings = self.time_drop(embeddings)
+ embeddings = embeddings.view(batch_size, patch_height, num_frames, patch_width).reshape(
+ batch_size, patch_height * num_frames, patch_width
+ )
+ embeddings = torch.cat((cls_tokens, embeddings), dim=1)
+
+ return embeddings
+
+
+# Adapted from https://github.com/facebookresearch/TimeSformer/blob/a5ef29a7b7264baff199a30b3306ac27de901133/timesformer/models/vit.py#L57
+class TimesformerSelfAttention(nn.Module):
+ def __init__(self, config: TimesformerConfig):
+ super().__init__()
+
+ num_heads = config.num_attention_heads
+ qkv_bias = config.qkv_bias
+ attention_dropout_prob = config.attention_probs_dropout_prob
+
+ self.num_heads = num_heads
+ head_dim = config.hidden_size // num_heads
+ self.scale = head_dim**-0.5
+ self.qkv = nn.Linear(config.hidden_size, config.hidden_size * 3, bias=qkv_bias)
+ self.attn_drop = nn.Dropout(attention_dropout_prob)
+
+ def forward(self, hidden_states, output_attentions: bool = False):
+ batch_size, hidden_size, num_channels = hidden_states.shape
+ qkv = (
+ self.qkv(hidden_states)
+ .reshape(batch_size, hidden_size, 3, self.num_heads, num_channels // self.num_heads)
+ .permute(2, 0, 3, 1, 4)
+ )
+ query, key, value = qkv[0], qkv[1], qkv[2]
+
+ attention_probs = (query @ key.transpose(-2, -1)) * self.scale
+ attention_probs = attention_probs.softmax(dim=-1)
+ attention_probs = self.attn_drop(attention_probs)
+
+ context_layer = (attention_probs @ value).transpose(1, 2).reshape(batch_size, hidden_size, num_channels)
+
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
+
+ return outputs
+
+
+class TimesformerSelfOutput(nn.Module):
+ """
+ The residual connection is defined in TimesformerLayer instead of here (as is the case with other models), due to
+ the layernorm applied before each block.
+ """
+
+ def __init__(self, config: TimesformerConfig) -> None:
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+
+ return hidden_states
+
+
+class TimeSformerAttention(nn.Module):
+ def __init__(self, config: TimesformerConfig) -> None:
+ super().__init__()
+ self.attention = TimesformerSelfAttention(config)
+ self.output = TimesformerSelfOutput(config)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ output_attentions: bool = False,
+ ) -> tuple[torch.Tensor, torch.Tensor] | tuple[torch.Tensor]:
+ self_outputs = self.attention(hidden_states, output_attentions)
+
+ attention_output = self.output(self_outputs[0])
+
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
+ return outputs
+
+
+# Adapted from https://github.com/facebookresearch/TimeSformer/blob/a5ef29a7b7264baff199a30b3306ac27de901133/timesformer/models/vit.py#L39
+class TimesformerIntermediate(nn.Module):
+ def __init__(self, config: TimesformerConfig) -> None:
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ if isinstance(config.hidden_act, str):
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
+ else:
+ self.intermediate_act_fn = config.hidden_act
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.intermediate_act_fn(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+
+ return hidden_states
+
+
+class TimesformerOutput(nn.Module):
+ def __init__(self, config: TimesformerConfig) -> None:
+ super().__init__()
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+
+ return hidden_states
+
+
+# Copied from transformers.models.swin.modular_swin.SwinDropPath with SwinDropPath->TimesformerDropPath
+class TimesformerDropPath(nn.Module):
+ """Stochastic depth (DropPath) per sample, for residual blocks.
+
+ Identity when ``drop_prob`` is 0 or outside training. See `Deep Networks with Stochastic Depth
+ `_.
+ """
+
+ def __init__(self, drop_prob: float = 0.0) -> None:
+ super().__init__()
+ self.drop_prob = drop_prob
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ if self.drop_prob == 0.0 or not self.training:
+ return hidden_states
+ keep_prob = 1 - self.drop_prob
+ shape = (hidden_states.shape[0],) + (1,) * (hidden_states.ndim - 1)
+ random_tensor = torch.rand(shape, dtype=hidden_states.dtype, device=hidden_states.device)
+ random_tensor = torch.floor(random_tensor + keep_prob)
+ return hidden_states.div(keep_prob) * random_tensor
+
+ def extra_repr(self) -> str:
+ return f"p={self.drop_prob}"
+
+
+# Adapted from https://github.com/facebookresearch/TimeSformer/blob/a5ef29a7b7264baff199a30b3306ac27de901133/timesformer/models/vit.py#L89
+class TimesformerLayer(GradientCheckpointingLayer):
+ def __init__(self, config: TimesformerConfig, layer_index: int) -> None:
+ super().__init__()
+
+ attention_type = config.attention_type
+
+ drop_path_rates = [
+ x.item() for x in torch.linspace(0, config.drop_path_rate, config.num_hidden_layers, device="cpu")
+ ] # stochastic depth decay rule
+ drop_path_rate = drop_path_rates[layer_index]
+
+ self.drop_path = TimesformerDropPath(drop_path_rate) if drop_path_rate > 0.0 else nn.Identity()
+ self.attention = TimeSformerAttention(config)
+ self.intermediate = TimesformerIntermediate(config)
+ self.output = TimesformerOutput(config)
+ self.layernorm_before = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.layernorm_after = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+
+ self.config = config
+ self.attention_type = attention_type
+ if attention_type not in ["divided_space_time", "space_only", "joint_space_time"]:
+ raise ValueError(f"Unknown attention type: {attention_type}")
+
+ # Temporal Attention Parameters
+ if self.attention_type == "divided_space_time":
+ self.temporal_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.temporal_attention = TimeSformerAttention(config)
+ self.temporal_dense = nn.Linear(config.hidden_size, config.hidden_size)
+
+ def forward(self, hidden_states: torch.Tensor, output_attentions: bool = False):
+ num_frames = self.config.num_frames
+ num_patch_width = self.config.image_size // self.config.patch_size
+ batch_size = hidden_states.shape[0]
+ num_spatial_tokens = (hidden_states.size(1) - 1) // num_frames
+ num_patch_height = num_spatial_tokens // num_patch_width
+
+ if self.attention_type in ["space_only", "joint_space_time"]:
+ self_attention_outputs = self.attention(
+ self.layernorm_before(hidden_states), output_attentions=output_attentions
+ )
+ attention_output = self_attention_outputs[0]
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
+
+ hidden_states = hidden_states + self.drop_path(attention_output)
+
+ layer_output = self.layernorm_after(hidden_states)
+ layer_output = self.intermediate(layer_output)
+ layer_output = self.output(layer_output)
+ layer_output = hidden_states + self.drop_path(layer_output)
+
+ outputs = (layer_output,) + outputs
+
+ return outputs
+
+ elif self.attention_type == "divided_space_time":
+ # Temporal
+ temporal_embedding = hidden_states[:, 1:, :]
+ temporal_embedding = temporal_embedding.reshape(
+ batch_size, num_patch_height, num_patch_width, num_frames, temporal_embedding.shape[2]
+ ).reshape(batch_size * num_patch_height * num_patch_width, num_frames, temporal_embedding.shape[2])
+
+ temporal_attention_outputs = self.temporal_attention(
+ self.temporal_layernorm(temporal_embedding),
+ )
+ attention_output = temporal_attention_outputs[0]
+
+ residual_temporal = self.drop_path(attention_output)
+
+ residual_temporal = residual_temporal.reshape(
+ batch_size, num_patch_height, num_patch_width, num_frames, residual_temporal.shape[2]
+ ).reshape(batch_size, num_patch_height * num_patch_width * num_frames, residual_temporal.shape[2])
+ residual_temporal = self.temporal_dense(residual_temporal)
+ temporal_embedding = hidden_states[:, 1:, :] + residual_temporal
+
+ # Spatial
+ init_cls_token = hidden_states[:, 0, :].unsqueeze(1)
+ cls_token = init_cls_token.repeat(1, num_frames, 1)
+ cls_token = cls_token.reshape(batch_size * num_frames, 1, cls_token.shape[2])
+ spatial_embedding = temporal_embedding
+ spatial_embedding = (
+ spatial_embedding.reshape(
+ batch_size, num_patch_height, num_patch_width, num_frames, spatial_embedding.shape[2]
+ )
+ .permute(0, 3, 1, 2, 4)
+ .reshape(batch_size * num_frames, num_patch_height * num_patch_width, spatial_embedding.shape[2])
+ )
+ spatial_embedding = torch.cat((cls_token, spatial_embedding), 1)
+
+ spatial_attention_outputs = self.attention(
+ self.layernorm_before(spatial_embedding), output_attentions=output_attentions
+ )
+ attention_output = spatial_attention_outputs[0]
+ outputs = spatial_attention_outputs[1:] # add self attentions if we output attention weights
+
+ residual_spatial = self.drop_path(attention_output)
+
+ # Taking care of CLS token
+ cls_token = residual_spatial[:, 0, :]
+ cls_token = cls_token.reshape(batch_size, num_frames, cls_token.shape[1])
+ cls_token = torch.mean(cls_token, 1, True) # averaging for every frame
+ residual_spatial = residual_spatial[:, 1:, :]
+ residual_spatial = (
+ residual_spatial.reshape(
+ batch_size, num_frames, num_patch_height, num_patch_width, residual_spatial.shape[2]
+ )
+ .permute(0, 2, 3, 1, 4)
+ .reshape(batch_size, num_patch_height * num_patch_width * num_frames, residual_spatial.shape[2])
+ )
+ residual = residual_spatial
+ hidden_states = temporal_embedding
+
+ # Mlp
+ hidden_states = torch.cat((init_cls_token, hidden_states), 1) + torch.cat((cls_token, residual), 1)
+ layer_output = self.layernorm_after(hidden_states)
+ layer_output = self.intermediate(layer_output)
+ layer_output = self.output(layer_output)
+ layer_output = hidden_states + self.drop_path(layer_output)
+
+ outputs = (layer_output,) + outputs
+
+ return outputs
+
+
+class TimesformerEncoder(nn.Module):
+ def __init__(self, config: TimesformerConfig) -> None:
+ super().__init__()
+ self.config = config
+ self.layer = nn.ModuleList([TimesformerLayer(config, ind) for ind in range(config.num_hidden_layers)])
+ self.gradient_checkpointing = False
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ output_attentions: bool = False,
+ output_hidden_states: bool = False,
+ return_dict: bool = True,
+ ) -> tuple | BaseModelOutput:
+ all_hidden_states = () if output_hidden_states else None
+ all_self_attentions = () if output_attentions else None
+
+ for i, layer_module in enumerate(self.layer):
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ layer_outputs = layer_module(hidden_states, output_attentions)
+
+ hidden_states = layer_outputs[0]
+
+ if output_attentions:
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
+
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ if not return_dict:
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
+ return BaseModelOutput(
+ last_hidden_state=hidden_states,
+ hidden_states=all_hidden_states,
+ attentions=all_self_attentions,
+ )
+
+
+@auto_docstring
+class TimesformerPreTrainedModel(PreTrainedModel):
+ config: TimesformerConfig
+ base_model_prefix = "timesformer"
+ main_input_name = "pixel_values"
+ input_modalities = ("image",)
+ supports_gradient_checkpointing = True
+ _no_split_modules = ["TimesformerLayer"]
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ if isinstance(module, (nn.Linear, nn.Conv2d)):
+ init.trunc_normal_(module.weight, std=self.config.initializer_range)
+ if module.bias is not None:
+ init.constant_(module.bias, 0)
+ elif isinstance(module, nn.LayerNorm):
+ init.constant_(module.bias, 0)
+ init.constant_(module.weight, 1.0)
+ elif isinstance(module, TimesformerEmbeddings):
+ init.trunc_normal_(module.cls_token, std=self.config.initializer_range)
+ init.trunc_normal_(module.position_embeddings, std=self.config.initializer_range)
+
+
+@auto_docstring
+class TimesformerModel(TimesformerPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.config = config
+
+ self.embeddings = TimesformerEmbeddings(config)
+ self.encoder = TimesformerEncoder(config)
+
+ self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.embeddings.patch_embeddings
+
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: torch.FloatTensor,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple[torch.FloatTensor] | BaseModelOutput:
+ r"""
+ Examples:
+
+ ```python
+ >>> import av
+ >>> import numpy as np
+
+ >>> from transformers import AutoImageProcessor, TimesformerModel
+ >>> from huggingface_hub import hf_hub_download
+
+ >>> np.random.seed(0)
+
+
+ >>> def read_video_pyav(container, indices):
+ ... '''
+ ... Decode the video with PyAV decoder.
+ ... Args:
+ ... container (`av.container.input.InputContainer`): PyAV container.
+ ... indices (`list[int]`): List of frame indices to decode.
+ ... Returns:
+ ... result (np.ndarray): np array of decoded frames of shape (num_frames, height, width, 3).
+ ... '''
+ ... frames = []
+ ... container.seek(0)
+ ... start_index = indices[0]
+ ... end_index = indices[-1]
+ ... for i, frame in enumerate(container.decode(video=0)):
+ ... if i > end_index:
+ ... break
+ ... if i >= start_index and i in indices:
+ ... frames.append(frame)
+ ... return np.stack([x.to_ndarray(format="rgb24") for x in frames])
+
+
+ >>> def sample_frame_indices(clip_len, frame_sample_rate, seg_len):
+ ... '''
+ ... Sample a given number of frame indices from the video.
+ ... Args:
+ ... clip_len (`int`): Total number of frames to sample.
+ ... frame_sample_rate (`int`): Sample every n-th frame.
+ ... seg_len (`int`): Maximum allowed index of sample's last frame.
+ ... Returns:
+ ... indices (`list[int]`): List of sampled frame indices
+ ... '''
+ ... converted_len = int(clip_len * frame_sample_rate)
+ ... end_idx = np.random.randint(converted_len, seg_len)
+ ... start_idx = end_idx - converted_len
+ ... indices = np.linspace(start_idx, end_idx, num=clip_len)
+ ... indices = np.clip(indices, start_idx, end_idx - 1).astype(np.int64)
+ ... return indices
+
+
+ >>> # video clip consists of 300 frames (10 seconds at 30 FPS)
+ >>> file_path = hf_hub_download(
+ ... repo_id="nielsr/video-demo", filename="eating_spaghetti.mp4", repo_type="dataset"
+ ... )
+ >>> container = av.open(file_path)
+
+ >>> # sample 8 frames
+ >>> indices = sample_frame_indices(clip_len=8, frame_sample_rate=4, seg_len=container.streams.video[0].frames)
+ >>> video = read_video_pyav(container, indices)
+
+ >>> image_processor = AutoImageProcessor.from_pretrained("MCG-NJU/videomae-base")
+ >>> model = TimesformerModel.from_pretrained("facebook/timesformer-base-finetuned-k400")
+
+ >>> # prepare video for the model
+ >>> inputs = image_processor(list(video), return_tensors="pt")
+
+ >>> # forward pass
+ >>> outputs = model(**inputs)
+ >>> last_hidden_states = outputs.last_hidden_state
+ >>> list(last_hidden_states.shape)
+ [1, 1569, 768]
+ ```"""
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ embedding_output = self.embeddings(pixel_values)
+
+ encoder_outputs = self.encoder(
+ embedding_output,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+ sequence_output = encoder_outputs[0]
+ if self.layernorm is not None:
+ sequence_output = self.layernorm(sequence_output)
+
+ if not return_dict:
+ return (sequence_output,) + encoder_outputs[1:]
+
+ return BaseModelOutput(
+ last_hidden_state=sequence_output,
+ hidden_states=encoder_outputs.hidden_states,
+ attentions=encoder_outputs.attentions,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ TimeSformer Model transformer with a video classification head on top (a linear layer on top of the final hidden state
+ of the [CLS] token) e.g. for ImageNet.
+ """
+)
+class TimesformerForVideoClassification(TimesformerPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.num_labels = config.num_labels
+ self.timesformer = TimesformerModel(config)
+
+ # Classifier head
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels) if config.num_labels > 0 else nn.Identity()
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: torch.Tensor | None = None,
+ labels: torch.Tensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> tuple | ImageClassifierOutput:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+
+ Examples:
+
+ ```python
+ >>> import av
+ >>> import torch
+ >>> import numpy as np
+
+ >>> from transformers import AutoImageProcessor, TimesformerForVideoClassification
+ >>> from huggingface_hub import hf_hub_download
+
+ >>> np.random.seed(0)
+
+
+ >>> def read_video_pyav(container, indices):
+ ... '''
+ ... Decode the video with PyAV decoder.
+ ... Args:
+ ... container (`av.container.input.InputContainer`): PyAV container.
+ ... indices (`list[int]`): List of frame indices to decode.
+ ... Returns:
+ ... result (np.ndarray): np array of decoded frames of shape (num_frames, height, width, 3).
+ ... '''
+ ... frames = []
+ ... container.seek(0)
+ ... start_index = indices[0]
+ ... end_index = indices[-1]
+ ... for i, frame in enumerate(container.decode(video=0)):
+ ... if i > end_index:
+ ... break
+ ... if i >= start_index and i in indices:
+ ... frames.append(frame)
+ ... return np.stack([x.to_ndarray(format="rgb24") for x in frames])
+
+
+ >>> def sample_frame_indices(clip_len, frame_sample_rate, seg_len):
+ ... '''
+ ... Sample a given number of frame indices from the video.
+ ... Args:
+ ... clip_len (`int`): Total number of frames to sample.
+ ... frame_sample_rate (`int`): Sample every n-th frame.
+ ... seg_len (`int`): Maximum allowed index of sample's last frame.
+ ... Returns:
+ ... indices (`list[int]`): List of sampled frame indices
+ ... '''
+ ... converted_len = int(clip_len * frame_sample_rate)
+ ... end_idx = np.random.randint(converted_len, seg_len)
+ ... start_idx = end_idx - converted_len
+ ... indices = np.linspace(start_idx, end_idx, num=clip_len)
+ ... indices = np.clip(indices, start_idx, end_idx - 1).astype(np.int64)
+ ... return indices
+
+
+ >>> # video clip consists of 300 frames (10 seconds at 30 FPS)
+ >>> file_path = hf_hub_download(
+ ... repo_id="nielsr/video-demo", filename="eating_spaghetti.mp4", repo_type="dataset"
+ ... )
+ >>> container = av.open(file_path)
+
+ >>> # sample 8 frames
+ >>> indices = sample_frame_indices(clip_len=8, frame_sample_rate=1, seg_len=container.streams.video[0].frames)
+ >>> video = read_video_pyav(container, indices)
+
+ >>> image_processor = AutoImageProcessor.from_pretrained("MCG-NJU/videomae-base-finetuned-kinetics")
+ >>> model = TimesformerForVideoClassification.from_pretrained("facebook/timesformer-base-finetuned-k400")
+
+ >>> inputs = image_processor(list(video), return_tensors="pt")
+
+ >>> with torch.no_grad():
+ ... outputs = model(**inputs)
+ ... logits = outputs.logits
+
+ >>> # model predicts one of the 400 Kinetics-400 classes
+ >>> predicted_label = logits.argmax(-1).item()
+ >>> print(model.config.id2label[predicted_label])
+ eating spaghetti
+ ```"""
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ outputs = self.timesformer(
+ pixel_values,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ sequence_output = outputs[0][:, 0]
+
+ logits = self.classifier(sequence_output)
+
+ loss = None
+ if labels is not None:
+ if self.config.problem_type is None:
+ if self.num_labels == 1:
+ self.config.problem_type = "regression"
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
+ self.config.problem_type = "single_label_classification"
+ else:
+ self.config.problem_type = "multi_label_classification"
+
+ if self.config.problem_type == "regression":
+ loss_fct = MSELoss()
+ if self.num_labels == 1:
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
+ else:
+ loss = loss_fct(logits, labels)
+ elif self.config.problem_type == "single_label_classification":
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+ elif self.config.problem_type == "multi_label_classification":
+ loss_fct = BCEWithLogitsLoss()
+ loss = loss_fct(logits, labels)
+
+ if not return_dict:
+ output = (logits,) + outputs[1:]
+ return ((loss,) + output) if loss is not None else output
+
+ return ImageClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+__all__ = ["TimesformerModel", "TimesformerForVideoClassification", "TimesformerPreTrainedModel"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/timm_backbone/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/timm_backbone/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..4a58f096b1e48227518b04a11250d66635c65701
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/timm_backbone/__init__.py
@@ -0,0 +1,27 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_timm_backbone import *
+ from .modeling_timm_backbone import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/timm_backbone/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/timm_backbone/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9b7cb4754a8d698e0584dfd56a27352061d19141
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/timm_backbone/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/timm_backbone/__pycache__/configuration_timm_backbone.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/timm_backbone/__pycache__/configuration_timm_backbone.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e847e58c04bf26bc23a714e1b9f7d60a3270af6f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/timm_backbone/__pycache__/configuration_timm_backbone.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/timm_backbone/__pycache__/modeling_timm_backbone.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/timm_backbone/__pycache__/modeling_timm_backbone.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..004db8fee4dab9311ce57d0c373964dca087dfff
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/timm_backbone/__pycache__/modeling_timm_backbone.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/timm_backbone/configuration_timm_backbone.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/timm_backbone/configuration_timm_backbone.py
new file mode 100644
index 0000000000000000000000000000000000000000..15c0a9cd8d280e835ea53a2b724831d2c1fe807c
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/timm_backbone/configuration_timm_backbone.py
@@ -0,0 +1,90 @@
+# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Configuration for Backbone models"""
+
+from huggingface_hub.dataclasses import strict
+
+from ...backbone_utils import BackboneConfigMixin
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring
+
+
+@auto_docstring(checkpoint="")
+@strict
+class TimmBackboneConfig(BackboneConfigMixin, PreTrainedConfig):
+ r"""
+ backbone (`str`, *optional*):
+ The timm checkpoint to load.
+ features_only (`bool`, *optional*, defaults to `True`):
+ Whether to output only the features or also the logits.
+ freeze_batch_norm_2d (`bool`, *optional*, defaults to `False`):
+ Converts all `BatchNorm2d` and `SyncBatchNorm` layers of provided module into `FrozenBatchNorm2d`.
+
+ Example:
+ ```python
+ >>> from transformers import TimmBackboneConfig, TimmBackbone
+
+ >>> # Initializing a timm backbone
+ >>> configuration = TimmBackboneConfig("resnet50")
+
+ >>> # Initializing a model from the configuration
+ >>> model = TimmBackbone(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```
+ """
+
+ model_type = "timm_backbone"
+
+ backbone: str | None = None
+ num_channels: int = 3
+ features_only: bool = True
+ _out_indices: list[int] | None = None
+ freeze_batch_norm_2d: bool = False
+ output_stride: int | None = None
+
+ def __post_init__(self, **kwargs):
+ self.out_indices = self.out_indices if self.out_indices is not None else [-1]
+ super().__post_init__(**kwargs)
+
+ @property
+ def out_indices(self):
+ return self._out_indices
+
+ @out_indices.setter
+ def out_indices(self, out_indices: tuple[int, ...] | list[int]):
+ """
+ Set the out_indices attribute. This will also update the out_features attribute to match the new out_indices.
+ """
+ self._out_indices = list(out_indices) if out_indices is not None else out_indices
+ if getattr(self, "stage_names", None) is not None:
+ self.set_output_features_output_indices(out_features=None, out_indices=out_indices)
+
+ @property
+ def out_features(self):
+ return self._out_features
+
+ @out_features.setter
+ def out_features(self, out_features: list[str]):
+ """
+ Set the out_features attribute. This will also update the out_indices attribute to match the new out_features.
+ """
+ self._out_features = out_features
+ if getattr(self, "stage_names", None) is not None:
+ self.set_output_features_output_indices(out_features=out_features, out_indices=None)
+
+
+__all__ = ["TimmBackboneConfig"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/timm_backbone/modeling_timm_backbone.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/timm_backbone/modeling_timm_backbone.py
new file mode 100644
index 0000000000000000000000000000000000000000..c60606a7657ec9e9648ff808b5461337ae67a784
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/timm_backbone/modeling_timm_backbone.py
@@ -0,0 +1,161 @@
+# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+import torch
+from torch import Tensor, nn
+
+from ... import initialization as init
+from ...backbone_utils import BackboneMixin, filter_output_hidden_states
+from ...modeling_outputs import BackboneOutput
+from ...modeling_utils import PreTrainedModel
+from ...utils import is_timm_available, requires_backends
+from ...utils.generic import can_return_tuple
+from .configuration_timm_backbone import TimmBackboneConfig
+
+
+if is_timm_available():
+ import timm
+
+
+class TimmBackbone(BackboneMixin, PreTrainedModel):
+ """
+ Wrapper class for timm models to be used as backbones. This enables using the timm models interchangeably with the
+ other models in the library keeping the same API.
+ """
+
+ main_input_name = "pixel_values"
+ input_modalities = ("image",)
+ supports_gradient_checkpointing = False
+ config: TimmBackboneConfig
+
+ def __init__(self, config, **kwargs):
+ requires_backends(self, "timm")
+
+ if config.backbone is None:
+ raise ValueError("backbone is not set in the config. Please set it to a timm model name.")
+
+ # We just take the final layer by default. This matches the default for the transformers models.
+ out_indices = config.out_indices if getattr(config, "out_indices", None) is not None else (-1,)
+ pretrained = kwargs.pop("pretrained", False)
+ in_chans = kwargs.pop("in_chans", config.num_channels)
+
+ backbone = timm.create_model(
+ config.backbone,
+ pretrained=pretrained,
+ # This is currently not possible for transformer architectures.
+ features_only=config.features_only,
+ in_chans=in_chans,
+ out_indices=out_indices,
+ output_stride=config.output_stride,
+ **kwargs,
+ )
+
+ # Needs to be called after creating timm model, because `super()` will try to infer
+ # `stage_names` from model architecture
+ super().__init__(config, timm_backbone=backbone)
+ self._backbone = backbone
+
+ # Converts all `BatchNorm2d` and `SyncBatchNorm` or `BatchNormAct2d` and `SyncBatchNormAct2d` layers of
+ # provided module into `FrozenBatchNorm2d` or `FrozenBatchNormAct2d` respectively
+ if getattr(config, "freeze_batch_norm_2d", False):
+ self.freeze_batch_norm_2d()
+
+ # These are used to control the output of the model when called. If output_hidden_states is True, then
+ # return_layers is modified to include all layers.
+ self._return_layers = {
+ layer["module"]: str(layer["index"]) for layer in self._backbone.feature_info.get_dicts()
+ }
+ self._all_layers = {layer["module"]: str(i) for i, layer in enumerate(self._backbone.feature_info.info)}
+
+ self.post_init()
+
+ @classmethod
+ def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):
+ requires_backends(cls, ["vision", "timm"])
+
+ config = kwargs.pop("config", TimmBackboneConfig())
+ num_channels = kwargs.pop("num_channels", config.num_channels)
+ features_only = kwargs.pop("features_only", config.features_only)
+ out_indices = kwargs.pop("out_indices", config.out_indices)
+ config = TimmBackboneConfig(
+ backbone=pretrained_model_name_or_path,
+ num_channels=num_channels,
+ features_only=features_only,
+ out_indices=out_indices,
+ )
+ return super()._from_config(config, pretrained=True, **kwargs)
+
+ def freeze_batch_norm_2d(self):
+ timm.utils.model.freeze_batch_norm_2d(self._backbone)
+
+ def unfreeze_batch_norm_2d(self):
+ timm.utils.model.unfreeze_batch_norm_2d(self._backbone)
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ """We need to at least re-init the non-persistent buffers if the model was initialized on meta device (we
+ assume weights and persistent buffers will be part of checkpoint as we have no way to control timm inits)"""
+ if hasattr(module, "init_non_persistent_buffers"):
+ module.init_non_persistent_buffers()
+ elif isinstance(module, nn.BatchNorm2d):
+ # For non-pretrained models, always initialize buffers (handles both meta device and to_empty() cases)
+ running_mean = getattr(module, "running_mean", None)
+ if running_mean is not None:
+ init.zeros_(module.running_mean)
+ init.ones_(module.running_var)
+ init.zeros_(module.num_batches_tracked)
+
+ @can_return_tuple
+ @filter_output_hidden_states
+ def forward(
+ self,
+ pixel_values: torch.FloatTensor,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ **kwargs,
+ ) -> BackboneOutput | tuple[Tensor, ...]:
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+
+ if output_attentions:
+ raise ValueError("Cannot output attentions for timm backbones at the moment")
+
+ if output_hidden_states:
+ # We modify the return layers to include all the stages of the backbone
+ self._backbone.return_layers = self._all_layers
+ hidden_states = self._backbone(pixel_values, **kwargs)
+ self._backbone.return_layers = self._return_layers
+ feature_maps = tuple(hidden_states[i] for i in self.out_indices)
+ else:
+ feature_maps = self._backbone(pixel_values, **kwargs)
+ hidden_states = None
+
+ feature_maps = tuple(feature_maps)
+ hidden_states = tuple(hidden_states) if hidden_states is not None else None
+
+ if not return_dict:
+ output = (feature_maps,)
+ if output_hidden_states:
+ output = output + (hidden_states,)
+ return output
+
+ return BackboneOutput(feature_maps=feature_maps, hidden_states=hidden_states, attentions=None)
+
+
+__all__ = ["TimmBackbone"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/unispeech/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/unispeech/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6a283bacae6523efe0aef12ac88f6f107ffe3f7f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/unispeech/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/unispeech/__pycache__/configuration_unispeech.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/unispeech/__pycache__/configuration_unispeech.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b0473d0d7a75db7dfde94f12c36343d6e0886f0d
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/unispeech/__pycache__/configuration_unispeech.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/unispeech/__pycache__/modeling_unispeech.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/unispeech/__pycache__/modeling_unispeech.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2bc044516b299d8dce8ea5dc898e7c446732c4a6
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/unispeech/__pycache__/modeling_unispeech.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/unispeech/__pycache__/modular_unispeech.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/unispeech/__pycache__/modular_unispeech.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ad221346a176dc91e2b2e1e6131b082868c9b1bc
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/unispeech/__pycache__/modular_unispeech.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/unispeech_sat/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/unispeech_sat/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e70db5f54bd78ac6405303ce8cc480435e0d11a3
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/unispeech_sat/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/unispeech_sat/__pycache__/configuration_unispeech_sat.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/unispeech_sat/__pycache__/configuration_unispeech_sat.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..22cddb15dad20c2043c70dc6db5f2768175d35d4
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/unispeech_sat/__pycache__/configuration_unispeech_sat.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/unispeech_sat/__pycache__/modeling_unispeech_sat.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/unispeech_sat/__pycache__/modeling_unispeech_sat.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7cf5a4a2dce8acdf77d2ee395205a7e6629ccecb
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/unispeech_sat/__pycache__/modeling_unispeech_sat.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/unispeech_sat/__pycache__/modular_unispeech_sat.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/unispeech_sat/__pycache__/modular_unispeech_sat.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3194c525ef8493364afa68d4091087836becc796
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/unispeech_sat/__pycache__/modular_unispeech_sat.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/vaultgemma/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/vaultgemma/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e41a0e15febbd8cb5cccdc0867560b7c70d10d80
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/vaultgemma/__init__.py
@@ -0,0 +1,28 @@
+# Copyright 2025 the HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_vaultgemma import *
+ from .modeling_vaultgemma import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/vaultgemma/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/vaultgemma/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9c6ef2ccbeeea5a92a2720ae5dee000a3bb598ec
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/vaultgemma/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/vaultgemma/__pycache__/configuration_vaultgemma.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/vaultgemma/__pycache__/configuration_vaultgemma.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a2c970b2f97d3eecfc2fbc565f20b77a0c0a235a
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/vaultgemma/__pycache__/configuration_vaultgemma.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/vaultgemma/__pycache__/modeling_vaultgemma.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/vaultgemma/__pycache__/modeling_vaultgemma.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a1e6f3770ad4f0e85e46100b2527451663ef19a3
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/vaultgemma/__pycache__/modeling_vaultgemma.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/vaultgemma/__pycache__/modular_vaultgemma.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/vaultgemma/__pycache__/modular_vaultgemma.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1666e8112d19588b6e3a9da78ffe6f96df403a75
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/vaultgemma/__pycache__/modular_vaultgemma.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/vaultgemma/configuration_vaultgemma.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/vaultgemma/configuration_vaultgemma.py
new file mode 100644
index 0000000000000000000000000000000000000000..a60b7e8edc0c8c9928fe0dd27a80c7ffcf08d316
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/vaultgemma/configuration_vaultgemma.py
@@ -0,0 +1,109 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/vaultgemma/modular_vaultgemma.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_vaultgemma.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2025 the HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...modeling_rope_utils import RopeParameters
+from ...utils import auto_docstring
+
+
+@auto_docstring(checkpoint="google/vaultgemma-1b")
+@strict
+class VaultGemmaConfig(PreTrainedConfig):
+ r"""
+ query_pre_attn_scalar (`float`, *optional*, defaults to 256):
+ scaling factor used on the attention scores
+ final_logit_softcapping (`float`, *optional*, defaults to 30.0):
+ scaling factor when applying tanh softcapping on the logits.
+ attn_logit_softcapping (`float`, *optional*, defaults to 50.0):
+ scaling factor when applying tanh softcapping on the attention scores.
+
+ ```python
+ >>> from transformers import VaultGemmaModel, VaultGemmaConfig
+ >>> # Initializing a VaultGemma vaultgemma-7b style configuration
+ >>> configuration = VaultGemmaConfig()
+ >>> # Initializing a model from the vaultgemma-7b style configuration
+ >>> model = VaultGemmaModel(configuration)
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "vaultgemma"
+ keys_to_ignore_at_inference = ["past_key_values"]
+ base_model_tp_plan = {
+ "layers.*.self_attn.q_proj": "colwise",
+ "layers.*.self_attn.k_proj": "colwise",
+ "layers.*.self_attn.v_proj": "colwise",
+ "layers.*.self_attn.o_proj": "rowwise",
+ "layers.*.mlp.gate_proj": "colwise",
+ "layers.*.mlp.up_proj": "colwise",
+ "layers.*.mlp.down_proj": "rowwise",
+ }
+ base_model_pp_plan = {
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
+ "norm": (["hidden_states"], ["hidden_states"]),
+ }
+
+ vocab_size: int = 256000
+ hidden_size: int = 2304
+ intermediate_size: int = 9216
+ num_hidden_layers: int = 26
+ num_attention_heads: int = 8
+ num_key_value_heads: int = 4
+ head_dim: int = 256
+ hidden_activation: str = "gelu_pytorch_tanh"
+ max_position_embeddings: int = 8192
+ initializer_range: float = 0.02
+ rms_norm_eps: float = 1e-6
+ use_cache: bool = True
+ pad_token_id: int | None = 0
+ eos_token_id: int | list[int] | None = 1
+ bos_token_id: int | None = 2
+ tie_word_embeddings: bool = True
+ rope_parameters: RopeParameters | dict | None = None
+ attention_bias: bool = False
+ attention_dropout: int | float | None = 0.0
+ query_pre_attn_scalar: int = 256
+ sliding_window: int | None = 4096
+ layer_types: list[str] | None = None
+ final_logit_softcapping: float | None = 30.0
+ attn_logit_softcapping: float | None = 50.0
+
+ def __post_init__(self, **kwargs):
+ if self.layer_types is None:
+ self.layer_types = [
+ "sliding_attention" if bool((i + 1) % 2) else "full_attention" for i in range(self.num_hidden_layers)
+ ]
+
+ super().__post_init__(**kwargs)
+
+ def validate_architecture(self):
+ """Part of `@strict`-powered validation. Validates the architecture of the config."""
+ if self.hidden_size % self.num_attention_heads != 0:
+ raise ValueError(
+ f"The hidden size ({self.hidden_size}) is not a multiple of the number of attention "
+ f"heads ({self.num_attention_heads})."
+ )
+
+
+__all__ = ["VaultGemmaConfig"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/vaultgemma/modeling_vaultgemma.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/vaultgemma/modeling_vaultgemma.py
new file mode 100644
index 0000000000000000000000000000000000000000..f0a2e48d20b8fd36e6a096baa1b5d28c10f3b8b4
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/vaultgemma/modeling_vaultgemma.py
@@ -0,0 +1,546 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/vaultgemma/modular_vaultgemma.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_vaultgemma.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2025 the HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+from collections.abc import Callable
+from typing import Optional
+
+import torch
+import torch.nn as nn
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...cache_utils import Cache, DynamicCache
+from ...generation import GenerationMixin
+from ...integrations import use_kernel_func_from_hub, use_kernelized_func
+from ...masking_utils import create_causal_mask, create_sliding_window_causal_mask
+from ...modeling_flash_attention_utils import FlashAttentionKwargs
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
+from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import TransformersKwargs, auto_docstring, can_return_tuple
+from ...utils.generic import maybe_autocast, merge_with_config_defaults
+from ...utils.output_capturing import capture_outputs
+from .configuration_vaultgemma import VaultGemmaConfig
+
+
+class VaultGemmaRMSNorm(nn.Module):
+ def __init__(self, dim: int, eps: float = 1e-6):
+ super().__init__()
+ self.eps = eps
+ self.weight = nn.Parameter(torch.zeros(dim))
+
+ def _norm(self, x):
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
+
+ def forward(self, x):
+ output = self._norm(x.float())
+ # Llama does x.to(float16) * w whilst VaultGemma is (x * w).to(float16)
+ # See https://github.com/huggingface/transformers/pull/29402
+ output = output * (1.0 + self.weight.float())
+ return output.type_as(x)
+
+ def extra_repr(self):
+ return f"{tuple(self.weight.shape)}, eps={self.eps}"
+
+
+class VaultGemmaMLP(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.hidden_size = config.hidden_size
+ self.intermediate_size = config.intermediate_size
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
+ self.act_fn = ACT2FN[config.hidden_activation]
+
+ def forward(self, x):
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
+ return down_proj
+
+
+def rotate_half(x):
+ """Rotates half the hidden dims of the input."""
+ x1 = x[..., : x.shape[-1] // 2]
+ x2 = x[..., x.shape[-1] // 2 :]
+ return torch.cat((-x2, x1), dim=-1)
+
+
+@use_kernel_func_from_hub("rotary_pos_emb")
+def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
+ """Applies Rotary Position Embedding to the query and key tensors.
+
+ Args:
+ q (`torch.Tensor`): The query tensor.
+ k (`torch.Tensor`): The key tensor.
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
+ Returns:
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
+ """
+ cos = cos.unsqueeze(unsqueeze_dim)
+ sin = sin.unsqueeze(unsqueeze_dim)
+ q_embed = (q * cos) + (rotate_half(q) * sin)
+ k_embed = (k * cos) + (rotate_half(k) * sin)
+ return q_embed, k_embed
+
+
+def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
+ """
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
+ """
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
+ if n_rep == 1:
+ return hidden_states
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
+
+
+def eager_attention_forward(
+ module: nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: torch.Tensor | None,
+ dropout: float | int = 0.0,
+ scaling: float | None = None,
+ softcap: float | None = None,
+ **kwargs,
+) -> tuple[torch.Tensor, torch.Tensor]:
+ if scaling is None:
+ scaling = module.head_dim**-0.5
+
+ key_states = repeat_kv(key, module.num_key_value_groups)
+ value_states = repeat_kv(value, module.num_key_value_groups)
+
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
+
+ if softcap is not None:
+ attn_weights = attn_weights / softcap
+ attn_weights = torch.tanh(attn_weights)
+ attn_weights = attn_weights * softcap
+ if attention_mask is not None:
+ attn_weights = attn_weights + attention_mask
+
+ # upcast attention to fp32
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
+ attn_output = torch.matmul(attn_weights, value_states)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+ return attn_output, attn_weights
+
+
+@use_kernelized_func(apply_rotary_pos_emb)
+class VaultGemmaAttention(nn.Module):
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
+
+ def __init__(self, config: VaultGemmaConfig, layer_idx: int):
+ super().__init__()
+ self.layer_type = config.layer_types[layer_idx] if hasattr(config, "layer_types") else None
+ self.config = config
+ self.layer_idx = layer_idx
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
+ self.scaling = config.query_pre_attn_scalar**-0.5
+ self.attention_dropout = self.config.attention_dropout
+ self.is_causal = True
+
+ self.q_proj = nn.Linear(
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
+ )
+ self.k_proj = nn.Linear(
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
+ )
+ self.v_proj = nn.Linear(
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
+ )
+ self.o_proj = nn.Linear(
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
+ )
+ self.attn_logit_softcapping = self.config.attn_logit_softcapping
+ self.sliding_window = config.sliding_window if self.layer_type == "sliding_attention" else None
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
+ attention_mask: torch.Tensor | None = None,
+ past_key_values: Cache | None = None,
+ **kwargs: Unpack[FlashAttentionKwargs],
+ ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
+ input_shape = hidden_states.shape[:-1]
+ hidden_shape = (*input_shape, -1, self.head_dim)
+
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+
+ cos, sin = position_embeddings
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
+
+ if past_key_values is not None:
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_states,
+ key_states,
+ value_states,
+ attention_mask,
+ dropout=self.attention_dropout if self.training else 0.0,
+ scaling=self.scaling,
+ sliding_window=self.sliding_window,
+ softcap=self.attn_logit_softcapping,
+ **kwargs,
+ )
+
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ attn_output = self.o_proj(attn_output)
+ return attn_output, attn_weights
+
+
+class VaultGemmaDecoderLayer(GradientCheckpointingLayer):
+ def __init__(self, config: VaultGemmaConfig, layer_idx: int):
+ super().__init__()
+ self.hidden_size = config.hidden_size
+ self.config = config
+ self.self_attn = VaultGemmaAttention(config=config, layer_idx=layer_idx)
+ self.mlp = VaultGemmaMLP(config)
+ self.input_layernorm = VaultGemmaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+
+ self.pre_feedforward_layernorm = VaultGemmaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ **kwargs,
+ ) -> tuple[torch.FloatTensor, tuple[torch.FloatTensor, torch.FloatTensor] | None]:
+ residual = hidden_states
+ hidden_states = self.input_layernorm(hidden_states)
+ # Self Attention
+ hidden_states, _ = self.self_attn(
+ hidden_states=hidden_states,
+ position_embeddings=position_embeddings,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ **kwargs,
+ )
+ hidden_states = residual + hidden_states
+
+ residual = hidden_states
+ hidden_states = self.pre_feedforward_layernorm(hidden_states)
+ hidden_states = self.mlp(hidden_states)
+ hidden_states = residual + hidden_states
+
+ return hidden_states
+
+
+class VaultGemmaRotaryEmbedding(nn.Module):
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
+
+ def __init__(self, config: VaultGemmaConfig, device=None):
+ super().__init__()
+ self.max_seq_len_cached = config.max_position_embeddings
+ self.original_max_seq_len = config.max_position_embeddings
+
+ self.config = config
+
+ self.rope_type = self.config.rope_parameters["rope_type"]
+ rope_init_fn: Callable = self.compute_default_rope_parameters
+ if self.rope_type != "default":
+ rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
+ inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
+
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
+ self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
+
+ @staticmethod
+ def compute_default_rope_parameters(
+ config: VaultGemmaConfig | None = None,
+ device: Optional["torch.device"] = None,
+ seq_len: int | None = None,
+ ) -> tuple["torch.Tensor", float]:
+ """
+ Computes the inverse frequencies according to the original RoPE implementation
+ Args:
+ config ([`~transformers.PreTrainedConfig`]):
+ The model configuration.
+ device (`torch.device`):
+ The device to use for initialization of the inverse frequencies.
+ seq_len (`int`, *optional*):
+ The current sequence length. Unused for this type of RoPE.
+ Returns:
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
+ """
+ base = config.rope_parameters["rope_theta"]
+ dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
+
+ attention_factor = 1.0 # Unused in this type of RoPE
+
+ # Compute the inverse frequencies
+ inv_freq = 1.0 / (
+ base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
+ )
+ return inv_freq, attention_factor
+
+ @torch.no_grad()
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
+ def forward(self, x, position_ids):
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
+ position_ids_expanded = position_ids[:, None, :].float()
+
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
+ with maybe_autocast(device_type=device_type, enabled=False): # Force float32
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
+ emb = torch.cat((freqs, freqs), dim=-1)
+ cos = emb.cos() * self.attention_scaling
+ sin = emb.sin() * self.attention_scaling
+
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
+
+
+class VaultGemmaTextScaledWordEmbedding(nn.Embedding):
+ """
+ This module overrides nn.Embeddings' forward by multiplying with embeddings scale.
+ """
+
+ def __init__(self, num_embeddings: int, embedding_dim: int, padding_idx: int, embed_scale: float = 1.0):
+ super().__init__(num_embeddings, embedding_dim, padding_idx)
+ self.scalar_embed_scale = embed_scale
+ self.register_buffer("embed_scale", torch.tensor(embed_scale), persistent=False)
+
+ def forward(self, input_ids: torch.Tensor):
+ return super().forward(input_ids) * self.embed_scale.to(self.weight.dtype)
+
+
+@auto_docstring
+class VaultGemmaPreTrainedModel(PreTrainedModel):
+ config: VaultGemmaConfig
+ base_model_prefix = "model"
+ supports_gradient_checkpointing = True
+ _no_split_modules = ["VaultGemmaDecoderLayer"]
+ _skip_keys_device_placement = ["past_key_values"]
+ _supports_flash_attn = True
+ _supports_sdpa = True
+ _supports_flex_attn = True
+
+ _can_compile_fullgraph = True
+ _supports_attention_backend = True
+ _can_record_outputs = {
+ "hidden_states": VaultGemmaDecoderLayer,
+ "attentions": VaultGemmaAttention,
+ }
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ super()._init_weights(module)
+ # We initialize with 0s to be 1 centered as the RMSNorm here does (1 + weight)
+ if "RMSNorm" in module.__class__.__name__:
+ init.zeros_(module.weight)
+ elif isinstance(module, VaultGemmaTextScaledWordEmbedding):
+ init.constant_(module.embed_scale, module.scalar_embed_scale)
+
+
+@auto_docstring
+class VaultGemmaModel(VaultGemmaPreTrainedModel):
+ def __init__(self, config: VaultGemmaConfig):
+ super().__init__(config)
+ self.padding_idx = config.pad_token_id
+ self.vocab_size = config.vocab_size
+ # VaultGemma3 downcasts the below to bfloat16, causing sqrt(3072)=55.4256 to become 55.5. See https://github.com/huggingface/transformers/pull/29402
+ self.embed_tokens = VaultGemmaTextScaledWordEmbedding(
+ config.vocab_size, config.hidden_size, self.padding_idx, embed_scale=self.config.hidden_size**0.5
+ )
+ self.layers = nn.ModuleList(
+ [VaultGemmaDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
+ )
+ self.norm = VaultGemmaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.rotary_emb = VaultGemmaRotaryEmbedding(config)
+ self.gradient_checkpointing = False
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @merge_with_config_defaults
+ @capture_outputs
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ use_cache: bool | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> BaseModelOutputWithPast:
+ if (input_ids is None) ^ (inputs_embeds is not None):
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
+
+ if inputs_embeds is None:
+ inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)
+
+ if use_cache and past_key_values is None:
+ past_key_values = DynamicCache(config=self.config)
+
+ if position_ids is None:
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
+ position_ids = position_ids.unsqueeze(0)
+
+ # It may already have been prepared by e.g. `generate`
+ if not isinstance(causal_mask_mapping := attention_mask, dict):
+ # Prepare mask arguments
+ mask_kwargs = {
+ "config": self.config,
+ "inputs_embeds": inputs_embeds,
+ "attention_mask": attention_mask,
+ "past_key_values": past_key_values,
+ "position_ids": position_ids,
+ }
+ # Create the masks
+ causal_mask_mapping = {
+ "full_attention": create_causal_mask(**mask_kwargs),
+ "sliding_attention": create_sliding_window_causal_mask(**mask_kwargs),
+ }
+
+ # embed positions
+ hidden_states = inputs_embeds
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
+
+ for i, decoder_layer in enumerate(self.layers[: self.config.num_hidden_layers]):
+ hidden_states = decoder_layer(
+ hidden_states,
+ attention_mask=causal_mask_mapping[self.config.layer_types[i]],
+ position_embeddings=position_embeddings,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ **kwargs,
+ )
+
+ hidden_states = self.norm(hidden_states)
+
+ return BaseModelOutputWithPast(
+ last_hidden_state=hidden_states,
+ past_key_values=past_key_values,
+ )
+
+
+@auto_docstring
+class VaultGemmaForCausalLM(VaultGemmaPreTrainedModel, GenerationMixin):
+ _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
+ _tp_plan = {"lm_head": "colwise_gather_output"}
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
+
+ def __init__(self, config):
+ super().__init__(config)
+ self.model = VaultGemmaModel(config)
+ self.vocab_size = config.vocab_size
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ use_cache: bool | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> CausalLMOutputWithPast:
+ r"""
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, VaultGemmaForCausalLM
+
+ >>> model = VaultGemmaForCausalLM.from_pretrained("google/gemma-2-9b")
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/gemma-2-9b")
+
+ >>> prompt = "What is your favorite condiment?"
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
+
+ >>> # Generate
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
+ "What is your favorite condiment?"
+ ```"""
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
+ outputs: BaseModelOutputWithPast = self.model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ **kwargs,
+ )
+
+ hidden_states = outputs.last_hidden_state
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
+ if self.config.final_logit_softcapping is not None:
+ logits = logits / self.config.final_logit_softcapping
+ logits = torch.tanh(logits)
+ logits = logits * self.config.final_logit_softcapping
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
+
+ return CausalLMOutputWithPast(
+ loss=loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+__all__ = ["VaultGemmaForCausalLM", "VaultGemmaModel", "VaultGemmaPreTrainedModel"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/vaultgemma/modular_vaultgemma.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/vaultgemma/modular_vaultgemma.py
new file mode 100644
index 0000000000000000000000000000000000000000..9a4ce67c9a553c5124ff2997defd008a86260f8f
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/vaultgemma/modular_vaultgemma.py
@@ -0,0 +1,110 @@
+# Copyright 2025 the HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+import torch
+from huggingface_hub.dataclasses import strict
+
+from ...cache_utils import Cache
+from ...utils import auto_docstring
+from ..gemma2.configuration_gemma2 import Gemma2Config
+from ..gemma2.modeling_gemma2 import Gemma2Attention, Gemma2DecoderLayer, Gemma2ForCausalLM, Gemma2MLP, Gemma2RMSNorm
+
+
+@auto_docstring(checkpoint="google/vaultgemma-1b")
+@strict
+class VaultGemmaConfig(Gemma2Config):
+ r"""
+ query_pre_attn_scalar (`float`, *optional*, defaults to 256):
+ scaling factor used on the attention scores
+ final_logit_softcapping (`float`, *optional*, defaults to 30.0):
+ scaling factor when applying tanh softcapping on the logits.
+ attn_logit_softcapping (`float`, *optional*, defaults to 50.0):
+ scaling factor when applying tanh softcapping on the attention scores.
+
+ ```python
+ >>> from transformers import VaultGemmaModel, VaultGemmaConfig
+ >>> # Initializing a VaultGemma vaultgemma-7b style configuration
+ >>> configuration = VaultGemmaConfig()
+ >>> # Initializing a model from the vaultgemma-7b style configuration
+ >>> model = VaultGemmaModel(configuration)
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ use_bidirectional_attention = AttributeError()
+
+
+class VaultGemmaRMSNorm(Gemma2RMSNorm):
+ pass
+
+
+class VaultGemmaMLP(Gemma2MLP):
+ pass
+
+
+class VaultGemmaAttention(Gemma2Attention):
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
+
+ def __init__(self, config: VaultGemmaConfig, layer_idx: int):
+ super().__init__()
+ self.is_causal = True
+
+
+class VaultGemmaDecoderLayer(Gemma2DecoderLayer):
+ def __init__(self, **super_kwargs):
+ super().__init__(**super_kwargs)
+ del self.post_attention_layernorm
+ del self.post_feedforward_layernorm
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ **kwargs,
+ ) -> tuple[torch.FloatTensor, tuple[torch.FloatTensor, torch.FloatTensor] | None]:
+ residual = hidden_states
+ hidden_states = self.input_layernorm(hidden_states)
+ # Self Attention
+ hidden_states, _ = self.self_attn(
+ hidden_states=hidden_states,
+ position_embeddings=position_embeddings,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ **kwargs,
+ )
+ hidden_states = residual + hidden_states
+
+ residual = hidden_states
+ hidden_states = self.pre_feedforward_layernorm(hidden_states)
+ hidden_states = self.mlp(hidden_states)
+ hidden_states = residual + hidden_states
+
+ return hidden_states
+
+
+class VaultGemmaForCausalLM(Gemma2ForCausalLM):
+ pass
+
+
+__all__ = [
+ "VaultGemmaConfig",
+ "VaultGemmaForCausalLM",
+ "VaultGemmaModel", # noqa: F822
+ "VaultGemmaPreTrainedModel", # noqa: F822
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/vibevoice_acoustic_tokenizer/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/vibevoice_acoustic_tokenizer/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..8c79b85ae96cff49e5c38362b248925b802d8e95
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/vibevoice_acoustic_tokenizer/__init__.py
@@ -0,0 +1,28 @@
+# Copyright 2026 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_vibevoice_acoustic_tokenizer import *
+ from .feature_extraction_vibevoice_acoustic_tokenizer import *
+ from .modeling_vibevoice_acoustic_tokenizer import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/vibevoice_acoustic_tokenizer/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/vibevoice_acoustic_tokenizer/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6fecaef124b7f5b42d3ba6efd929a0474fbef915
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/vibevoice_acoustic_tokenizer/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/vibevoice_acoustic_tokenizer/__pycache__/configuration_vibevoice_acoustic_tokenizer.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/vibevoice_acoustic_tokenizer/__pycache__/configuration_vibevoice_acoustic_tokenizer.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6bc8c24abc51160af50568854e62e5b4cc992462
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/vibevoice_acoustic_tokenizer/__pycache__/configuration_vibevoice_acoustic_tokenizer.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/vibevoice_acoustic_tokenizer/__pycache__/feature_extraction_vibevoice_acoustic_tokenizer.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/vibevoice_acoustic_tokenizer/__pycache__/feature_extraction_vibevoice_acoustic_tokenizer.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5b39aee6c1c9e52b75205714d6da891536b3fd29
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/vibevoice_acoustic_tokenizer/__pycache__/feature_extraction_vibevoice_acoustic_tokenizer.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/vibevoice_acoustic_tokenizer/__pycache__/modeling_vibevoice_acoustic_tokenizer.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/vibevoice_acoustic_tokenizer/__pycache__/modeling_vibevoice_acoustic_tokenizer.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..59e34ef981f7e803fe6a83694b4e40c3c554f9db
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/vibevoice_acoustic_tokenizer/__pycache__/modeling_vibevoice_acoustic_tokenizer.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/vibevoice_acoustic_tokenizer/__pycache__/modular_vibevoice_acoustic_tokenizer.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/vibevoice_acoustic_tokenizer/__pycache__/modular_vibevoice_acoustic_tokenizer.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..069f9efae0b71801036be55730071f8659c5325e
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/vibevoice_acoustic_tokenizer/__pycache__/modular_vibevoice_acoustic_tokenizer.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/vibevoice_acoustic_tokenizer/configuration_vibevoice_acoustic_tokenizer.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/vibevoice_acoustic_tokenizer/configuration_vibevoice_acoustic_tokenizer.py
new file mode 100644
index 0000000000000000000000000000000000000000..68601f82dc7f2ef92c019a897358ee571403e766
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/vibevoice_acoustic_tokenizer/configuration_vibevoice_acoustic_tokenizer.py
@@ -0,0 +1,162 @@
+# Copyright 2026 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+import math
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring
+
+
+@auto_docstring(checkpoint="microsoft/VibeVoice-1.5B")
+@strict
+class VibeVoiceAcousticTokenizerConfig(PreTrainedConfig):
+ r"""
+ channels (`int`, *optional*, defaults to 1):
+ Number of input channels.
+ hidden_size (`int`, *optional*, defaults to 64):
+ Dimensionality of latent representations.
+ kernel_size (`int`, *optional*, defaults to 7):
+ Kernel size for convolutional layers.
+ num_filters (`int`, *optional*, defaults to 32):
+ Number of filters in initial convolutional layer, and doubles after each downsampling.
+ downsampling_ratios (`List[int]`, *optional*, defaults to `[2, 2, 4, 5, 5, 8]`):
+ Downsampling ratios for each layer.
+ depths (`List[int]`, *optional*, defaults to `[3, 3, 3, 3, 3, 3, 8]`):
+ Number of ConvNeXt blocks at each stage.
+ ffn_expansion (`int`, *optional*, defaults to 4):
+ Expansion factor for feed-forward networks.
+ vae_std (`float`, *optional*, defaults to 0.625):
+ Standard deviation used for VAE sampling after encoder.
+
+ Example:
+
+ ```python
+ >>> from transformers import VibeVoiceAcousticTokenizerModel, VibeVoiceAcousticTokenizerConfig
+
+ >>> # Initializing a VibeVoice Acoustic Tokenizer configuration
+ >>> configuration = VibeVoiceAcousticTokenizerConfig()
+
+ >>> # Initializing a model (with random weights)
+ >>> model = VibeVoiceAcousticTokenizerModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "vibevoice_acoustic_tokenizer"
+
+ channels: int = 1
+ hidden_size: int = 64
+ kernel_size: int = 7
+ rms_norm_eps: float = 1e-5
+ layer_scale_init_value: float = 1e-6
+ initializer_range: float = 1e-2
+ num_filters: int = 32
+ downsampling_ratios: list[int] | tuple[int, ...] = (2, 2, 4, 5, 5, 8)
+ depths: list[int] | tuple[int, ...] = (3, 3, 3, 3, 3, 3, 8)
+ hidden_act: str = "gelu"
+ ffn_expansion: int = 4
+ vae_std: float = 0.625
+
+ @property
+ def hop_length(self):
+ return int(math.prod(self.downsampling_ratios))
+
+ @property
+ def encoder_config(self):
+ return VibeVoiceAcousticTokenizerEncoderConfig(**self.to_dict())
+
+ @property
+ def decoder_config(self):
+ config_dict = self.to_dict()
+ config_dict["depths"] = list(reversed(config_dict["depths"]))
+ return VibeVoiceAcousticTokenizerDecoderConfig(**config_dict)
+
+
+@auto_docstring(checkpoint="microsoft/VibeVoice-1.5B")
+@strict
+class VibeVoiceAcousticTokenizerEncoderConfig(VibeVoiceAcousticTokenizerConfig):
+ r"""
+ channels (`int`, *optional*, defaults to 1):
+ Number of input channels.
+ hidden_size (`int`, *optional*, defaults to 64):
+ Dimensionality of latent representations.
+ kernel_size (`int`, *optional*, defaults to 7):
+ Kernel size for convolutional layers.
+ num_filters (`int`, *optional*, defaults to 32):
+ Number of filters in initial convolutional layer, and doubles after each downsampling.
+ downsampling_ratios (`List[int]`, *optional*, defaults to `[2, 2, 4, 5, 5, 8]`):
+ Downsampling ratios for each layer.
+ depths (`List[int]`, *optional*, defaults to `[3, 3, 3, 3, 3, 3, 8]`):
+ Number of ConvNeXt blocks at each stage.
+ ffn_expansion (`int`, *optional*, defaults to 4):
+ Expansion factor for feed-forward networks.
+ vae_std (`float`, *optional*, defaults to 0.625):
+ Standard deviation used for VAE sampling after encoder.
+ """
+
+ model_type = "vibevoice_acoustic_tokenizer_encoder"
+ base_config_key = "encoder_config"
+
+ @property
+ def encoder_config(self):
+ return None
+
+
+@auto_docstring(checkpoint="microsoft/VibeVoice-1.5B")
+@strict
+class VibeVoiceAcousticTokenizerDecoderConfig(VibeVoiceAcousticTokenizerConfig):
+ r"""
+ channels (`int`, *optional*, defaults to 1):
+ Number of input channels.
+ hidden_size (`int`, *optional*, defaults to 64):
+ Dimensionality of latent representations.
+ kernel_size (`int`, *optional*, defaults to 7):
+ Kernel size for convolutional layers.
+ num_filters (`int`, *optional*, defaults to 32):
+ Number of filters in initial convolutional layer, and doubles after each downsampling.
+ downsampling_ratios (`List[int]`, *optional*, defaults to `[2, 2, 4, 5, 5, 8]`):
+ Downsampling ratios for each layer.
+ depths (`List[int]`, *optional*, defaults to `[3, 3, 3, 3, 3, 3, 8]`):
+ Number of ConvNeXt blocks at each stage.
+ ffn_expansion (`int`, *optional*, defaults to 4):
+ Expansion factor for feed-forward networks.
+ vae_std (`float`, *optional*, defaults to 0.625):
+ Standard deviation used for VAE sampling after encoder.
+ """
+
+ model_type = "vibevoice_acoustic_tokenizer_decoder"
+ base_config_key = "decoder_config"
+
+ @property
+ def encoder_config(self):
+ return None
+
+ @property
+ def decoder_config(self):
+ return None
+
+ @property
+ def upsampling_ratios(self):
+ return list(reversed(self.downsampling_ratios))
+
+
+__all__ = [
+ "VibeVoiceAcousticTokenizerConfig",
+ "VibeVoiceAcousticTokenizerEncoderConfig",
+ "VibeVoiceAcousticTokenizerDecoderConfig",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/vibevoice_acoustic_tokenizer/feature_extraction_vibevoice_acoustic_tokenizer.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/vibevoice_acoustic_tokenizer/feature_extraction_vibevoice_acoustic_tokenizer.py
new file mode 100644
index 0000000000000000000000000000000000000000..859dc58e5873406f584d88d88ca92fe8f4378e27
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/vibevoice_acoustic_tokenizer/feature_extraction_vibevoice_acoustic_tokenizer.py
@@ -0,0 +1,151 @@
+# Copyright 2026 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from ...audio_utils import AudioInput, make_list_of_audio
+from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
+from ...feature_extraction_utils import BatchFeature
+from ...utils import PaddingStrategy, logging
+from ...utils.import_utils import is_torch_available, requires
+
+
+if is_torch_available():
+ import torch
+
+logger = logging.get_logger(__name__)
+
+
+@requires(backends=("torch",))
+class VibeVoiceAcousticTokenizerFeatureExtractor(SequenceFeatureExtractor):
+ r"""
+ Constructs a VibeVoiceAcousticTokenizer feature extractor.
+
+ Args:
+ feature_size (`int`, *optional*, defaults to 1):
+ The number of channels.
+ sampling_rate (`int`, *optional*, defaults to 24000):
+ The sampling rate at which the audio waveform should be digitalized, expressed in hertz (Hz).
+ padding_value (`float`, *optional*, defaults to 0.0):
+ The value that is used for padding.
+ normalize_audio (`bool`, *optional*, defaults to `True`):
+ Whether to normalize audio to a target dB FS.
+ target_dB_FS (`float`, *optional*, defaults to -25):
+ Target dB FS for normalization.
+ eps (`float`, *optional*, defaults to 1e-06):
+ A small value to avoid division by zero when normalizing.
+
+ """
+
+ model_input_names = ["input_values", "padding_mask"]
+
+ def __init__(
+ self,
+ feature_size=1,
+ sampling_rate=24000,
+ padding_value=0.0,
+ normalize_audio=True,
+ target_dB_FS=-25,
+ eps=1e-6,
+ **kwargs,
+ ):
+ super().__init__(feature_size=feature_size, sampling_rate=sampling_rate, padding_value=padding_value, **kwargs)
+
+ self.normalize_audio = normalize_audio
+ self.target_dB_FS = target_dB_FS
+ self.eps = eps
+
+ def __call__(
+ self,
+ audio: AudioInput,
+ sampling_rate: int | None = None,
+ padding: bool | str | PaddingStrategy | None = True,
+ pad_to_multiple_of: int | None = None,
+ max_length: int | None = None,
+ return_attention_mask: bool | None = True,
+ return_tensors: str | None = "pt",
+ **kwargs,
+ ) -> BatchFeature:
+ """
+ Args:
+ audio (`np.ndarray`, `torch.Tensor`, `list[np.ndarray]`, `list[torch.Tensor]`:
+ The sequence or batch of sequences to be processed. Each sequence can be a numpy array, a torch tensor,
+ a list of numpy arrays or a list of torch tensors.
+ sampling_rate (`int`, *optional*):
+ The sampling rate at which the `audio` input was sampled. It is strongly recommended to pass
+ `sampling_rate` at the forward call to prevent silent errors.
+ padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `True`):
+ Select a strategy to pad the returned sequences (according to the model's padding side and padding
+ index) among:
+
+ - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
+ sequence if provided).
+ - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
+ acceptable input length for the model if that argument is not provided.
+ - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
+ lengths).
+ pad_to_multiple_of (`int`, *optional*):
+ If set will pad the sequence to a multiple of the provided value.
+
+ """
+ if sampling_rate is not None:
+ if sampling_rate != self.sampling_rate:
+ raise ValueError(
+ f"The model corresponding to this feature extractor: {self} was trained using a sampling rate of"
+ f" {self.sampling_rate}. Please make sure that the provided audio input was sampled with"
+ f" {self.sampling_rate} and not {sampling_rate}."
+ )
+ else:
+ logger.warning(
+ f"It is strongly recommended to pass the `sampling_rate` argument to `{self.__class__.__name__}()`. "
+ "Failing to do so can result in silent errors that might be hard to debug."
+ )
+
+ if return_tensors != "pt":
+ raise ValueError(f"{self.__class__.__name__} only supports `return_tensors='pt'`.")
+
+ # Ensure batch of mono tensors
+ audio = make_list_of_audio(audio)
+ for idx, example in enumerate(audio):
+ example = torch.tensor(example, dtype=torch.float32)
+ if example.ndim != 1:
+ raise ValueError(f"Audio should be mono, got shape: {example.shape}")
+ audio[idx] = example
+
+ if self.normalize_audio:
+ for idx, example in enumerate(audio):
+ rms = torch.sqrt(torch.mean(example**2))
+ example *= 10 ** (self.target_dB_FS / 20) / (rms + self.eps)
+ max_val = torch.max(torch.abs(example))
+ if max_val > 1.0:
+ example = example / (max_val + self.eps)
+ audio[idx] = example
+
+ output_values = BatchFeature({"input_values": audio})
+ if padding or pad_to_multiple_of:
+ output_values = self.pad(
+ output_values,
+ padding=padding,
+ pad_to_multiple_of=pad_to_multiple_of,
+ return_attention_mask=return_attention_mask,
+ max_length=max_length,
+ )
+ if return_attention_mask:
+ output_values["padding_mask"] = output_values.pop("attention_mask")
+
+ # add channel dimension
+ output_values["input_values"] = output_values["input_values"][:, None, :]
+
+ return output_values
+
+
+__all__ = ["VibeVoiceAcousticTokenizerFeatureExtractor"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/vibevoice_acoustic_tokenizer/modeling_vibevoice_acoustic_tokenizer.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/vibevoice_acoustic_tokenizer/modeling_vibevoice_acoustic_tokenizer.py
new file mode 100644
index 0000000000000000000000000000000000000000..b3b8376bed6175c578bd141e2d4a737ad0b969ab
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/vibevoice_acoustic_tokenizer/modeling_vibevoice_acoustic_tokenizer.py
@@ -0,0 +1,577 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/vibevoice_acoustic_tokenizer/modular_vibevoice_acoustic_tokenizer.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_vibevoice_acoustic_tokenizer.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2026 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from dataclasses import dataclass
+from typing import Optional
+
+import torch
+import torch.nn as nn
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...integrations import use_kernel_forward_from_hub
+from ...modeling_utils import PreTrainedModel
+from ...utils import ModelOutput, auto_docstring, can_return_tuple, is_torchdynamo_compiling
+from ..auto.modeling_auto import AutoModel
+from .configuration_vibevoice_acoustic_tokenizer import (
+ VibeVoiceAcousticTokenizerConfig,
+ VibeVoiceAcousticTokenizerDecoderConfig,
+ VibeVoiceAcousticTokenizerEncoderConfig,
+)
+
+
+@auto_docstring
+@dataclass
+class VibeVoiceAcousticTokenizerOutput(ModelOutput):
+ r"""
+ audio (`torch.FloatTensor` of shape `(batch_size, channels, sequence_length)`):
+ Decoded audio.
+ latents (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
+ Projected latents (continuous representations for acoustic tokens) at the output of the encoder.
+ padding_cache (`VibeVoiceAcousticTokenizerConv1dPaddingCache`, *optional*, returned when `use_cache=True` is passed):
+ A [`VibeVoiceAcousticTokenizerConv1dPaddingCache`] instance containing cached convolution states for each decoder
+ layer that can be passed to subsequent forward calls.
+ """
+
+ audio: torch.FloatTensor | None = None
+ latents: torch.FloatTensor | None = None
+ padding_cache: Optional["VibeVoiceAcousticTokenizerConv1dPaddingCache"] = None
+
+
+@auto_docstring
+@dataclass
+class VibeVoiceAcousticTokenizerEncoderOutput(ModelOutput):
+ r"""
+ latents (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
+ Projected latents (continuous representations for acoustic tokens) at the output of the encoder.
+ padding_cache (`VibeVoiceAcousticTokenizerConv1dPaddingCache`, *optional*, returned when `use_cache=True` is passed):
+ A [`VibeVoiceAcousticTokenizerConv1dPaddingCache`] instance containing cached convolution states for each encoder
+ layer that can be passed to subsequent forward calls.
+ """
+
+ latents: torch.FloatTensor | None = None
+ padding_cache: Optional["VibeVoiceAcousticTokenizerConv1dPaddingCache"] = None
+
+
+@auto_docstring
+@dataclass
+class VibeVoiceAcousticTokenizerDecoderOutput(ModelOutput):
+ r"""
+ audio (`torch.FloatTensor` of shape `(batch_size, channels, sequence_length)`):
+ Decoded audio.
+ padding_cache (`VibeVoiceAcousticTokenizerConv1dPaddingCache`, *optional*, returned when `use_cache=True` is passed):
+ A [`VibeVoiceAcousticTokenizerConv1dPaddingCache`] instance containing cached convolution states for each decoder
+ layer that can be passed to subsequent forward calls.
+ """
+
+ audio: torch.FloatTensor | None = None
+ padding_cache: Optional["VibeVoiceAcousticTokenizerConv1dPaddingCache"] = None
+
+
+@use_kernel_forward_from_hub("RMSNorm")
+class VibeVoiceAcousticTokenizerRMSNorm(nn.Module):
+ def __init__(self, hidden_size, eps: float = 1e-6) -> None:
+ """
+ VibeVoiceAcousticTokenizerRMSNorm is equivalent to T5LayerNorm
+ """
+ super().__init__()
+ self.weight = nn.Parameter(torch.ones(hidden_size))
+ self.variance_epsilon = eps
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ input_dtype = hidden_states.dtype
+ hidden_states = hidden_states.to(torch.float32)
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
+ return self.weight * hidden_states.to(input_dtype)
+
+ def extra_repr(self):
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
+
+
+class VibeVoiceAcousticTokenizerFeedForward(nn.Module):
+ def __init__(self, config, hidden_size):
+ super().__init__()
+ self.linear1 = nn.Linear(hidden_size, config.ffn_expansion * hidden_size)
+ self.activation = ACT2FN[config.hidden_act]
+ self.linear2 = nn.Linear(config.ffn_expansion * hidden_size, hidden_size)
+
+ def forward(self, hidden_states):
+ return self.linear2(self.activation(self.linear1(hidden_states)))
+
+
+class VibeVoiceAcousticTokenizerConv1dCacheLayer:
+ def __init__(self):
+ self.cache: torch.Tensor | None = None
+ self.is_initialized: bool = False
+
+ def lazy_initialization(self, hidden_states, conv_module):
+ self.left_pad = conv_module.left_pad
+ self.in_channels = conv_module.in_channels
+ self.cache = torch.zeros(
+ hidden_states.shape[0],
+ self.in_channels,
+ self.left_pad,
+ device=hidden_states.device,
+ dtype=hidden_states.dtype,
+ )
+
+ if not is_torchdynamo_compiling():
+ torch._dynamo.mark_static_address(self.cache)
+
+ self.is_initialized = True
+
+ def update(self, hidden_states, conv_module=None):
+ if not self.is_initialized and conv_module is not None:
+ self.lazy_initialization(hidden_states, conv_module)
+ elif not self.is_initialized:
+ raise ValueError(
+ "VibeVoiceAcousticTokenizerConv1dCacheLayer is not initialized. Make sure to provide conv_module to the update method."
+ )
+
+ # get the padding states
+ if self.left_pad > 0:
+ shortfall = max(0, self.left_pad - hidden_states.shape[-1])
+ if shortfall > 0:
+ padding_states = torch.cat([self.cache[:, :, -shortfall:], hidden_states], dim=-1)
+ else:
+ padding_states = hidden_states[:, :, -self.left_pad :]
+ else:
+ padding_states = torch.empty(
+ hidden_states.shape[0], self.in_channels, 0, dtype=hidden_states.dtype, device=hidden_states.device
+ )
+
+ current_cache = self.cache.clone()
+ self.cache.copy_(padding_states)
+
+ return current_cache
+
+
+class VibeVoiceAcousticTokenizerConv1dPaddingCache:
+ def __init__(self):
+ self.layers = {}
+
+ def update(self, hidden_states, cache_key, conv_module):
+ if cache_key not in self.layers:
+ self.layers[cache_key] = VibeVoiceAcousticTokenizerConv1dCacheLayer()
+
+ padding_states = self.layers[cache_key].update(hidden_states, conv_module)
+ padded_hidden_states = torch.cat([padding_states, hidden_states], dim=-1)
+ return padded_hidden_states
+
+
+# TODO: @eustlb, @ebezzam this should be latter factorized with other causalconv1d (e.g. VoxtralRealtimeCausalConv1d)
+class VibeVoiceAcousticTokenizerCausalConv1d(nn.Module):
+ """Conv1d with built-in causal padding and optional streaming support through a cache."""
+
+ def __init__(
+ self,
+ in_channels: int,
+ out_channels: int,
+ kernel_size: int,
+ cache_key: str,
+ stride: int = 1,
+ dilation: int = 1,
+ groups: int = 1,
+ ):
+ super().__init__()
+ self.conv = nn.Conv1d(in_channels, out_channels, kernel_size, stride, dilation=dilation, groups=groups)
+ self.causal_padding = (kernel_size - 1) * dilation - (stride - 1)
+ if self.causal_padding < 0:
+ raise ValueError(
+ f"Invalid causal padding {self.causal_padding} for kernel_size={kernel_size}, "
+ f"dilation={dilation}, stride={stride}."
+ )
+ self.cache_key = cache_key
+ self.in_channels = in_channels
+ self.left_pad = self.causal_padding
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ padding_cache: VibeVoiceAcousticTokenizerConv1dPaddingCache | None = None,
+ ) -> torch.Tensor:
+ if padding_cache is not None:
+ hidden_states = padding_cache.update(hidden_states, self.cache_key, self)
+ else:
+ hidden_states = nn.functional.pad(hidden_states, (self.left_pad, 0))
+
+ return self.conv(hidden_states)
+
+
+class VibeVoiceAcousticTokenizerCausalConvTranspose1d(nn.Module):
+ """ConvTranspose1d with built-in causal padding and optional streaming support through a cache."""
+
+ def __init__(
+ self,
+ in_channels: int,
+ out_channels: int,
+ kernel_size: int,
+ cache_key: str,
+ stride: int = 1,
+ ):
+ super().__init__()
+ self.convtr = nn.ConvTranspose1d(in_channels, out_channels, kernel_size, stride)
+
+ self.stride = stride
+ self.cache_key = cache_key
+ self.in_channels = in_channels
+ self.padding_total = kernel_size - stride
+ self.causal_padding = kernel_size - 1
+ self.left_pad = self.causal_padding
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ padding_cache: Optional["VibeVoiceAcousticTokenizerConv1dPaddingCache"] = None,
+ ) -> torch.Tensor:
+ time_dim = hidden_states.shape[-1]
+
+ if padding_cache is not None:
+ hidden_states = padding_cache.update(hidden_states, self.cache_key, self)
+ hidden_states = self.convtr(hidden_states)
+
+ # Remove extra padding at the right side
+ if self.padding_total > 0:
+ hidden_states = hidden_states[..., : -self.padding_total]
+
+ if padding_cache is not None:
+ # For first chunk return full output, for subsequent chunks return only new output
+ expected_new_output = time_dim * self.stride
+ if hidden_states.shape[2] >= expected_new_output:
+ hidden_states = hidden_states[:, :, -expected_new_output:]
+ return hidden_states
+
+
+class VibeVoiceAcousticTokenizerConvNext1dLayer(nn.Module):
+ """ConvNeXt-like block adapted for 1D convolutions."""
+
+ def __init__(self, config, hidden_size, dilation=1, stride=1, layer_idx=None):
+ super().__init__()
+
+ self.norm = VibeVoiceAcousticTokenizerRMSNorm(hidden_size, eps=config.rms_norm_eps)
+ self.ffn_norm = VibeVoiceAcousticTokenizerRMSNorm(hidden_size, eps=config.rms_norm_eps)
+ self.ffn = VibeVoiceAcousticTokenizerFeedForward(config, hidden_size)
+ self.gamma = nn.Parameter(config.layer_scale_init_value * torch.ones(hidden_size), requires_grad=True)
+ self.ffn_gamma = nn.Parameter(config.layer_scale_init_value * torch.ones(hidden_size), requires_grad=True)
+ self.mixer = VibeVoiceAcousticTokenizerCausalConv1d(
+ in_channels=hidden_size,
+ out_channels=hidden_size,
+ kernel_size=config.kernel_size,
+ cache_key=f"convnext_layer_{layer_idx}",
+ groups=hidden_size,
+ dilation=dilation,
+ stride=stride,
+ )
+
+ def forward(self, hidden_states, padding_cache=None):
+ # mixer
+ residual = hidden_states
+ hidden_states = self.norm(hidden_states.transpose(1, 2)).transpose(1, 2)
+ hidden_states = self.mixer(hidden_states, padding_cache=padding_cache)
+ hidden_states = hidden_states * self.gamma.unsqueeze(-1)
+ hidden_states = residual + hidden_states
+
+ # ffn
+ residual = hidden_states
+ hidden_states = self.ffn_norm(hidden_states.transpose(1, 2))
+ hidden_states = self.ffn(hidden_states).transpose(1, 2)
+ hidden_states = hidden_states * self.ffn_gamma.unsqueeze(-1)
+ return residual + hidden_states
+
+
+class VibeVoiceAcousticTokenizerEncoderStem(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+
+ self.conv = VibeVoiceAcousticTokenizerCausalConv1d(
+ in_channels=config.channels,
+ out_channels=config.num_filters,
+ kernel_size=config.kernel_size,
+ cache_key="encoder_stem",
+ )
+ self.stage = nn.ModuleList(
+ [
+ VibeVoiceAcousticTokenizerConvNext1dLayer(
+ config,
+ hidden_size=config.num_filters,
+ layer_idx=layer_idx,
+ )
+ for layer_idx in range(1, config.depths[0] + 1)
+ ]
+ )
+
+ def forward(self, hidden_states, padding_cache=None):
+ hidden_states = self.conv(hidden_states, padding_cache=padding_cache)
+ for block in self.stage:
+ hidden_states = block(hidden_states, padding_cache=padding_cache)
+ return hidden_states
+
+
+class VibeVoiceAcousticTokenizerEncoderLayer(nn.Module):
+ def __init__(self, config, stage_idx):
+ super().__init__()
+
+ depth_idx = stage_idx + 1 # first depth is for stem layer
+ layer_idx = sum(depth + 1 for depth in config.depths[:depth_idx])
+ intermediate_channels = int(config.num_filters * (2 ** (depth_idx)))
+
+ self.conv = VibeVoiceAcousticTokenizerCausalConv1d(
+ in_channels=int(config.num_filters * (2**stage_idx)),
+ out_channels=intermediate_channels,
+ kernel_size=int(config.downsampling_ratios[stage_idx] * 2),
+ cache_key=f"encoder_layer_{stage_idx}",
+ stride=config.downsampling_ratios[stage_idx],
+ )
+ self.stage = nn.ModuleList(
+ [
+ VibeVoiceAcousticTokenizerConvNext1dLayer(
+ config, hidden_size=intermediate_channels, layer_idx=layer_idx + offset
+ )
+ for offset in range(1, config.depths[depth_idx] + 1)
+ ]
+ )
+
+ def forward(self, hidden_states, padding_cache=None):
+ hidden_states = self.conv(hidden_states, padding_cache=padding_cache)
+ for block in self.stage:
+ hidden_states = block(hidden_states, padding_cache=padding_cache)
+ return hidden_states
+
+
+@auto_docstring
+class VibeVoiceAcousticTokenizerPreTrainedModel(PreTrainedModel):
+ config: VibeVoiceAcousticTokenizerConfig
+ base_model_prefix = "vibevoice_acoustic_tokenizer"
+ main_input_name = "input_values"
+ _no_split_modules = ["VibeVoiceAcousticTokenizerEncoderModel", "VibeVoiceAcousticTokenizerDecoderModel"]
+
+ def _init_weights(self, module):
+ super()._init_weights(module)
+ if isinstance(module, VibeVoiceAcousticTokenizerConvNext1dLayer):
+ init.constant_(module.gamma, self.config.layer_scale_init_value)
+ init.constant_(module.ffn_gamma, self.config.layer_scale_init_value)
+
+
+class VibeVoiceAcousticTokenizerEncoderModel(VibeVoiceAcousticTokenizerPreTrainedModel):
+ config: VibeVoiceAcousticTokenizerEncoderConfig
+
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.stem = VibeVoiceAcousticTokenizerEncoderStem(config)
+ self.conv_layers = nn.ModuleList(
+ [
+ VibeVoiceAcousticTokenizerEncoderLayer(config, stage_idx)
+ for stage_idx in range(len(config.downsampling_ratios))
+ ]
+ )
+ self.head = VibeVoiceAcousticTokenizerCausalConv1d(
+ in_channels=int(config.num_filters * (2 ** len(config.downsampling_ratios))),
+ out_channels=config.hidden_size,
+ kernel_size=config.kernel_size,
+ cache_key="encoder_head",
+ )
+ self.post_init()
+
+ def forward(self, hidden_states, padding_cache=None, use_cache=False, **kwargs):
+ if use_cache and padding_cache is None:
+ padding_cache = VibeVoiceAcousticTokenizerConv1dPaddingCache()
+
+ hidden_states = self.stem(hidden_states, padding_cache=padding_cache)
+ for layer in self.conv_layers:
+ hidden_states = layer(hidden_states, padding_cache=padding_cache)
+ hidden_states = self.head(hidden_states, padding_cache=padding_cache)
+ latents = hidden_states.permute(0, 2, 1)
+ return VibeVoiceAcousticTokenizerEncoderOutput(latents=latents, padding_cache=padding_cache)
+
+
+class VibeVoiceAcousticTokenizerDecoderStem(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+
+ intermediate_channels = int(config.num_filters * 2 ** (len(config.depths) - 1))
+ self.conv = VibeVoiceAcousticTokenizerCausalConv1d(
+ in_channels=config.hidden_size,
+ out_channels=intermediate_channels,
+ kernel_size=config.kernel_size,
+ cache_key="decoder_stem",
+ )
+ self.stage = nn.ModuleList(
+ [
+ VibeVoiceAcousticTokenizerConvNext1dLayer(
+ config,
+ hidden_size=intermediate_channels,
+ layer_idx=layer_idx,
+ )
+ for layer_idx in range(1, config.depths[0] + 1)
+ ]
+ )
+
+ def forward(self, hidden_states, padding_cache=None):
+ hidden_states = self.conv(hidden_states, padding_cache=padding_cache)
+ for block in self.stage:
+ hidden_states = block(hidden_states, padding_cache=padding_cache)
+ return hidden_states
+
+
+class VibeVoiceAcousticTokenizerDecoderLayer(nn.Module):
+ def __init__(self, config, stage_idx):
+ super().__init__()
+
+ depth_idx = stage_idx + 1 # first depth is for stem layer
+ layer_idx = sum(depth + 1 for depth in config.depths[:depth_idx])
+ intermediate_channels = int(config.num_filters * (2 ** (len(config.depths) - 2 - stage_idx)))
+
+ self.convtr = VibeVoiceAcousticTokenizerCausalConvTranspose1d(
+ in_channels=int(config.num_filters * (2 ** (len(config.depths) - 1 - stage_idx))),
+ out_channels=intermediate_channels,
+ kernel_size=int(config.upsampling_ratios[stage_idx] * 2),
+ cache_key=f"decoder_layer_{stage_idx}",
+ stride=config.upsampling_ratios[stage_idx],
+ )
+ self.stage = nn.ModuleList(
+ [
+ VibeVoiceAcousticTokenizerConvNext1dLayer(
+ config, hidden_size=intermediate_channels, layer_idx=layer_idx + offset
+ )
+ for offset in range(1, config.depths[depth_idx] + 1)
+ ]
+ )
+
+ def forward(self, hidden_states, padding_cache=None):
+ hidden_states = self.convtr(hidden_states, padding_cache=padding_cache)
+ for block in self.stage:
+ hidden_states = block(hidden_states, padding_cache=padding_cache)
+ return hidden_states
+
+
+class VibeVoiceAcousticTokenizerDecoderModel(VibeVoiceAcousticTokenizerPreTrainedModel):
+ config: VibeVoiceAcousticTokenizerDecoderConfig
+
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.stem = VibeVoiceAcousticTokenizerDecoderStem(config)
+ self.conv_layers = nn.ModuleList(
+ [
+ VibeVoiceAcousticTokenizerDecoderLayer(config, stage_idx)
+ for stage_idx in range(len(config.upsampling_ratios))
+ ]
+ )
+ self.head = VibeVoiceAcousticTokenizerCausalConv1d(
+ in_channels=config.num_filters,
+ out_channels=config.channels,
+ kernel_size=config.kernel_size,
+ cache_key="decoder_head",
+ )
+ self.post_init()
+
+ def forward(self, hidden_states, padding_cache=None, use_cache=False, **kwargs):
+ if use_cache and padding_cache is None:
+ padding_cache = VibeVoiceAcousticTokenizerConv1dPaddingCache()
+
+ hidden_states = self.stem(hidden_states, padding_cache=padding_cache)
+ for layer in self.conv_layers:
+ hidden_states = layer(hidden_states, padding_cache=padding_cache)
+ hidden_states = self.head(hidden_states, padding_cache=padding_cache)
+ return VibeVoiceAcousticTokenizerDecoderOutput(audio=hidden_states, padding_cache=padding_cache)
+
+
+@auto_docstring(
+ custom_intro="""
+ VibeVoice acoustic tokenizer with an encoder and decoder for continuous acoustic tokens.
+ """
+)
+class VibeVoiceAcousticTokenizerModel(VibeVoiceAcousticTokenizerPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.encoder = AutoModel.from_config(config.encoder_config)
+ self.decoder = AutoModel.from_config(config.decoder_config)
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def encode(self, input_values, padding_cache=None, use_cache=None, sample=True):
+ r"""
+ input_values (`torch.FloatTensor` of shape `(batch_size, channels, sequence_length)`):
+ Input audio waveform to be encoded into latent representation.
+ padding_cache (`VibeVoiceAcousticTokenizerConv1dPaddingCache`, *optional*):
+ Cache object for streaming mode to maintain convolution states across layers.
+ use_cache (`bool`, *optional*):
+ Whether to use caching for convolution states.
+ sample (`bool`, *optional*):
+ Whether to sample from the VAE. If False, no noise is added.
+ """
+ encoder_output = self.encoder(input_values, padding_cache=padding_cache, use_cache=use_cache)
+
+ if sample:
+ noise_std = self.config.vae_std * torch.randn(
+ encoder_output.latents.shape[0],
+ device=encoder_output.latents.device,
+ dtype=encoder_output.latents.dtype,
+ )
+ encoder_output.latents = encoder_output.latents + noise_std[:, None, None] * torch.randn_like(
+ encoder_output.latents
+ )
+ return encoder_output
+
+ @can_return_tuple
+ @auto_docstring
+ def decode(self, latents, padding_cache=None, use_cache=False):
+ r"""
+ latents (`torch.FloatTensor` of shape `(batch_size, channels, sequence_length)`):
+ Input latent representation to be decoded back into audio.
+ padding_cache (`VibeVoiceAcousticTokenizerConv1dPaddingCache`, *optional*):
+ Cache object for streaming mode to maintain convolution states across layers.
+ use_cache (`bool`, *optional*):
+ Whether to use caching for convolution states.
+ """
+ latents = latents.permute(0, 2, 1)
+ return self.decoder(latents, padding_cache=padding_cache, use_cache=use_cache)
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(self, input_values, padding_cache=None, use_cache=False, sample=True, **kwargs):
+ r"""
+ input_values (`torch.FloatTensor` of shape `(batch_size, channels, sequence_length)`):
+ Input audio waveform to be encoded into latent representation.
+ padding_cache (`VibeVoiceAcousticTokenizerConv1dPaddingCache`, *optional*):
+ Cache object for streaming mode to maintain convolution states across layers. Note only used by decoder.
+ use_cache (`bool`, *optional*):
+ Whether to use caching for convolution states.
+ sample (`bool`, *optional*):
+ Whether to sample from the VAE latent distribution. If False, no noise is added to the latents.
+ """
+ encoder_output = self.encode(input_values, use_cache=use_cache, sample=sample)
+ decoder_output = self.decode(encoder_output.latents, padding_cache=padding_cache, use_cache=use_cache)
+ return VibeVoiceAcousticTokenizerOutput(
+ audio=decoder_output.audio,
+ latents=encoder_output.latents,
+ padding_cache=decoder_output.padding_cache,
+ )
+
+
+__all__ = [
+ "VibeVoiceAcousticTokenizerModel",
+ "VibeVoiceAcousticTokenizerEncoderModel",
+ "VibeVoiceAcousticTokenizerDecoderModel",
+ "VibeVoiceAcousticTokenizerPreTrainedModel",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/vibevoice_acoustic_tokenizer/modular_vibevoice_acoustic_tokenizer.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/vibevoice_acoustic_tokenizer/modular_vibevoice_acoustic_tokenizer.py
new file mode 100644
index 0000000000000000000000000000000000000000..5ceeacd269de421d4e377d66f292d88e5368af71
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/vibevoice_acoustic_tokenizer/modular_vibevoice_acoustic_tokenizer.py
@@ -0,0 +1,499 @@
+# Copyright 2026 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from dataclasses import dataclass
+from typing import Optional
+
+import torch
+import torch.nn as nn
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...modeling_utils import PreTrainedModel
+from ...utils import ModelOutput, auto_docstring, can_return_tuple
+from ..auto.modeling_auto import AutoModel
+from ..llama.modeling_llama import LlamaRMSNorm
+from ..voxtral_realtime.modeling_voxtral_realtime import VoxtralRealtimeConv1dPaddingCache
+from .configuration_vibevoice_acoustic_tokenizer import (
+ VibeVoiceAcousticTokenizerConfig,
+ VibeVoiceAcousticTokenizerDecoderConfig,
+ VibeVoiceAcousticTokenizerEncoderConfig,
+)
+
+
+@auto_docstring
+@dataclass
+class VibeVoiceAcousticTokenizerOutput(ModelOutput):
+ r"""
+ audio (`torch.FloatTensor` of shape `(batch_size, channels, sequence_length)`):
+ Decoded audio.
+ latents (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
+ Projected latents (continuous representations for acoustic tokens) at the output of the encoder.
+ padding_cache (`VibeVoiceAcousticTokenizerConv1dPaddingCache`, *optional*, returned when `use_cache=True` is passed):
+ A [`VibeVoiceAcousticTokenizerConv1dPaddingCache`] instance containing cached convolution states for each decoder
+ layer that can be passed to subsequent forward calls.
+ """
+
+ audio: torch.FloatTensor | None = None
+ latents: torch.FloatTensor | None = None
+ padding_cache: Optional["VibeVoiceAcousticTokenizerConv1dPaddingCache"] = None
+
+
+@auto_docstring
+@dataclass
+class VibeVoiceAcousticTokenizerEncoderOutput(ModelOutput):
+ r"""
+ latents (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
+ Projected latents (continuous representations for acoustic tokens) at the output of the encoder.
+ padding_cache (`VibeVoiceAcousticTokenizerConv1dPaddingCache`, *optional*, returned when `use_cache=True` is passed):
+ A [`VibeVoiceAcousticTokenizerConv1dPaddingCache`] instance containing cached convolution states for each encoder
+ layer that can be passed to subsequent forward calls.
+ """
+
+ latents: torch.FloatTensor | None = None
+ padding_cache: Optional["VibeVoiceAcousticTokenizerConv1dPaddingCache"] = None
+
+
+@auto_docstring
+@dataclass
+class VibeVoiceAcousticTokenizerDecoderOutput(ModelOutput):
+ r"""
+ audio (`torch.FloatTensor` of shape `(batch_size, channels, sequence_length)`):
+ Decoded audio.
+ padding_cache (`VibeVoiceAcousticTokenizerConv1dPaddingCache`, *optional*, returned when `use_cache=True` is passed):
+ A [`VibeVoiceAcousticTokenizerConv1dPaddingCache`] instance containing cached convolution states for each decoder
+ layer that can be passed to subsequent forward calls.
+ """
+
+ audio: torch.FloatTensor | None = None
+ padding_cache: Optional["VibeVoiceAcousticTokenizerConv1dPaddingCache"] = None
+
+
+class VibeVoiceAcousticTokenizerRMSNorm(LlamaRMSNorm):
+ pass
+
+
+class VibeVoiceAcousticTokenizerFeedForward(nn.Module):
+ def __init__(self, config, hidden_size):
+ super().__init__()
+ self.linear1 = nn.Linear(hidden_size, config.ffn_expansion * hidden_size)
+ self.activation = ACT2FN[config.hidden_act]
+ self.linear2 = nn.Linear(config.ffn_expansion * hidden_size, hidden_size)
+
+ def forward(self, hidden_states):
+ return self.linear2(self.activation(self.linear1(hidden_states)))
+
+
+class VibeVoiceAcousticTokenizerConv1dPaddingCache(VoxtralRealtimeConv1dPaddingCache):
+ pass
+
+
+# TODO: @eustlb, @ebezzam this should be latter factorized with other causalconv1d (e.g. VoxtralRealtimeCausalConv1d)
+class VibeVoiceAcousticTokenizerCausalConv1d(nn.Module):
+ """Conv1d with built-in causal padding and optional streaming support through a cache."""
+
+ def __init__(
+ self,
+ in_channels: int,
+ out_channels: int,
+ kernel_size: int,
+ cache_key: str,
+ stride: int = 1,
+ dilation: int = 1,
+ groups: int = 1,
+ ):
+ super().__init__()
+ self.conv = nn.Conv1d(in_channels, out_channels, kernel_size, stride, dilation=dilation, groups=groups)
+ self.causal_padding = (kernel_size - 1) * dilation - (stride - 1)
+ if self.causal_padding < 0:
+ raise ValueError(
+ f"Invalid causal padding {self.causal_padding} for kernel_size={kernel_size}, "
+ f"dilation={dilation}, stride={stride}."
+ )
+ self.cache_key = cache_key
+ self.in_channels = in_channels
+ self.left_pad = self.causal_padding
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ padding_cache: VibeVoiceAcousticTokenizerConv1dPaddingCache | None = None,
+ ) -> torch.Tensor:
+ if padding_cache is not None:
+ hidden_states = padding_cache.update(hidden_states, self.cache_key, self)
+ else:
+ hidden_states = nn.functional.pad(hidden_states, (self.left_pad, 0))
+
+ return self.conv(hidden_states)
+
+
+class VibeVoiceAcousticTokenizerCausalConvTranspose1d(nn.Module):
+ """ConvTranspose1d with built-in causal padding and optional streaming support through a cache."""
+
+ def __init__(
+ self,
+ in_channels: int,
+ out_channels: int,
+ kernel_size: int,
+ cache_key: str,
+ stride: int = 1,
+ ):
+ super().__init__()
+ self.convtr = nn.ConvTranspose1d(in_channels, out_channels, kernel_size, stride)
+
+ self.stride = stride
+ self.cache_key = cache_key
+ self.in_channels = in_channels
+ self.padding_total = kernel_size - stride
+ self.causal_padding = kernel_size - 1
+ self.left_pad = self.causal_padding
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ padding_cache: Optional["VibeVoiceAcousticTokenizerConv1dPaddingCache"] = None,
+ ) -> torch.Tensor:
+ time_dim = hidden_states.shape[-1]
+
+ if padding_cache is not None:
+ hidden_states = padding_cache.update(hidden_states, self.cache_key, self)
+ hidden_states = self.convtr(hidden_states)
+
+ # Remove extra padding at the right side
+ if self.padding_total > 0:
+ hidden_states = hidden_states[..., : -self.padding_total]
+
+ if padding_cache is not None:
+ # For first chunk return full output, for subsequent chunks return only new output
+ expected_new_output = time_dim * self.stride
+ if hidden_states.shape[2] >= expected_new_output:
+ hidden_states = hidden_states[:, :, -expected_new_output:]
+ return hidden_states
+
+
+class VibeVoiceAcousticTokenizerConvNext1dLayer(nn.Module):
+ """ConvNeXt-like block adapted for 1D convolutions."""
+
+ def __init__(self, config, hidden_size, dilation=1, stride=1, layer_idx=None):
+ super().__init__()
+
+ self.norm = VibeVoiceAcousticTokenizerRMSNorm(hidden_size, eps=config.rms_norm_eps)
+ self.ffn_norm = VibeVoiceAcousticTokenizerRMSNorm(hidden_size, eps=config.rms_norm_eps)
+ self.ffn = VibeVoiceAcousticTokenizerFeedForward(config, hidden_size)
+ self.gamma = nn.Parameter(config.layer_scale_init_value * torch.ones(hidden_size), requires_grad=True)
+ self.ffn_gamma = nn.Parameter(config.layer_scale_init_value * torch.ones(hidden_size), requires_grad=True)
+ self.mixer = VibeVoiceAcousticTokenizerCausalConv1d(
+ in_channels=hidden_size,
+ out_channels=hidden_size,
+ kernel_size=config.kernel_size,
+ cache_key=f"convnext_layer_{layer_idx}",
+ groups=hidden_size,
+ dilation=dilation,
+ stride=stride,
+ )
+
+ def forward(self, hidden_states, padding_cache=None):
+ # mixer
+ residual = hidden_states
+ hidden_states = self.norm(hidden_states.transpose(1, 2)).transpose(1, 2)
+ hidden_states = self.mixer(hidden_states, padding_cache=padding_cache)
+ hidden_states = hidden_states * self.gamma.unsqueeze(-1)
+ hidden_states = residual + hidden_states
+
+ # ffn
+ residual = hidden_states
+ hidden_states = self.ffn_norm(hidden_states.transpose(1, 2))
+ hidden_states = self.ffn(hidden_states).transpose(1, 2)
+ hidden_states = hidden_states * self.ffn_gamma.unsqueeze(-1)
+ return residual + hidden_states
+
+
+class VibeVoiceAcousticTokenizerEncoderStem(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+
+ self.conv = VibeVoiceAcousticTokenizerCausalConv1d(
+ in_channels=config.channels,
+ out_channels=config.num_filters,
+ kernel_size=config.kernel_size,
+ cache_key="encoder_stem",
+ )
+ self.stage = nn.ModuleList(
+ [
+ VibeVoiceAcousticTokenizerConvNext1dLayer(
+ config,
+ hidden_size=config.num_filters,
+ layer_idx=layer_idx,
+ )
+ for layer_idx in range(1, config.depths[0] + 1)
+ ]
+ )
+
+ def forward(self, hidden_states, padding_cache=None):
+ hidden_states = self.conv(hidden_states, padding_cache=padding_cache)
+ for block in self.stage:
+ hidden_states = block(hidden_states, padding_cache=padding_cache)
+ return hidden_states
+
+
+class VibeVoiceAcousticTokenizerEncoderLayer(nn.Module):
+ def __init__(self, config, stage_idx):
+ super().__init__()
+
+ depth_idx = stage_idx + 1 # first depth is for stem layer
+ layer_idx = sum(depth + 1 for depth in config.depths[:depth_idx])
+ intermediate_channels = int(config.num_filters * (2 ** (depth_idx)))
+
+ self.conv = VibeVoiceAcousticTokenizerCausalConv1d(
+ in_channels=int(config.num_filters * (2**stage_idx)),
+ out_channels=intermediate_channels,
+ kernel_size=int(config.downsampling_ratios[stage_idx] * 2),
+ cache_key=f"encoder_layer_{stage_idx}",
+ stride=config.downsampling_ratios[stage_idx],
+ )
+ self.stage = nn.ModuleList(
+ [
+ VibeVoiceAcousticTokenizerConvNext1dLayer(
+ config, hidden_size=intermediate_channels, layer_idx=layer_idx + offset
+ )
+ for offset in range(1, config.depths[depth_idx] + 1)
+ ]
+ )
+
+ def forward(self, hidden_states, padding_cache=None):
+ hidden_states = self.conv(hidden_states, padding_cache=padding_cache)
+ for block in self.stage:
+ hidden_states = block(hidden_states, padding_cache=padding_cache)
+ return hidden_states
+
+
+@auto_docstring
+class VibeVoiceAcousticTokenizerPreTrainedModel(PreTrainedModel):
+ config: VibeVoiceAcousticTokenizerConfig
+ base_model_prefix = "vibevoice_acoustic_tokenizer"
+ main_input_name = "input_values"
+ _no_split_modules = ["VibeVoiceAcousticTokenizerEncoderModel", "VibeVoiceAcousticTokenizerDecoderModel"]
+
+ def _init_weights(self, module):
+ super()._init_weights(module)
+ if isinstance(module, VibeVoiceAcousticTokenizerConvNext1dLayer):
+ init.constant_(module.gamma, self.config.layer_scale_init_value)
+ init.constant_(module.ffn_gamma, self.config.layer_scale_init_value)
+
+
+class VibeVoiceAcousticTokenizerEncoderModel(VibeVoiceAcousticTokenizerPreTrainedModel):
+ config: VibeVoiceAcousticTokenizerEncoderConfig
+
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.stem = VibeVoiceAcousticTokenizerEncoderStem(config)
+ self.conv_layers = nn.ModuleList(
+ [
+ VibeVoiceAcousticTokenizerEncoderLayer(config, stage_idx)
+ for stage_idx in range(len(config.downsampling_ratios))
+ ]
+ )
+ self.head = VibeVoiceAcousticTokenizerCausalConv1d(
+ in_channels=int(config.num_filters * (2 ** len(config.downsampling_ratios))),
+ out_channels=config.hidden_size,
+ kernel_size=config.kernel_size,
+ cache_key="encoder_head",
+ )
+ self.post_init()
+
+ def forward(self, hidden_states, padding_cache=None, use_cache=False, **kwargs):
+ if use_cache and padding_cache is None:
+ padding_cache = VibeVoiceAcousticTokenizerConv1dPaddingCache()
+
+ hidden_states = self.stem(hidden_states, padding_cache=padding_cache)
+ for layer in self.conv_layers:
+ hidden_states = layer(hidden_states, padding_cache=padding_cache)
+ hidden_states = self.head(hidden_states, padding_cache=padding_cache)
+ latents = hidden_states.permute(0, 2, 1)
+ return VibeVoiceAcousticTokenizerEncoderOutput(latents=latents, padding_cache=padding_cache)
+
+
+class VibeVoiceAcousticTokenizerDecoderStem(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+
+ intermediate_channels = int(config.num_filters * 2 ** (len(config.depths) - 1))
+ self.conv = VibeVoiceAcousticTokenizerCausalConv1d(
+ in_channels=config.hidden_size,
+ out_channels=intermediate_channels,
+ kernel_size=config.kernel_size,
+ cache_key="decoder_stem",
+ )
+ self.stage = nn.ModuleList(
+ [
+ VibeVoiceAcousticTokenizerConvNext1dLayer(
+ config,
+ hidden_size=intermediate_channels,
+ layer_idx=layer_idx,
+ )
+ for layer_idx in range(1, config.depths[0] + 1)
+ ]
+ )
+
+ def forward(self, hidden_states, padding_cache=None):
+ hidden_states = self.conv(hidden_states, padding_cache=padding_cache)
+ for block in self.stage:
+ hidden_states = block(hidden_states, padding_cache=padding_cache)
+ return hidden_states
+
+
+class VibeVoiceAcousticTokenizerDecoderLayer(nn.Module):
+ def __init__(self, config, stage_idx):
+ super().__init__()
+
+ depth_idx = stage_idx + 1 # first depth is for stem layer
+ layer_idx = sum(depth + 1 for depth in config.depths[:depth_idx])
+ intermediate_channels = int(config.num_filters * (2 ** (len(config.depths) - 2 - stage_idx)))
+
+ self.convtr = VibeVoiceAcousticTokenizerCausalConvTranspose1d(
+ in_channels=int(config.num_filters * (2 ** (len(config.depths) - 1 - stage_idx))),
+ out_channels=intermediate_channels,
+ kernel_size=int(config.upsampling_ratios[stage_idx] * 2),
+ cache_key=f"decoder_layer_{stage_idx}",
+ stride=config.upsampling_ratios[stage_idx],
+ )
+ self.stage = nn.ModuleList(
+ [
+ VibeVoiceAcousticTokenizerConvNext1dLayer(
+ config, hidden_size=intermediate_channels, layer_idx=layer_idx + offset
+ )
+ for offset in range(1, config.depths[depth_idx] + 1)
+ ]
+ )
+
+ def forward(self, hidden_states, padding_cache=None):
+ hidden_states = self.convtr(hidden_states, padding_cache=padding_cache)
+ for block in self.stage:
+ hidden_states = block(hidden_states, padding_cache=padding_cache)
+ return hidden_states
+
+
+class VibeVoiceAcousticTokenizerDecoderModel(VibeVoiceAcousticTokenizerPreTrainedModel):
+ config: VibeVoiceAcousticTokenizerDecoderConfig
+
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.stem = VibeVoiceAcousticTokenizerDecoderStem(config)
+ self.conv_layers = nn.ModuleList(
+ [
+ VibeVoiceAcousticTokenizerDecoderLayer(config, stage_idx)
+ for stage_idx in range(len(config.upsampling_ratios))
+ ]
+ )
+ self.head = VibeVoiceAcousticTokenizerCausalConv1d(
+ in_channels=config.num_filters,
+ out_channels=config.channels,
+ kernel_size=config.kernel_size,
+ cache_key="decoder_head",
+ )
+ self.post_init()
+
+ def forward(self, hidden_states, padding_cache=None, use_cache=False, **kwargs):
+ if use_cache and padding_cache is None:
+ padding_cache = VibeVoiceAcousticTokenizerConv1dPaddingCache()
+
+ hidden_states = self.stem(hidden_states, padding_cache=padding_cache)
+ for layer in self.conv_layers:
+ hidden_states = layer(hidden_states, padding_cache=padding_cache)
+ hidden_states = self.head(hidden_states, padding_cache=padding_cache)
+ return VibeVoiceAcousticTokenizerDecoderOutput(audio=hidden_states, padding_cache=padding_cache)
+
+
+@auto_docstring(
+ custom_intro="""
+ VibeVoice acoustic tokenizer with an encoder and decoder for continuous acoustic tokens.
+ """
+)
+class VibeVoiceAcousticTokenizerModel(VibeVoiceAcousticTokenizerPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.encoder = AutoModel.from_config(config.encoder_config)
+ self.decoder = AutoModel.from_config(config.decoder_config)
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def encode(self, input_values, padding_cache=None, use_cache=None, sample=True):
+ r"""
+ input_values (`torch.FloatTensor` of shape `(batch_size, channels, sequence_length)`):
+ Input audio waveform to be encoded into latent representation.
+ padding_cache (`VibeVoiceAcousticTokenizerConv1dPaddingCache`, *optional*):
+ Cache object for streaming mode to maintain convolution states across layers.
+ use_cache (`bool`, *optional*):
+ Whether to use caching for convolution states.
+ sample (`bool`, *optional*):
+ Whether to sample from the VAE. If False, no noise is added.
+ """
+ encoder_output = self.encoder(input_values, padding_cache=padding_cache, use_cache=use_cache)
+
+ if sample:
+ noise_std = self.config.vae_std * torch.randn(
+ encoder_output.latents.shape[0],
+ device=encoder_output.latents.device,
+ dtype=encoder_output.latents.dtype,
+ )
+ encoder_output.latents = encoder_output.latents + noise_std[:, None, None] * torch.randn_like(
+ encoder_output.latents
+ )
+ return encoder_output
+
+ @can_return_tuple
+ @auto_docstring
+ def decode(self, latents, padding_cache=None, use_cache=False):
+ r"""
+ latents (`torch.FloatTensor` of shape `(batch_size, channels, sequence_length)`):
+ Input latent representation to be decoded back into audio.
+ padding_cache (`VibeVoiceAcousticTokenizerConv1dPaddingCache`, *optional*):
+ Cache object for streaming mode to maintain convolution states across layers.
+ use_cache (`bool`, *optional*):
+ Whether to use caching for convolution states.
+ """
+ latents = latents.permute(0, 2, 1)
+ return self.decoder(latents, padding_cache=padding_cache, use_cache=use_cache)
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(self, input_values, padding_cache=None, use_cache=False, sample=True, **kwargs):
+ r"""
+ input_values (`torch.FloatTensor` of shape `(batch_size, channels, sequence_length)`):
+ Input audio waveform to be encoded into latent representation.
+ padding_cache (`VibeVoiceAcousticTokenizerConv1dPaddingCache`, *optional*):
+ Cache object for streaming mode to maintain convolution states across layers. Note only used by decoder.
+ use_cache (`bool`, *optional*):
+ Whether to use caching for convolution states.
+ sample (`bool`, *optional*):
+ Whether to sample from the VAE latent distribution. If False, no noise is added to the latents.
+ """
+ encoder_output = self.encode(input_values, use_cache=use_cache, sample=sample)
+ decoder_output = self.decode(encoder_output.latents, padding_cache=padding_cache, use_cache=use_cache)
+ return VibeVoiceAcousticTokenizerOutput(
+ audio=decoder_output.audio,
+ latents=encoder_output.latents,
+ padding_cache=decoder_output.padding_cache,
+ )
+
+
+__all__ = [
+ "VibeVoiceAcousticTokenizerModel",
+ "VibeVoiceAcousticTokenizerEncoderModel",
+ "VibeVoiceAcousticTokenizerDecoderModel",
+ "VibeVoiceAcousticTokenizerPreTrainedModel",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/video_llava/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/video_llava/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..bb5f5971a167997ffc89de76d5cc5ba3d8216b4b
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/video_llava/__init__.py
@@ -0,0 +1,29 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_video_llava import *
+ from .image_processing_video_llava import *
+ from .modeling_video_llava import *
+ from .processing_video_llava import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/video_llava/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/video_llava/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2cd60d4729ce50148e6eab8770820460cb9195b7
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/video_llava/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/video_llava/__pycache__/configuration_video_llava.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/video_llava/__pycache__/configuration_video_llava.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cf079c248ffe80f45bba6008e8e477ae813d8452
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/video_llava/__pycache__/configuration_video_llava.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/video_llava/__pycache__/image_processing_video_llava.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/video_llava/__pycache__/image_processing_video_llava.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d0364caf69480cd2178c438b3b77967c93ba4e31
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/video_llava/__pycache__/image_processing_video_llava.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/video_llava/__pycache__/modeling_video_llava.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/video_llava/__pycache__/modeling_video_llava.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f666ec818ffcaa0293cad2b0ad8d84cff9cd3bf0
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/video_llava/__pycache__/modeling_video_llava.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/video_llava/__pycache__/processing_video_llava.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/video_llava/__pycache__/processing_video_llava.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..71501a2950d2d073e5cf1a4d16d7daf780c5533f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/video_llava/__pycache__/processing_video_llava.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/video_llava/__pycache__/video_processing_video_llava.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/video_llava/__pycache__/video_processing_video_llava.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..21fdb90f20468cf0b25ec8a5e1f3b28a01777370
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/video_llava/__pycache__/video_processing_video_llava.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/video_llava/configuration_video_llava.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/video_llava/configuration_video_llava.py
new file mode 100644
index 0000000000000000000000000000000000000000..8b02aa2a24bf351104e2637e9ffb9125fb53ebaa
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/video_llava/configuration_video_llava.py
@@ -0,0 +1,100 @@
+# Copyright 2024 Microsoft Research & University of Wisconsin-Madison and the HuggingFace Inc. team. All rights reserved.
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""VideoLlava model configuration"""
+
+from typing import Literal
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring, logging
+from ..auto import CONFIG_MAPPING, AutoConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+@auto_docstring(checkpoint="LanguageBind/Video-LLaVA-7B-hf")
+@strict
+class VideoLlavaConfig(PreTrainedConfig):
+ r"""
+ Example:
+
+ ```python
+ >>> from transformers import VideoLlavaForConditionalGeneration, VideoLlavaConfig, CLIPVisionConfig, LlamaConfig
+
+ >>> # Initializing a CLIP-vision config
+ >>> vision_config = CLIPVisionConfig()
+
+ >>> # Initializing a Llama config
+ >>> text_config = LlamaConfig()
+
+ >>> # Initializing a VideoLlava video_llava-1.5-7b style configuration
+ >>> configuration = VideoLlavaConfig(vision_config, text_config)
+
+ >>> # Initializing a model from the video_llava-1.5-7b style configuration
+ >>> model = VideoLlavaForConditionalGeneration(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "video_llava"
+ attribute_map = {
+ "image_token_id": "image_token_index",
+ "video_token_id": "video_token_index",
+ }
+ sub_configs = {"text_config": AutoConfig, "vision_config": AutoConfig}
+
+ vision_config: dict | PreTrainedConfig | None = None
+ text_config: dict | PreTrainedConfig | None = None
+ image_token_index: int = 32000
+ video_token_index: int = 32001
+ projector_hidden_act: str = "gelu"
+ vision_feature_select_strategy: Literal["default", "full"] = "default"
+ vision_feature_layer: int | list[int] = -2
+ image_seq_length: int = 256
+ video_seq_length: int = 2056
+ multimodal_projector_bias: bool = True
+ tie_word_embeddings: bool = False
+
+ def __post_init__(self, **kwargs):
+ if isinstance(self.vision_config, dict):
+ if "model_type" not in self.vision_config:
+ self.vision_config["model_type"] = "clip_vision_model"
+ logger.warning("Key=`model_type` not found in vision config, setting it to `clip_vision_model`")
+ self.vision_config = CONFIG_MAPPING[self.vision_config["model_type"]](**self.vision_config)
+ elif self.vision_config is None:
+ self.vision_config = CONFIG_MAPPING["clip_vision_model"](
+ intermediate_size=4096,
+ hidden_size=1024,
+ patch_size=14,
+ image_size=224,
+ num_hidden_layers=24,
+ num_attention_heads=16,
+ vocab_size=32000,
+ projection_dim=768,
+ )
+
+ if isinstance(self.text_config, dict):
+ if "model_type" not in self.text_config:
+ self.text_config["model_type"] = "llama"
+ logger.warning("Key=`model_type` not found in text config, setting it to `llama`")
+ self.text_config = CONFIG_MAPPING[self.text_config["model_type"]](**self.text_config)
+ elif self.text_config is None:
+ self.text_config = CONFIG_MAPPING["llama"]()
+
+ super().__post_init__(**kwargs)
+
+
+__all__ = ["VideoLlavaConfig"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/video_llava/image_processing_video_llava.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/video_llava/image_processing_video_llava.py
new file mode 100644
index 0000000000000000000000000000000000000000..d462a00d026022575663cfb1491c6c37c4dc8eb9
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/video_llava/image_processing_video_llava.py
@@ -0,0 +1,344 @@
+# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Image processor class for Video-LLaVA."""
+
+import numpy as np
+
+from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
+from ...image_transforms import (
+ convert_to_rgb,
+ get_resize_output_image_size,
+ resize,
+ to_channel_dimension_format,
+)
+from ...image_utils import (
+ OPENAI_CLIP_MEAN,
+ OPENAI_CLIP_STD,
+ ChannelDimension,
+ ImageInput,
+ PILImageResampling,
+ infer_channel_dimension_format,
+ is_scaled_image,
+ make_flat_list_of_images,
+ to_numpy_array,
+ valid_images,
+ validate_preprocess_arguments,
+)
+from ...utils import TensorType, filter_out_non_signature_kwargs, logging
+
+
+logger = logging.get_logger(__name__)
+
+
+class VideoLlavaImageProcessor(BaseImageProcessor):
+ r"""
+ Constructs a CLIP image processor.
+
+ Args:
+ do_resize (`bool`, *optional*, defaults to `True`):
+ Whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden by
+ `do_resize` in the `preprocess` method.
+ size (`dict[str, int]` *optional*, defaults to `{"shortest_edge": 224}`):
+ Size of the image after resizing. The shortest edge of the image is resized to size["shortest_edge"], with
+ the longest edge resized to keep the input aspect ratio. Can be overridden by `size` in the `preprocess`
+ method.
+ resample (`PILImageResampling`, *optional*, defaults to `Resampling.BICUBIC`):
+ Resampling filter to use if resizing the image. Can be overridden by `resample` in the `preprocess` method.
+ do_center_crop (`bool`, *optional*, defaults to `True`):
+ Whether to center crop the image to the specified `crop_size`. Can be overridden by `do_center_crop` in the
+ `preprocess` method.
+ crop_size (`dict[str, int]` *optional*, defaults to 224):
+ Size of the output image after applying `center_crop`. Can be overridden by `crop_size` in the `preprocess`
+ method.
+ do_rescale (`bool`, *optional*, defaults to `True`):
+ Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by `do_rescale` in
+ the `preprocess` method.
+ rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
+ Scale factor to use if rescaling the image. Can be overridden by `rescale_factor` in the `preprocess`
+ method.
+ do_normalize (`bool`, *optional*, defaults to `True`):
+ Whether to normalize the image. Can be overridden by `do_normalize` in the `preprocess` method.
+ image_mean (`float` or `list[float]`, *optional*, defaults to `[0.48145466, 0.4578275, 0.40821073]`):
+ Mean to use if normalizing the image. This is a float or list of floats the length of the number of
+ channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method.
+ image_std (`float` or `list[float]`, *optional*, defaults to `[0.26862954, 0.26130258, 0.27577711]`):
+ Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
+ number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
+ Can be overridden by the `image_std` parameter in the `preprocess` method.
+ do_convert_rgb (`bool`, *optional*, defaults to `True`):
+ Whether to convert the image to RGB.
+ """
+
+ model_input_names = ["pixel_values"]
+
+ def __init__(
+ self,
+ do_resize: bool = True,
+ size: dict[str, int] | None = None,
+ resample: PILImageResampling = PILImageResampling.BICUBIC,
+ do_center_crop: bool = True,
+ crop_size: dict[str, int] | None = None,
+ do_rescale: bool = True,
+ rescale_factor: int | float = 1 / 255,
+ do_normalize: bool = True,
+ image_mean: float | list[float] | None = None,
+ image_std: float | list[float] | None = None,
+ do_convert_rgb: bool = True,
+ **kwargs,
+ ) -> None:
+ super().__init__(**kwargs)
+ size = size if size is not None else {"shortest_edge": 224}
+ size = get_size_dict(size, default_to_square=False)
+ crop_size = crop_size if crop_size is not None else {"height": 224, "width": 224}
+ crop_size = get_size_dict(crop_size, default_to_square=True, param_name="crop_size")
+
+ self.do_resize = do_resize
+ self.size = size
+ self.resample = resample
+ self.do_center_crop = do_center_crop
+ self.crop_size = crop_size
+ self.do_rescale = do_rescale
+ self.rescale_factor = rescale_factor
+ self.do_normalize = do_normalize
+ self.image_mean = image_mean if image_mean is not None else OPENAI_CLIP_MEAN
+ self.image_std = image_std if image_std is not None else OPENAI_CLIP_STD
+ self.do_convert_rgb = do_convert_rgb
+
+ def resize(
+ self,
+ image: np.ndarray,
+ size: dict[str, int],
+ resample: PILImageResampling = PILImageResampling.BICUBIC,
+ data_format: str | ChannelDimension | None = None,
+ input_data_format: str | ChannelDimension | None = None,
+ **kwargs,
+ ) -> np.ndarray:
+ """
+ Resize an image. The shortest edge of the image is resized to size["shortest_edge"], with the longest edge
+ resized to keep the input aspect ratio.
+
+ Args:
+ image (`np.ndarray`):
+ Image to resize.
+ size (`dict[str, int]`):
+ Size of the output image.
+ resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):
+ Resampling filter to use when resiizing the image.
+ data_format (`str` or `ChannelDimension`, *optional*):
+ The channel dimension format of the image. If not provided, it will be the same as the input image.
+ input_data_format (`ChannelDimension` or `str`, *optional*):
+ The channel dimension format of the input image. If not provided, it will be inferred.
+ """
+ default_to_square = True
+ if "shortest_edge" in size:
+ size = size["shortest_edge"]
+ default_to_square = False
+ elif "height" in size and "width" in size:
+ size = (size["height"], size["width"])
+ else:
+ raise ValueError("Size must contain either 'shortest_edge' or 'height' and 'width'.")
+
+ output_size = get_resize_output_image_size(
+ image,
+ size=size,
+ default_to_square=default_to_square,
+ input_data_format=input_data_format,
+ )
+ return resize(
+ image,
+ size=output_size,
+ resample=resample,
+ data_format=data_format,
+ input_data_format=input_data_format,
+ **kwargs,
+ )
+
+ @filter_out_non_signature_kwargs()
+ def preprocess(
+ self,
+ images: list[ImageInput] | None = None,
+ do_resize: bool | None = None,
+ size: dict[str, int] | None = None,
+ resample: PILImageResampling | None = None,
+ do_center_crop: bool | None = None,
+ crop_size: int | None = None,
+ do_rescale: bool | None = None,
+ rescale_factor: float | None = None,
+ do_normalize: bool | None = None,
+ image_mean: float | list[float] | None = None,
+ image_std: float | list[float] | None = None,
+ do_convert_rgb: bool | None = None,
+ return_tensors: str | TensorType | None = None,
+ data_format: ChannelDimension | None = ChannelDimension.FIRST,
+ input_data_format: str | ChannelDimension | None = None,
+ ) -> BatchFeature:
+ """
+ Preprocess an image or batch of images.
+
+ Args:
+ images (`ImageInput`, *optional*):
+ List of images to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
+ passing in images with pixel values between 0 and 1, set `do_rescale=False`.
+ do_resize (`bool`, *optional*, defaults to `self.do_resize`):
+ Whether to resize the image.
+ size (`dict[str, int]`, *optional*, defaults to `self.size`):
+ Size of the image after resizing. Shortest edge of the image is resized to size["shortest_edge"], with
+ the longest edge resized to keep the input aspect ratio.
+ resample (`int`, *optional*, defaults to `self.resample`):
+ Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`. Only
+ has an effect if `do_resize` is set to `True`.
+ do_center_crop (`bool`, *optional*, defaults to `self.do_center_crop`):
+ Whether to center crop the image.
+ crop_size (`dict[str, int]`, *optional*, defaults to `self.crop_size`):
+ Size of the center crop. Only has an effect if `do_center_crop` is set to `True`.
+ do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
+ Whether to rescale the image.
+ rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
+ Rescale factor to rescale the image by if `do_rescale` is set to `True`.
+ do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
+ Whether to normalize the image.
+ image_mean (`float` or `list[float]`, *optional*, defaults to `self.image_mean`):
+ Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`.
+ image_std (`float` or `list[float]`, *optional*, defaults to `self.image_std`):
+ Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to
+ `True`.
+ do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):
+ Whether to convert the image to RGB.
+ return_tensors (`str` or `TensorType`, *optional*):
+ The type of tensors to return. Can be one of:
+ - Unset: Return a list of `np.ndarray`.
+ - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
+ - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
+ data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
+ The channel dimension format for the output image. Can be one of:
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
+ - Unset: Use the channel dimension format of the input image.
+ input_data_format (`ChannelDimension` or `str`, *optional*):
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
+ from the input image. Can be one of:
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
+ """
+ do_resize = do_resize if do_resize is not None else self.do_resize
+ size = size if size is not None else self.size
+ size = get_size_dict(size, param_name="size", default_to_square=False)
+ resample = resample if resample is not None else self.resample
+ do_center_crop = do_center_crop if do_center_crop is not None else self.do_center_crop
+ crop_size = crop_size if crop_size is not None else self.crop_size
+ crop_size = get_size_dict(crop_size, param_name="crop_size", default_to_square=True)
+ do_rescale = do_rescale if do_rescale is not None else self.do_rescale
+ rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
+ do_normalize = do_normalize if do_normalize is not None else self.do_normalize
+ image_mean = image_mean if image_mean is not None else self.image_mean
+ image_std = image_std if image_std is not None else self.image_std
+ do_convert_rgb = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
+
+ if images is not None:
+ images = self.fetch_images(images)
+ images = make_flat_list_of_images(images)
+
+ if images is not None and not valid_images(images):
+ raise ValueError("Invalid input type. Must be of type PIL.Image.Image, numpy.ndarray, or torch.Tensor")
+
+ pixel_values_images = [
+ self._preprocess_image(
+ image=image,
+ do_resize=do_resize,
+ size=size,
+ resample=resample,
+ do_rescale=do_rescale,
+ rescale_factor=rescale_factor,
+ do_normalize=do_normalize,
+ image_mean=image_mean,
+ image_std=image_std,
+ do_center_crop=do_center_crop,
+ crop_size=crop_size,
+ do_convert_rgb=do_convert_rgb,
+ data_format=data_format,
+ input_data_format=input_data_format,
+ )
+ for image in images
+ ]
+ data = {"pixel_values_images": pixel_values_images}
+ encoded_outputs = BatchFeature(data, tensor_type=return_tensors)
+
+ return encoded_outputs
+
+ def _preprocess_image(
+ self,
+ image: ImageInput | None = None,
+ do_resize: bool | None = None,
+ size: dict[str, int] | None = None,
+ resample: PILImageResampling | None = None,
+ do_rescale: bool | None = None,
+ rescale_factor: float | None = None,
+ do_normalize: bool | None = None,
+ image_mean: float | list[float] | None = None,
+ image_std: float | list[float] | None = None,
+ do_center_crop: bool | None = None,
+ crop_size: int | None = None,
+ do_convert_rgb: bool | None = None,
+ data_format: ChannelDimension = ChannelDimension.FIRST,
+ input_data_format: str | ChannelDimension | None = None,
+ ) -> np.ndarray:
+ validate_preprocess_arguments(
+ do_rescale=do_rescale,
+ rescale_factor=rescale_factor,
+ do_normalize=do_normalize,
+ image_mean=image_mean,
+ image_std=image_std,
+ do_center_crop=do_center_crop,
+ crop_size=crop_size,
+ do_resize=do_resize,
+ size=size,
+ resample=resample,
+ )
+
+ # PIL RGBA images are converted to RGB
+ if do_convert_rgb:
+ image = convert_to_rgb(image)
+
+ # All transformations expect numpy arrays.
+ image = to_numpy_array(image)
+
+ if do_rescale and is_scaled_image(image):
+ logger.warning_once(
+ "It looks like you are trying to rescale already rescaled images/video frames. If the input"
+ " images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
+ )
+
+ if input_data_format is None:
+ # We assume that all images have the same channel dimension format.
+ input_data_format = infer_channel_dimension_format(image)
+
+ if do_resize:
+ image = self.resize(image=image, size=size, resample=resample, input_data_format=input_data_format)
+
+ if do_center_crop:
+ image = self.center_crop(image=image, size=crop_size, input_data_format=input_data_format)
+
+ if do_rescale:
+ image = self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)
+
+ if do_normalize:
+ image = self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format)
+
+ image = to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)
+
+ return image
+
+
+__all__ = ["VideoLlavaImageProcessor"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/video_llava/modeling_video_llava.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/video_llava/modeling_video_llava.py
new file mode 100644
index 0000000000000000000000000000000000000000..a14ee23172bc59302ff5fb8bb3b566bbc0a9cd05
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/transformers/models/video_llava/modeling_video_llava.py
@@ -0,0 +1,579 @@
+# Copyright 2024 the HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch VideoLlava model."""
+
+from dataclasses import dataclass
+
+import torch
+from torch import nn
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...cache_utils import Cache
+from ...generation import GenerationMixin
+from ...modeling_flash_attention_utils import FlashAttentionKwargs
+from ...modeling_outputs import BaseModelOutputWithPooling, ModelOutput
+from ...modeling_utils import PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import TransformersKwargs, auto_docstring, logging, torch_compilable_check
+from ...utils.generic import can_return_tuple, merge_with_config_defaults
+from ..auto import AutoModel
+from .configuration_video_llava import VideoLlavaConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+@auto_docstring(
+ custom_intro="""
+ Base class for VideoLlava base model outputs.
+ """
+)
+@dataclass
+class VideoLlavaModelOutputWithPast(ModelOutput):
+ r"""
+ past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
+ It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
+
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
+ `past_key_values` input) to speed up sequential decoding.
+ image_hidden_states (`torch.FloatTensor`, *optional*):
+ A `torch.FloatTensor` of size (batch_size, num_images, sequence_length, hidden_size)`.
+ image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
+ video_hidden_states (`torch.FloatTensor`, *optional*):
+ A `torch.FloatTensor` of size `(batch_size * num_frames, num_videos, sequence_length, hidden_size)`.
+ video_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
+ """
+
+ last_hidden_state: torch.FloatTensor | None = None
+ past_key_values: Cache | None = None
+ hidden_states: tuple[torch.FloatTensor] | None = None
+ attentions: tuple[torch.FloatTensor] | None = None
+ image_hidden_states: torch.FloatTensor | None = None
+ video_hidden_states: torch.FloatTensor | None = None
+
+
+@auto_docstring(
+ custom_intro="""
+ Base class for VideoLlava causal language model (or autoregressive) outputs.
+ """
+)
+@dataclass
+class VideoLlavaCausalLMOutputWithPast(ModelOutput):
+ r"""
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
+ Language modeling loss (for next-token prediction).
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
+ past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
+ It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
+
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
+ `past_key_values` input) to speed up sequential decoding.
+ image_hidden_states (`torch.FloatTensor`, *optional*):
+ A `torch.FloatTensor` of size (batch_size, num_images, sequence_length, hidden_size)`.
+ image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
+ video_hidden_states (`torch.FloatTensor`, *optional*):
+ A `torch.FloatTensor` of size `(batch_size * num_frames, num_videos, sequence_length, hidden_size)`.
+ video_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
+ """
+
+ loss: torch.FloatTensor | None = None
+ logits: torch.FloatTensor | None = None
+ past_key_values: Cache | None = None
+ hidden_states: tuple[torch.FloatTensor] | None = None
+ attentions: tuple[torch.FloatTensor] | None = None
+ image_hidden_states: torch.FloatTensor | None = None
+ video_hidden_states: torch.FloatTensor | None = None
+
+
+# Copied from transformers.models.llava.modeling_llava.LlavaMultiModalProjector with Llava->VideoLlava
+class VideoLlavaMultiModalProjector(nn.Module):
+ def __init__(self, config: VideoLlavaConfig):
+ super().__init__()
+ # We have hidden_size * the number of vision feature layers
+ num_feature_layers = 1 if isinstance(config.vision_feature_layer, int) else len(config.vision_feature_layer)
+ self.linear_1 = nn.Linear(
+ config.vision_config.hidden_size * num_feature_layers,
+ config.text_config.hidden_size,
+ bias=config.multimodal_projector_bias,
+ )
+ self.act = ACT2FN[config.projector_hidden_act]
+ self.linear_2 = nn.Linear(
+ config.text_config.hidden_size, config.text_config.hidden_size, bias=config.multimodal_projector_bias
+ )
+
+ def forward(self, image_features):
+ hidden_states = self.linear_1(image_features)
+ hidden_states = self.act(hidden_states)
+ hidden_states = self.linear_2(hidden_states)
+ return hidden_states
+
+
+@auto_docstring
+class VideoLlavaPreTrainedModel(PreTrainedModel):
+ config: VideoLlavaConfig
+ base_model_prefix = "model"
+ input_modalities = ("image", "video", "text")
+ supports_gradient_checkpointing = True
+ _no_split_modules = ["VideoLlavaVisionAttention"]
+ _skip_keys_device_placement = ["past_key_values"]
+ _supports_flash_attn = True
+ _supports_sdpa = True
+ _can_compile_fullgraph = True
+ _supports_attention_backend = True
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ super()._init_weights(module)
+ std = (
+ self.config.initializer_range
+ if hasattr(self.config, "initializer_range")
+ else self.config.text_config.initializer_range
+ )
+ if hasattr(module, "class_embedding"):
+ init.normal_(module.class_embedding, mean=0.0, std=std)
+
+
+@auto_docstring(
+ custom_intro="""
+ The VideoLlava model which consists of a vision backbone and a language model without language modeling head.
+ """,
+)
+class VideoLlavaModel(VideoLlavaPreTrainedModel):
+ def __init__(self, config: VideoLlavaConfig):
+ super().__init__(config)
+ self.video_tower = AutoModel.from_config(config.vision_config)
+ self.image_tower = AutoModel.from_config(config.vision_config)
+
+ self.multi_modal_projector = VideoLlavaMultiModalProjector(config)
+ self.vocab_size = config.text_config.vocab_size
+ self.language_model = AutoModel.from_config(config.text_config)
+ self.post_init()
+
+ @merge_with_config_defaults
+ @can_return_tuple
+ @auto_docstring(
+ custom_intro="Obtains image last hidden states from the vision tower and apply multimodal projection."
+ )
+ def get_image_features(
+ self,
+ pixel_values_images: torch.FloatTensor,
+ vision_feature_layer: int | list[int] | list[int] | None = None,
+ vision_feature_select_strategy: str | None = None,
+ output_hidden_states: bool | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutputWithPooling:
+ r"""
+ pixel_values_images (`torch.FloatTensor]` of shape `(batch_size, channels, height, width)`)
+ The tensors corresponding to the input images.
+ vision_feature_layer (`Union[int, list[int]]`, *optional*):
+ The index of the layer to select the vision feature. If multiple indices are provided,
+ the vision feature of the corresponding indices will be concatenated to form the
+ vision features.
+ vision_feature_select_strategy (`str`, *optional*):
+ The feature selection strategy used to select the vision feature from the vision backbone.
+ Can be one of `"default"` or `"full"`
+ """
+ image_outputs = self.image_tower(
+ pixel_values_images,
+ output_hidden_states=True, # Ignore arg on purpose
+ return_dict=True,
+ **kwargs,
+ )
+
+ # If we have one vision feature layer, return the corresponding hidden states,
+ # otherwise, select the hidden states of each feature layer and concatenate them
+ if isinstance(vision_feature_layer, int):
+ selected_hidden_state = image_outputs.hidden_states[vision_feature_layer]
+ if vision_feature_select_strategy == "default":
+ selected_hidden_state = selected_hidden_state[:, 1:]
+ else:
+ hs_pool = [image_outputs.hidden_states[layer_idx] for layer_idx in vision_feature_layer]
+ # For default; crop CLS from each hidden state in the hidden state pool
+ if vision_feature_select_strategy == "default":
+ hs_pool = [hs[:, 1:] for hs in hs_pool]
+ selected_hidden_state = torch.cat(hs_pool, dim=-1)
+
+ image_features = self.multi_modal_projector(selected_hidden_state)
+ image_outputs.pooler_output = image_features
+
+ return image_outputs
+
+ @merge_with_config_defaults
+ @can_return_tuple
+ @auto_docstring(
+ custom_intro="Obtains video last hidden states from the vision tower and apply multimodal projection."
+ )
+ def get_video_features(
+ self,
+ pixel_values_videos: torch.FloatTensor,
+ vision_feature_layer: int | list[int] | list[int] | None = None,
+ output_hidden_states: bool | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutputWithPooling:
+ r"""
+ pixel_values_videos (`torch.FloatTensor]` of shape `(batch_size, num_frames, channels, height, width)`)
+ The tensors corresponding to the input videos.
+ vision_feature_layer (`Union[int, list[int]]`, *optional*):
+ The index of the layer to select the vision feature. If multiple indices are provided,
+ the vision feature of the corresponding indices will be concatenated to form the
+ vision features.
+ """
+ batch_size_vid, num_frames, channels, height, width = pixel_values_videos.shape
+
+ pixel_values = pixel_values_videos.reshape(batch_size_vid * num_frames, channels, height, width)
+ video_outputs = self.video_tower(
+ pixel_values,
+ output_hidden_states=True, # Ignore arg on purpose
+ return_dict=True,
+ **kwargs,
+ )
+
+ # If we have one vision feature layer, return the corresponding hidden states,
+ # otherwise, select the hidden states of each feature layer and concatenate them
+ if isinstance(vision_feature_layer, int):
+ video_features = video_outputs.hidden_states[vision_feature_layer]
+ else:
+ hs_pool = [video_outputs.hidden_states[layer_idx] for layer_idx in vision_feature_layer]
+ video_features = torch.cat(hs_pool, dim=-1)
+
+ video_features = self.multi_modal_projector(video_features)
+ video_outputs.pooler_output = video_features
+
+ return video_outputs
+
+ def get_placeholder_mask(
+ self,
+ input_ids: torch.LongTensor,
+ inputs_embeds: torch.FloatTensor,
+ image_features: torch.FloatTensor | None = None,
+ video_features: torch.FloatTensor | None = None,
+ ):
+ """
+ Obtains multimodal placeholder mask from `input_ids` or `inputs_embeds`, and checks that the placeholder token count is
+ equal to the length of multimodal features. If the lengths are different, an error is raised.
+ """
+ if input_ids is None:
+ special_image_mask = inputs_embeds == self.get_input_embeddings()(
+ torch.tensor(self.config.image_token_id, dtype=torch.long, device=inputs_embeds.device)
+ )
+ special_image_mask = special_image_mask.all(-1)
+ special_video_mask = inputs_embeds == self.get_input_embeddings()(
+ torch.tensor(self.config.video_token_id, dtype=torch.long, device=inputs_embeds.device)
+ )
+ special_video_mask = special_video_mask.all(-1)
+ else:
+ special_image_mask = input_ids == self.config.image_token_id
+ special_video_mask = input_ids == self.config.video_token_id
+
+ n_image_tokens = special_image_mask.sum()
+ special_image_mask = special_image_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
+ if image_features is not None:
+ torch_compilable_check(
+ inputs_embeds[special_image_mask].numel() == image_features.numel(),
+ f"Image features and image tokens do not match, tokens: {n_image_tokens}, features: {image_features.shape[0] * image_features.shape[1]}",
+ )
+
+ n_video_tokens = special_video_mask.sum()
+ special_video_mask = special_video_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
+ if video_features is not None:
+ torch_compilable_check(
+ inputs_embeds[special_video_mask].numel() == video_features.numel(),
+ f"Video features and video tokens do not match, tokens: {n_video_tokens}, features: {video_features.shape[0] * video_features.shape[1]}",
+ )
+ return special_image_mask, special_video_mask
+
+ @merge_with_config_defaults
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ pixel_values_images: torch.FloatTensor | None = None,
+ pixel_values_videos: torch.FloatTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ vision_feature_layer: int | list[int] | list[int] | None = None,
+ vision_feature_select_strategy: str | None = None,
+ use_cache: bool | None = None,
+ **kwargs: Unpack[FlashAttentionKwargs],
+ ) -> tuple | VideoLlavaModelOutputWithPast:
+ r"""
+ pixel_values_images (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)):
+ The tensors corresponding to the input images. Pixel values can be obtained using
+ [`AutoImageProcessor`]. See [`VideoLlavaImageProcessor.__call__`] for details ([]`LlavaProcessor`] uses
+ [`VideoLlavaImageProcessor`] for processing images).
+ """
+ if (input_ids is None) ^ (inputs_embeds is not None):
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
+
+ if inputs_embeds is None:
+ inputs_embeds = self.get_input_embeddings()(input_ids)
+
+ if pixel_values_images is not None:
+ image_features = self.get_image_features(
+ pixel_values_images,
+ vision_feature_layer=vision_feature_layer,
+ vision_feature_select_strategy=vision_feature_select_strategy,
+ return_dict=True,
+ ).pooler_output
+ image_features = image_features.to(inputs_embeds.device, inputs_embeds.dtype)
+ special_image_mask, _ = self.get_placeholder_mask(
+ input_ids, inputs_embeds=inputs_embeds, image_features=image_features
+ )
+ inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)
+
+ if pixel_values_videos is not None:
+ video_features = self.get_video_features(
+ pixel_values_videos=pixel_values_videos, vision_feature_layer=vision_feature_layer, return_dict=True
+ ).pooler_output
+ video_features = video_features.to(inputs_embeds.device, inputs_embeds.dtype)
+ _, special_video_mask = self.get_placeholder_mask(
+ input_ids, inputs_embeds=inputs_embeds, video_features=video_features
+ )
+ inputs_embeds = inputs_embeds.masked_scatter(special_video_mask, video_features)
+
+ outputs = self.language_model(
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ **kwargs,
+ )
+
+ return VideoLlavaModelOutputWithPast(
+ last_hidden_state=outputs.last_hidden_state,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ image_hidden_states=image_features if pixel_values_images is not None else None,
+ video_hidden_states=video_features if pixel_values_videos is not None else None,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ The VideoLlava model which consists of a vision backbone and a language model.
+ """
+)
+class VideoLlavaForConditionalGeneration(VideoLlavaPreTrainedModel, GenerationMixin):
+ _tied_weights_keys = {"lm_head.weight": "model.language_model.embed_tokens.weight"}
+
+ def __init__(self, config: VideoLlavaConfig):
+ super().__init__(config)
+ self.model = VideoLlavaModel(config)
+ self.lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.vocab_size, bias=False)
+ self.post_init()
+
+ def get_output_embeddings(self) -> nn.Module:
+ return self.lm_head
+
+ @merge_with_config_defaults
+ @can_return_tuple
+ @auto_docstring
+ def get_image_features(
+ self,
+ pixel_values_images: torch.FloatTensor,
+ vision_feature_layer: int | list[int] | list[int] | None = None,
+ vision_feature_select_strategy: str | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutputWithPooling:
+ r"""
+ pixel_values_images (`torch.FloatTensor]` of shape `(batch_size, channels, height, width)`)
+ The tensors corresponding to the input images.
+ vision_feature_layer (`Union[int, list[int]]`, *optional*):
+ The index of the layer to select the vision feature. If multiple indices are provided,
+ the vision feature of the corresponding indices will be concatenated to form the
+ vision features.
+ vision_feature_select_strategy (`str`, *optional*):
+ The feature selection strategy used to select the vision feature from the vision backbone.
+ Can be one of `"default"` or `"full"`
+ """
+ return self.model.get_image_features(
+ pixel_values_images=pixel_values_images,
+ vision_feature_layer=vision_feature_layer,
+ vision_feature_select_strategy=vision_feature_select_strategy,
+ **kwargs,
+ )
+
+ @merge_with_config_defaults
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ pixel_values_images: torch.FloatTensor | None = None,
+ pixel_values_videos: torch.FloatTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: Cache | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ vision_feature_layer: int | list[int] | list[int] | None = None,
+ vision_feature_select_strategy: str | None = None,
+ labels: torch.LongTensor | None = None,
+ use_cache: bool | None = None,
+ logits_to_keep: int | torch.Tensor = 0,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | VideoLlavaCausalLMOutputWithPast:
+ r"""
+ pixel_values_images (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)):
+ The tensors corresponding to the input images. Pixel values can be obtained using
+ [`AutoImageProcessor`]. See [`VideoLlavaImageProcessor.__call__`] for details ([]`LlavaProcessor`] uses
+ [`VideoLlavaImageProcessor`] for processing images).
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
+
+ Example:
+
+ ```python
+ >>> from PIL import Image
+ >>> import httpx
+ >>> from io import BytesIO
+ >>> import numpy as np
+ >>> import av
+ >>> from huggingface_hub import hf_hub_download
+ >>> from transformers import VideoLlavaProcessor, VideoLlavaForConditionalGeneration
+
+ >>> def read_video_pyav(container, indices):
+ ... '''
+ ... Decode the video with PyAV decoder.
+ ... Args:
+ ... container (`av.container.input.InputContainer`): PyAV container.
+ ... indices (`list[int]`): List of frame indices to decode.
+ ... Returns:
+ ... result (np.ndarray): np array of decoded frames of shape (num_frames, height, width, 3).
+ ... '''
+ ... frames = []
+ ... container.seek(0)
+ ... start_index = indices[0]
+ ... end_index = indices[-1]
+ ... for i, frame in enumerate(container.decode(video=0)):
+ ... if i > end_index:
+ ... break
+ ... if i >= start_index and i in indices:
+ ... frames.append(frame)
+ ... return np.stack([x.to_ndarray(format="rgb24") for x in frames])
+
+ >>> model = VideoLlavaForConditionalGeneration.from_pretrained("LanguageBind/Video-LLaVA-7B-hf")
+ >>> processor = VideoLlavaProcessor.from_pretrained("LanguageBind/Video-LLaVA-7B-hf")
+
+ >>> prompt = "USER: