JinghuiLuAstronaut commited on
Commit
1fbeba4
·
verified ·
1 Parent(s): a8878fc

Add files using upload-large-folder tool

Browse files
Files changed (20) hide show
  1. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/hiera/__init__.py +27 -0
  2. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/hiera/configuration_hiera.py +122 -0
  3. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/hiera/modeling_hiera.py +1398 -0
  4. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/hyperclovax/__init__.py +27 -0
  5. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/hyperclovax/configuration_hyperclovax.py +134 -0
  6. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/hyperclovax/modeling_hyperclovax.py +526 -0
  7. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/ibert/__init__.py +27 -0
  8. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/ibert/configuration_ibert.py +62 -0
  9. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/ibert/modeling_ibert.py +1202 -0
  10. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/mobilevitv2/__init__.py +27 -0
  11. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/mobilevitv2/modeling_mobilevitv2.py +942 -0
  12. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/musicgen_melody/__init__.py +27 -0
  13. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/musicgen_melody/feature_extraction_musicgen_melody.py +334 -0
  14. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/musicgen_melody/modeling_musicgen_melody.py +0 -0
  15. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/wav2vec2_phoneme/__init__.py +26 -0
  16. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/wav2vec2_phoneme/tokenization_wav2vec2_phoneme.py +581 -0
  17. LTA_openwebtext_dualt/mini_owt_logdirichlet/logs/debug_articlefull_elfopt_shared_wheel.log +49 -0
  18. LTA_openwebtext_dualt/mini_owt_logdirichlet/logs/infer_owt_lr3e3_bottleneck16_step552k_decode64_ema_20260615_084145.log +36 -0
  19. LTA_openwebtext_dualt/mini_owt_logdirichlet/logs/owt_llmclean_qwen36_35b_articlefull_full_rev8_4gpu_resume_20260531_013159.outer.log +0 -0
  20. LTA_openwebtext_dualt/mini_owt_logdirichlet/logs/vllm_qwen36_35b_a3b_gpu6_port8014.log +0 -0
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/hiera/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_hiera import *
22
+ from .modeling_hiera import *
23
+ else:
24
+ import sys
25
+
26
+ _file = globals()["__file__"]
27
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/hiera/configuration_hiera.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Hiera model configuration"""
15
+
16
+ from huggingface_hub.dataclasses import strict
17
+
18
+ from ...backbone_utils import BackboneConfigMixin
19
+ from ...configuration_utils import PreTrainedConfig
20
+ from ...utils import auto_docstring
21
+
22
+
23
+ @auto_docstring(checkpoint="facebook/hiera-base-224")
24
+ @strict
25
+ class HieraConfig(BackboneConfigMixin, PreTrainedConfig):
26
+ r"""
27
+ patch_stride (`list(int)`, *optional*, defaults to `[4, 4]`):
28
+ The stride of the patch.
29
+ patch_padding (`list(int)`, *optional*, defaults to `[3, 3]`):
30
+ The padding of the patch.
31
+ num_heads (`list(int)`, *optional*, defaults to `[1, 2, 4, 8]`):
32
+ Number of attention heads in each layer of the Transformer encoder.
33
+ embed_dim_multiplier (`float`, *optional*, defaults to 2.0):
34
+ The multiplier to the dimensionality of patch embedding in each layer of the Transformer encoder.
35
+ num_query_pool (`int`, *optional*, defaults to 3):
36
+ The number of query pool stages.
37
+ query_stride (`list(int)`, *optional*, defaults to `[2, 2]`):
38
+ The stride of the query pool.
39
+ masked_unit_size (`list(int)`, *optional*, defaults to `[8, 8]`):
40
+ The size of the masked unit.
41
+ masked_unit_attention (`list(bool)`, *optional*, defaults to `[True, True, False, False]`):
42
+ Whether to use masked unit attention in each layer of the Transformer encoder.
43
+ layer_norm_init (`float`, *optional*, defaults to 1.0):
44
+ The initial weight value for layer normalization layers.
45
+ decoder_depth (`int`, *optional*):
46
+ Depth of the decoder for MAE pretraining.
47
+ normalize_pixel_loss (`bool`, *optional*, defaults to `True`):
48
+ Whether to normalize the pixel loss by the number of pixels.
49
+ mask_ratio (`float`, *optional*, defaults to 0.6):
50
+ The ratio of masked tokens in the input.
51
+
52
+ Example:
53
+
54
+ ```python
55
+ >>> from transformers import HieraConfig, HieraModel
56
+
57
+ >>> # Initializing a Hiera hiera-base-patch16-224 style configuration
58
+ >>> configuration = HieraConfig()
59
+
60
+ >>> # Initializing a model (with random weights) from the hiera-base-patch16-224 style configuration
61
+ >>> model = HieraModel(configuration)
62
+
63
+ >>> # Accessing the model configuration
64
+ >>> configuration = model.config
65
+ ```"""
66
+
67
+ model_type = "hiera"
68
+
69
+ attribute_map = {"num_hidden_layers": "num_layers"}
70
+
71
+ embed_dim: int = 96
72
+ image_size: list[int] | tuple[int, ...] = (224, 224)
73
+ patch_size: list[int] | tuple[int, ...] = (7, 7)
74
+ patch_stride: list[int] | tuple[int, ...] = (4, 4)
75
+ patch_padding: list[int] | tuple[int, ...] = (3, 3)
76
+ mlp_ratio: float = 4.0
77
+ depths: list[int] | tuple[int, ...] = (2, 3, 16, 3)
78
+ num_heads: list[int] | tuple[int, ...] = (1, 2, 4, 8)
79
+ embed_dim_multiplier: float | int = 2.0
80
+ num_query_pool: int = 3
81
+ query_stride: list[int] | tuple[int, ...] = (2, 2)
82
+ masked_unit_size: list[int] | tuple[int, ...] = (8, 8)
83
+ masked_unit_attention: list[bool] | tuple[bool, ...] = (True, True, False, False)
84
+ drop_path_rate: float | int = 0.0
85
+ num_channels: int = 3
86
+ hidden_act: str = "gelu"
87
+ initializer_range: float = 0.02
88
+ layer_norm_init: float = 1.0
89
+ layer_norm_eps: float = 1e-6
90
+ decoder_hidden_size: int | None = None
91
+ decoder_depth: int | None = None
92
+ decoder_num_heads: int | None = None
93
+ normalize_pixel_loss: bool | None = True
94
+ mask_ratio: float = 0.6
95
+ _out_features: list[str] | None = None
96
+ _out_indices: list[int] | None = None
97
+
98
+ def __post_init__(self, **kwargs):
99
+ # we set the hidden_size attribute in order to make Hiera work with VisionEncoderDecoderModel
100
+ # this indicates the channel dimension after the last stage of the model
101
+ self.hidden_size = int(self.embed_dim * self.embed_dim_multiplier ** (len(self.depths) - 1))
102
+ self.stage_names = ["stem"] + [f"stage{idx}" for idx in range(1, len(self.depths) + 1)]
103
+ self.set_output_features_output_indices(
104
+ out_indices=kwargs.pop("out_indices", None), out_features=kwargs.pop("out_features", None)
105
+ )
106
+ super().__post_init__(**kwargs)
107
+
108
+ def validate_architecture(self):
109
+ """Part of `@strict`-powered validation. Validates the architecture of the config."""
110
+ if self.masked_unit_size[0] % self.query_stride[0] ** (len(self.depths) - 1) != 0:
111
+ raise ValueError(
112
+ f"masked_unit_size[0] ({self.masked_unit_size[0]}) must be divisible by query_stride[0] ({self.query_stride[0]}) "
113
+ f"raised to the power of the number of layers ({len(self.depths) - 1})"
114
+ )
115
+
116
+ if self.num_query_pool >= len(self.depths):
117
+ raise ValueError(
118
+ f"num_query_pool ({self.num_query_pool}) must be less than the number of layers ({len(self.depths)})"
119
+ )
120
+
121
+
122
+ __all__ = ["HieraConfig"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/hiera/modeling_hiera.py ADDED
@@ -0,0 +1,1398 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Meta and The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """PyTorch Hiera model."""
15
+
16
+ import math
17
+ from dataclasses import dataclass
18
+
19
+ import torch
20
+ from torch import nn
21
+
22
+ from ... import initialization as init
23
+ from ...activations import ACT2FN
24
+ from ...backbone_utils import BackboneMixin, filter_output_hidden_states
25
+ from ...modeling_layers import GradientCheckpointingLayer
26
+ from ...modeling_outputs import (
27
+ BackboneOutput,
28
+ BaseModelOutput,
29
+ BaseModelOutputWithPooling,
30
+ ImageClassifierOutput,
31
+ ModelOutput,
32
+ )
33
+ from ...modeling_utils import PreTrainedModel
34
+ from ...utils import auto_docstring, logging, torch_int
35
+ from ...utils.generic import can_return_tuple
36
+ from .configuration_hiera import HieraConfig
37
+
38
+
39
+ logger = logging.get_logger(__name__)
40
+
41
+
42
+ @auto_docstring(
43
+ custom_intro="""
44
+ Hiera encoder's outputs, with potential hidden states and attentions.
45
+ """
46
+ )
47
+ @dataclass
48
+ class HieraEncoderOutput(ModelOutput):
49
+ r"""
50
+ reshaped_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
51
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
52
+ shape `(batch_size, height, width, hidden_size)`. These are the reshaped and re-rolled hidden states of the model.
53
+
54
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs reshaped to
55
+ include the spatial dimensions.
56
+ """
57
+
58
+ last_hidden_state: torch.FloatTensor | None = None
59
+ hidden_states: tuple[torch.FloatTensor, ...] | None = None
60
+ attentions: tuple[torch.FloatTensor, ...] | None = None
61
+ reshaped_hidden_states: tuple[torch.FloatTensor, ...] | None = None
62
+
63
+
64
+ @auto_docstring(
65
+ custom_intro="""
66
+ Hiera model's outputs that also contains a pooling of the last hidden states.
67
+ """
68
+ )
69
+ @dataclass
70
+ class HieraModelOutput(ModelOutput):
71
+ r"""
72
+ pooler_output (`torch.FloatTensor` of shape `(batch_size, hidden_size)`, *optional*, returned when `add_pooling_layer=True` is passed):
73
+ Average pooling of the last layer hidden-state.
74
+ bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, sequence_length)`):
75
+ Tensor indicating which patches are masked (0) and which are not (1).
76
+ ids_restore (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
77
+ Tensor containing the original index of the (shuffled) masked patches.
78
+ reshaped_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
79
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
80
+ shape `(batch_size, height, width, hidden_size)`. These are the reshaped and re-rolled hidden states of the model.
81
+
82
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs reshaped to
83
+ include the spatial dimensions.
84
+ """
85
+
86
+ last_hidden_state: torch.FloatTensor | None = None
87
+ pooler_output: torch.FloatTensor | None = None
88
+ bool_masked_pos: torch.BoolTensor | None = None
89
+ ids_restore: torch.LongTensor | None = None
90
+ hidden_states: tuple[torch.FloatTensor, ...] | None = None
91
+ attentions: tuple[torch.FloatTensor, ...] | None = None
92
+ reshaped_hidden_states: tuple[torch.FloatTensor, ...] | None = None
93
+
94
+
95
+ @auto_docstring(
96
+ custom_intro="""
97
+ Hiera image classification outputs.
98
+ """
99
+ )
100
+ @dataclass
101
+ class HieraForImageClassificationOutput(ImageClassifierOutput):
102
+ r"""
103
+ loss (`torch.FloatTensor` of shape `(1,)`, `optional`):
104
+ Loss value for the training task.
105
+ logits (`torch.FloatTensor` of shape `(batch_size, num_labels)`):
106
+ Prediction scores of the classification head (logits of the output layer).
107
+ hidden_states (`tuple(torch.FloatTensor)`, `optional`):
108
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
109
+ shape `(batch_size, sequence_length, hidden_size)`. These are the unrolled hidden states of the model.
110
+
111
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
112
+ attentions (`tuple(torch.FloatTensor)`, `optional`):
113
+ Tuple of `torch.FloatTensor` (one for each stage) of shape `(batch_size, num_heads, sequence_length,
114
+ sequence_length)`.
115
+
116
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
117
+ heads.
118
+ reshaped_hidden_states (`tuple(torch.FloatTensor)`, `optional`):
119
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
120
+ shape `(batch_size, height, width, hidden_size)`. These are the reshaped and re-rolled hidden states of the model.
121
+
122
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs reshaped to
123
+ include the spatial dimensions.
124
+ """
125
+
126
+ loss: torch.FloatTensor | None = None
127
+ logits: torch.FloatTensor | None = None
128
+ hidden_states: tuple[torch.FloatTensor, ...] | None = None
129
+ attentions: tuple[torch.FloatTensor, ...] | None = None
130
+ reshaped_hidden_states: tuple[torch.FloatTensor, ...] | None = None
131
+
132
+
133
+ @auto_docstring(
134
+ custom_intro="""
135
+ Class for HieraForPreTraining's outputs, with potential hidden states and attentions.
136
+ """
137
+ )
138
+ @dataclass
139
+ class HieraForPreTrainingOutput(ModelOutput):
140
+ r"""
141
+ loss (`torch.FloatTensor` of shape `(1,)`):
142
+ Pixel reconstruction loss.
143
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, patch_size ** 2 * num_channels)`):
144
+ Pixel reconstruction logits.
145
+ bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, sequence_length)`):
146
+ Tensor indicating which patches are masked (0) and which are not (1).
147
+ ids_restore (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
148
+ Tensor containing the original index of the (shuffled) masked patches.
149
+ reshaped_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
150
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
151
+ shape `(batch_size, height, width, hidden_size)`. Hidden-states of the model at the output of each layer
152
+ plus the initial embedding outputs reshaped to include the spatial dimensions.
153
+ """
154
+
155
+ loss: torch.FloatTensor | None = None
156
+ logits: torch.FloatTensor | None = None
157
+ bool_masked_pos: torch.BoolTensor | None = None
158
+ ids_restore: torch.LongTensor | None = None
159
+ hidden_states: tuple[torch.FloatTensor] | None = None
160
+ attentions: tuple[torch.FloatTensor] | None = None
161
+ reshaped_hidden_states: tuple[torch.FloatTensor] | None = None
162
+
163
+
164
+ class HieraPatchEmbeddings(nn.Module):
165
+ """
166
+ This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
167
+ `hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
168
+ Transformer.
169
+ """
170
+
171
+ def __init__(self, config, is_mae: bool = False):
172
+ super().__init__()
173
+
174
+ # Support any number of spatial dimensions
175
+ self.spatial_dims = len(config.patch_size)
176
+ if self.spatial_dims != 2:
177
+ raise ValueError(f"The number of dimensions of the input image should be 2, but got {self.spatial_dims}.")
178
+ self.num_channels = config.num_channels
179
+ self.image_size = config.image_size[-2:]
180
+ self.tokens_spatial_shape = [i // s for i, s in zip(config.image_size, config.patch_stride)]
181
+ self.mask_spatial_shape = [i // s for i, s in zip(self.tokens_spatial_shape, config.masked_unit_size)]
182
+ self.mask_ratio = config.mask_ratio
183
+ self.is_mae = is_mae
184
+ self.projection = nn.Conv2d(
185
+ self.num_channels,
186
+ config.embed_dim,
187
+ kernel_size=config.patch_size,
188
+ stride=config.patch_stride,
189
+ padding=config.patch_padding,
190
+ )
191
+
192
+ def masked_conv(
193
+ self, pixel_values: torch.FloatTensor, bool_masked_pos: torch.BoolTensor | None = None
194
+ ) -> torch.Tensor:
195
+ """Zero-out the masked regions of the input before conv.
196
+ Prevents leakage of masked regions when using overlapping kernels.
197
+ """
198
+ if bool_masked_pos is None:
199
+ return self.projection(pixel_values)
200
+
201
+ target_size = pixel_values.shape[2:]
202
+ # Reshape bool_masked_pos to (batch_size, 1, mask_unit_height, mask_unit_width)
203
+ bool_masked_pos = bool_masked_pos.view(pixel_values.shape[0], 1, *self.mask_spatial_shape)
204
+
205
+ bool_masked_pos = nn.functional.interpolate(bool_masked_pos.float(), size=target_size)
206
+
207
+ return self.projection(pixel_values * bool_masked_pos)
208
+
209
+ def random_masking(
210
+ self, pixel_values: torch.FloatTensor, noise: torch.FloatTensor | None = None
211
+ ) -> tuple[torch.BoolTensor, torch.LongTensor]:
212
+ """
213
+ Perform per-sample random masking by per-sample shuffling. Per-sample shuffling is done by argsort random
214
+ noise.
215
+
216
+ Args:
217
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`)
218
+ noise (`torch.FloatTensor` of shape `(batch_size, num_mask_units)`, *optional*) which is
219
+ mainly used for testing purposes to control randomness and maintain the reproducibility
220
+ """
221
+ batch_size = pixel_values.shape[0]
222
+ # Tokens selected for masking at mask unit level
223
+ num_windows = math.prod(self.mask_spatial_shape)
224
+ len_keep = int(num_windows * (1 - self.mask_ratio))
225
+
226
+ if noise is None:
227
+ noise = torch.rand(batch_size, num_windows, device=pixel_values.device)
228
+
229
+ # Sort noise for each sample
230
+ ids_shuffle = torch.argsort(noise, dim=1)
231
+ # ascend: small is keep, large is remove
232
+ ids_restore = torch.argsort(ids_shuffle, dim=1).to(pixel_values.device)
233
+
234
+ # Generate the binary bool_masked_pos: 1 is *keep*, 0 is *remove*
235
+ # Note this is opposite to original MAE
236
+ bool_masked_pos = torch.zeros([batch_size, num_windows], device=pixel_values.device)
237
+ bool_masked_pos[:, :len_keep] = 1
238
+ # Unshuffle to get the binary bool_masked_pos
239
+ bool_masked_pos = torch.gather(bool_masked_pos, dim=1, index=ids_restore).bool()
240
+
241
+ return bool_masked_pos, ids_restore
242
+
243
+ def forward(
244
+ self,
245
+ pixel_values: torch.FloatTensor,
246
+ noise: torch.FloatTensor | None = None,
247
+ ) -> tuple[torch.Tensor, torch.BoolTensor | None, torch.LongTensor | None]:
248
+ (bool_masked_pos, ids_restore) = (
249
+ self.random_masking(pixel_values, noise=noise) if self.is_mae else (None, None)
250
+ )
251
+
252
+ embeddings = self.masked_conv(pixel_values, bool_masked_pos)
253
+ embeddings = embeddings.flatten(2).transpose(2, 1)
254
+
255
+ return embeddings, bool_masked_pos, ids_restore
256
+
257
+
258
+ class HieraEmbeddings(nn.Module):
259
+ """
260
+ Construct position and patch embeddings.
261
+ """
262
+
263
+ def __init__(self, config: HieraConfig, is_mae: bool = False) -> None:
264
+ super().__init__()
265
+ self.patch_stride = config.patch_stride
266
+ tokens_spatial_shape = [i // s for i, s in zip(config.image_size, config.patch_stride)]
267
+ self.mask_spatial_shape = [i // s for i, s in zip(tokens_spatial_shape, config.masked_unit_size)]
268
+ self.num_tokens = math.prod(tokens_spatial_shape)
269
+ self.is_mae = is_mae
270
+
271
+ self.patch_embeddings = HieraPatchEmbeddings(config, is_mae=is_mae)
272
+
273
+ self.position_embeddings = nn.Parameter(torch.zeros(1, self.num_tokens, config.embed_dim))
274
+
275
+ def interpolate_pos_encoding(
276
+ self, embeddings: torch.Tensor, pos_embeds: torch.Tensor, height: int, width: int
277
+ ) -> torch.Tensor:
278
+ """
279
+ This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher resolution
280
+ images. This method is also adapted to support torch.jit tracing, no class embeddings, and different patch strides.
281
+
282
+ Adapted from:
283
+ - https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174-L194, and
284
+ - https://github.com/facebookresearch/dinov2/blob/e1277af2ba9496fbadf7aec6eba56e8d882d1e35/dinov2/models/vision_transformer.py#L179-L211
285
+ """
286
+
287
+ num_patches = embeddings.shape[1]
288
+ num_positions = pos_embeds.shape[1]
289
+
290
+ # always interpolate when tracing to ensure the exported model works for dynamic input shapes
291
+ if not torch.jit.is_tracing() and num_patches == num_positions and height == width:
292
+ return pos_embeds
293
+
294
+ dim = embeddings.shape[-1]
295
+
296
+ new_height = height // self.patch_stride[0]
297
+ new_width = width // self.patch_stride[1]
298
+
299
+ sqrt_num_positions = torch_int(num_positions**0.5)
300
+ pos_embeds = pos_embeds.reshape(1, sqrt_num_positions, sqrt_num_positions, dim)
301
+ pos_embeds = pos_embeds.permute(0, 3, 1, 2)
302
+
303
+ pos_embeds = nn.functional.interpolate(
304
+ pos_embeds,
305
+ size=(new_height, new_width),
306
+ mode="bicubic",
307
+ align_corners=False,
308
+ )
309
+
310
+ pos_embeds = pos_embeds.permute(0, 2, 3, 1).view(1, -1, dim)
311
+ return pos_embeds
312
+
313
+ def get_position_embedding(
314
+ self, embeddings: torch.Tensor, height: int, width: int, interpolate_pos_encoding: bool
315
+ ) -> torch.FloatTensor:
316
+ return (
317
+ self.interpolate_pos_encoding(embeddings, self.position_embeddings, height, width)
318
+ if interpolate_pos_encoding
319
+ else self.position_embeddings
320
+ )
321
+
322
+ def forward(
323
+ self,
324
+ pixel_values: torch.FloatTensor,
325
+ noise: torch.FloatTensor | None = None,
326
+ interpolate_pos_encoding: bool = False,
327
+ ) -> tuple[torch.Tensor, torch.BoolTensor | None, torch.LongTensor | None]:
328
+ height, width = pixel_values.shape[-2:]
329
+ embeddings, bool_masked_pos, ids_restore = self.patch_embeddings(pixel_values, noise=noise)
330
+ embeddings = embeddings + self.get_position_embedding(embeddings, height, width, interpolate_pos_encoding)
331
+ return embeddings, bool_masked_pos, ids_restore
332
+
333
+
334
+ class HieraMaskUnitAttention(nn.Module):
335
+ """
336
+ Computes either Mask Unit or Global Attention. Also is able to perform query pooling.
337
+
338
+ Note: this assumes the tokens have already been flattened and unrolled into mask units.
339
+ """
340
+
341
+ def __init__(
342
+ self,
343
+ hidden_size: int,
344
+ hidden_size_output: int,
345
+ num_heads: int,
346
+ query_stride: int = 1,
347
+ window_size: int = 0,
348
+ use_mask_unit_attn: bool = False,
349
+ ) -> None:
350
+ super().__init__()
351
+ self.num_heads = num_heads
352
+ self.query_stride = query_stride
353
+ self.hidden_size_output = hidden_size_output
354
+
355
+ self.head_dim = hidden_size_output // num_heads
356
+ self.scale = (self.head_dim) ** -0.5
357
+
358
+ self.qkv = nn.Linear(hidden_size, 3 * hidden_size_output)
359
+ self.proj = nn.Linear(hidden_size_output, hidden_size_output)
360
+
361
+ self.window_size = window_size
362
+ self.use_mask_unit_attn = use_mask_unit_attn
363
+
364
+ def forward(
365
+ self,
366
+ hidden_states: torch.Tensor,
367
+ output_attentions: bool = False,
368
+ ) -> tuple[torch.Tensor, torch.Tensor | None]:
369
+ """Input should be of shape [batch, tokens, channels]."""
370
+ batch_size, seq_len, _ = hidden_states.shape
371
+
372
+ num_windows = 1
373
+ if self.use_mask_unit_attn:
374
+ num_windows = seq_len // (self.query_stride * self.window_size)
375
+
376
+ qkv = self.qkv(hidden_states)
377
+ qkv = qkv.reshape(batch_size, -1, num_windows, 3, self.num_heads, self.head_dim)
378
+ qkv = qkv.permute(3, 0, 4, 2, 1, 5)
379
+
380
+ query, key, value = qkv.unbind(0)
381
+
382
+ if self.query_stride > 1:
383
+ # Refer to unroll to see how this performs a maxpool-Nd
384
+ query = query.view(batch_size, self.num_heads, num_windows, self.query_stride, -1, self.head_dim)
385
+ query = query.max(dim=3).values
386
+
387
+ attn_weights = (query * self.scale) @ key.transpose(-1, -2)
388
+ attn_weights = attn_weights.softmax(dim=-1)
389
+
390
+ attn_output = attn_weights @ value
391
+ attn_output = attn_output.transpose(1, 3).reshape(batch_size, -1, self.hidden_size_output)
392
+ attn_output = self.proj(attn_output)
393
+
394
+ return (attn_output, attn_weights) if output_attentions else (attn_output, None)
395
+
396
+
397
+ class HieraMlp(nn.Module):
398
+ def __init__(self, config, dim: int) -> None:
399
+ super().__init__()
400
+ self.activation_fn = ACT2FN[config.hidden_act]
401
+ self.fc1 = nn.Linear(dim, int(dim * config.mlp_ratio))
402
+ self.fc2 = nn.Linear(int(dim * config.mlp_ratio), dim)
403
+
404
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
405
+ hidden_states = self.fc1(hidden_states)
406
+ hidden_states = self.activation_fn(hidden_states)
407
+ hidden_states = self.fc2(hidden_states)
408
+ return hidden_states
409
+
410
+
411
+ # Copied from transformers.models.swin.modular_swin.SwinDropPath with SwinDropPath->HieraDropPath
412
+ class HieraDropPath(nn.Module):
413
+ """Stochastic depth (DropPath) per sample, for residual blocks.
414
+
415
+ Identity when ``drop_prob`` is 0 or outside training. See `Deep Networks with Stochastic Depth
416
+ <https://arxiv.org/abs/1603.09382>`_.
417
+ """
418
+
419
+ def __init__(self, drop_prob: float = 0.0) -> None:
420
+ super().__init__()
421
+ self.drop_prob = drop_prob
422
+
423
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
424
+ if self.drop_prob == 0.0 or not self.training:
425
+ return hidden_states
426
+ keep_prob = 1 - self.drop_prob
427
+ shape = (hidden_states.shape[0],) + (1,) * (hidden_states.ndim - 1)
428
+ random_tensor = torch.rand(shape, dtype=hidden_states.dtype, device=hidden_states.device)
429
+ random_tensor = torch.floor(random_tensor + keep_prob)
430
+ return hidden_states.div(keep_prob) * random_tensor
431
+
432
+ def extra_repr(self) -> str:
433
+ return f"p={self.drop_prob}"
434
+
435
+
436
+ class HieraLayer(nn.Module):
437
+ def __init__(
438
+ self,
439
+ config,
440
+ hidden_size: int,
441
+ hidden_size_output: int,
442
+ num_heads: int,
443
+ drop_path: float = 0.0,
444
+ query_stride: int = 1,
445
+ window_size: int = 0,
446
+ use_mask_unit_attn: bool = False,
447
+ ) -> None:
448
+ super().__init__()
449
+
450
+ self.hidden_size = hidden_size
451
+ self.hidden_size_output = hidden_size_output
452
+ self.query_stride = query_stride
453
+
454
+ self.layernorm_before = nn.LayerNorm(hidden_size, eps=config.layer_norm_eps)
455
+ self.attn = HieraMaskUnitAttention(
456
+ hidden_size=hidden_size,
457
+ hidden_size_output=hidden_size_output,
458
+ num_heads=num_heads,
459
+ query_stride=query_stride,
460
+ window_size=window_size,
461
+ use_mask_unit_attn=use_mask_unit_attn,
462
+ )
463
+
464
+ self.layernorm_after = nn.LayerNorm(hidden_size_output, eps=config.layer_norm_eps)
465
+ self.mlp = HieraMlp(config, hidden_size_output)
466
+
467
+ self.drop_path = HieraDropPath(drop_path) if drop_path > 0 else nn.Identity()
468
+ if hidden_size != hidden_size_output:
469
+ self.proj = nn.Linear(hidden_size, hidden_size_output)
470
+
471
+ def forward(
472
+ self,
473
+ hidden_states: torch.Tensor,
474
+ output_attentions: bool = False,
475
+ ) -> tuple[torch.Tensor, torch.Tensor | None]:
476
+ batch_size, seq_len, _ = hidden_states.shape
477
+ # Attention + Q Pooling
478
+ hidden_states_norm = self.layernorm_before(hidden_states)
479
+ if self.hidden_size != self.hidden_size_output:
480
+ hidden_states = self.proj(hidden_states_norm)
481
+ # Refer to unroll to see how this performs a maxpool-Nd
482
+ hidden_states = (
483
+ hidden_states.view(batch_size, self.query_stride, -1, self.hidden_size_output).max(dim=1).values
484
+ )
485
+
486
+ (hidden_states_norm, attn_weights) = self.attn(hidden_states_norm, output_attentions=output_attentions)
487
+ hidden_states = hidden_states + self.drop_path(hidden_states_norm)
488
+
489
+ residual = hidden_states
490
+ hidden_states = self.layernorm_after(hidden_states)
491
+ hidden_states = self.mlp(hidden_states)
492
+ hidden_states = residual + self.drop_path(hidden_states)
493
+
494
+ return (hidden_states, attn_weights)
495
+
496
+
497
+ class HieraStage(GradientCheckpointingLayer):
498
+ def __init__(
499
+ self,
500
+ config,
501
+ depth: int,
502
+ hidden_size: int,
503
+ hidden_size_output: int,
504
+ num_heads: int,
505
+ drop_path: list[float],
506
+ query_stride: list[int],
507
+ window_size: int,
508
+ use_mask_unit_attn: bool,
509
+ stage_num: int | None = None,
510
+ ) -> None:
511
+ super().__init__()
512
+ # we need to know if the previous stage used masked attention
513
+ # mask unit or global attention.
514
+ # lag by 1 layer, so that global attention,
515
+ # applied post pooling on lower resolution
516
+ previous_stage_used_masked_attention = False
517
+ if stage_num is not None:
518
+ previous_stage_used_masked_attention = config.masked_unit_attention[stage_num - 1 if stage_num > 0 else 0]
519
+ self.layers = nn.ModuleList(
520
+ [
521
+ HieraLayer(
522
+ config=config,
523
+ hidden_size=hidden_size if i == 0 else hidden_size_output,
524
+ hidden_size_output=hidden_size_output,
525
+ num_heads=num_heads,
526
+ drop_path=drop_path[i],
527
+ query_stride=query_stride[i],
528
+ window_size=window_size,
529
+ use_mask_unit_attn=use_mask_unit_attn or (previous_stage_used_masked_attention and i == 0),
530
+ )
531
+ for i in range(depth)
532
+ ]
533
+ )
534
+
535
+ def forward(
536
+ self, hidden_states: torch.Tensor, output_attentions: bool = False
537
+ ) -> tuple[torch.Tensor, torch.Tensor | None]:
538
+ for i, layer_module in enumerate(self.layers):
539
+ (hidden_states, attn_weights) = layer_module(hidden_states, output_attentions=output_attentions)
540
+
541
+ return hidden_states, attn_weights
542
+
543
+
544
+ def undo_windowing(hidden_states: torch.Tensor, shape: list[int], mask_unit_shape: list[int]) -> torch.Tensor:
545
+ """
546
+ Restore spatial organization by undoing windowed organization of mask units.
547
+
548
+ Args:
549
+ hidden_states (`torch.Tensor`): The hidden states tensor of shape `[batch_size, num_mask_unit_height*num_mask_unit_width, hidden_size]`.
550
+ shape (`list[int]`): The original shape of the hidden states tensor before windowing.
551
+ mask_unit_shape (`list[int]`): The shape of the mask units used for windowing.
552
+
553
+ Returns:
554
+ torch.Tensor: The restored hidden states tensor of shape [batch_size, num_mask_unit_height*mask_unit_height, num_mask_unit_width*mask_unit_width, hidden_size].
555
+ """
556
+ batch_size, hidden_size = hidden_states.shape[0], hidden_states.shape[-1]
557
+ # From: [batch_size, num_mask_unit_height*num_mask_unit_width, hidden_size]
558
+ # To: [batch_size, num_mask_unit_height, num_mask_unit_width, mask_unit_height, mask_unit_width, hidden_size]
559
+ num_mask_units = [s // mu for s, mu in zip(shape, mask_unit_shape)]
560
+ hidden_states = hidden_states.view(batch_size, *num_mask_units, *mask_unit_shape, hidden_size)
561
+
562
+ # From: [batch_size, num_mask_unit_height, num_mask_unit_width, mask_unit_height, mask_unit_width, hidden_size]
563
+ # To: [batch_size, num_mask_unit_height*mask_unit_height, num_mask_unit_width*mask_unit_width, hidden_size]
564
+ hidden_states = hidden_states.permute(0, 1, 3, 2, 4, 5)
565
+ hidden_states = hidden_states.reshape(batch_size, *shape, hidden_size)
566
+
567
+ return hidden_states
568
+
569
+
570
+ class HieraEncoder(nn.Module):
571
+ def __init__(self, config: HieraConfig) -> None:
572
+ super().__init__()
573
+ total_depth = sum(config.depths)
574
+ # stochastic depth decay rule
575
+ dpr = [x.item() for x in torch.linspace(0, config.drop_path_rate, total_depth, device="cpu")]
576
+ # query strides rule
577
+ cumulative_depths = torch.tensor(config.depths, device="cpu").cumsum(0).tolist()
578
+ query_pool_layer = cumulative_depths[: config.num_query_pool]
579
+ query_strides = [math.prod(config.query_stride) if i in query_pool_layer else 1 for i in range(total_depth)]
580
+
581
+ # Transformer blocks
582
+ self.stages = nn.ModuleList()
583
+ hidden_size = config.embed_dim
584
+ stage_ends = [0] + cumulative_depths
585
+ masked_unit_area = math.prod(config.masked_unit_size)
586
+ query_stride_area = math.prod(config.query_stride)
587
+ for idx_stage, depth in enumerate(config.depths):
588
+ hidden_size_output = int(config.embed_dim * config.embed_dim_multiplier**idx_stage)
589
+
590
+ stage = HieraStage(
591
+ config=config,
592
+ depth=depth,
593
+ hidden_size=hidden_size,
594
+ hidden_size_output=hidden_size_output,
595
+ num_heads=config.num_heads[idx_stage],
596
+ drop_path=dpr[stage_ends[idx_stage] : stage_ends[idx_stage + 1]],
597
+ query_stride=query_strides[stage_ends[idx_stage] : stage_ends[idx_stage + 1]],
598
+ window_size=int(masked_unit_area * query_stride_area**-idx_stage),
599
+ use_mask_unit_attn=config.masked_unit_attention[idx_stage],
600
+ stage_num=idx_stage,
601
+ )
602
+
603
+ hidden_size = hidden_size_output
604
+ self.stages.append(stage)
605
+
606
+ # Setting reroll schedule
607
+ # The first stage has to reverse everything
608
+ # The next stage has to reverse all but the first unroll, etc.
609
+ stage_size = [i // s for i, s in zip(config.image_size, config.patch_stride)]
610
+ unroll_schedule = [config.query_stride] * len(config.depths[:-1])
611
+
612
+ self.schedule = {}
613
+ for idx_stage in range(len(config.depths)):
614
+ self.schedule[idx_stage] = unroll_schedule, stage_size
615
+ if idx_stage < config.num_query_pool:
616
+ stage_size = [i // s for i, s in zip(stage_size, config.query_stride)]
617
+ unroll_schedule = unroll_schedule[1:]
618
+
619
+ self.gradient_checkpointing = False
620
+
621
+ def reroll(
622
+ self, hidden_states: torch.Tensor, stage_idx: int, bool_masked_pos: torch.BoolTensor | None = None
623
+ ) -> torch.Tensor:
624
+ """
625
+ Roll the given tensor back up to spatial order assuming it's from the given block.
626
+
627
+ If no bool_masked_pos is provided returns:
628
+ - [batch_size, height, width, hidden_size]
629
+ If a bool_masked_pos is provided returns:
630
+ - [batch_size, num_mask_units, mask_unit_height, mask_unit_width, hidden_size]
631
+ """
632
+ schedule, size = self.schedule[stage_idx]
633
+ batch_size, seq_len, hidden_size = hidden_states.shape
634
+
635
+ num_dim = len(size)
636
+ mask_unit_shape = [1] * num_dim
637
+
638
+ for strides in schedule:
639
+ # Extract the current patch from seq_len
640
+ hidden_states = hidden_states.view(
641
+ batch_size, *strides, seq_len // math.prod(strides), *mask_unit_shape, hidden_size
642
+ )
643
+
644
+ # Move that patch into the current MU
645
+ # Input: [batch_size, stride, stride, seq_len//(stride*stride), mask_unit_height, mask_unit_width, hidden_size]
646
+ # Output: [batch_size, seq_len//(stride*stride), stride, mask_unit_height, stride, mask_unit_width, hidden_size]
647
+ hidden_states = hidden_states.permute(0, 3, 1, 4, 2, 5, 6)
648
+
649
+ # Reshape to [batch_size, seq_len//(stride*stride), *mask_units, hidden_size]
650
+ for i in range(num_dim):
651
+ mask_unit_shape[i] *= strides[i]
652
+ hidden_states = hidden_states.reshape(batch_size, -1, *mask_unit_shape, hidden_size)
653
+ seq_len = hidden_states.shape[1]
654
+
655
+ # Current shape (e.g., 2d: [batch_size, #num_mask_units_height*#num_mask_units_width, mask_unit_height, mask_unit_width, hidden_size])
656
+ hidden_states = hidden_states.view(batch_size, seq_len, *mask_unit_shape, hidden_size)
657
+
658
+ # If masked, return [batch_size, num_mask_units, mask_unit_height, mask_unit_width, hidden_size]
659
+ if bool_masked_pos is not None:
660
+ return hidden_states
661
+
662
+ # If not masked, we can return [batch_size, height, width, hidden_size]
663
+ hidden_states = undo_windowing(hidden_states, size, mask_unit_shape)
664
+
665
+ return hidden_states
666
+
667
+ def forward(
668
+ self,
669
+ hidden_states: torch.Tensor,
670
+ bool_masked_pos: torch.BoolTensor | None = None,
671
+ output_attentions: bool = False,
672
+ output_hidden_states: bool = False,
673
+ return_dict: bool = True,
674
+ ) -> tuple | BaseModelOutput:
675
+ all_hidden_states = () if output_hidden_states else None
676
+ all_reshaped_hidden_states = () if output_hidden_states else None
677
+ all_self_attentions = () if output_attentions else None
678
+
679
+ if output_hidden_states:
680
+ all_hidden_states = all_hidden_states + (hidden_states,)
681
+ reshaped_hidden_states = self.reroll(hidden_states, stage_idx=0, bool_masked_pos=bool_masked_pos)
682
+ all_reshaped_hidden_states = all_reshaped_hidden_states + (reshaped_hidden_states,)
683
+
684
+ for i, stage_module in enumerate(self.stages):
685
+ layer_outputs = stage_module(hidden_states, output_attentions)
686
+
687
+ hidden_states = layer_outputs[0]
688
+
689
+ if output_attentions:
690
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
691
+
692
+ if output_hidden_states:
693
+ all_hidden_states = all_hidden_states + (hidden_states,)
694
+ reshaped_hidden_states = self.reroll(hidden_states, stage_idx=i, bool_masked_pos=bool_masked_pos)
695
+ all_reshaped_hidden_states = all_reshaped_hidden_states + (reshaped_hidden_states,)
696
+
697
+ if not return_dict:
698
+ return tuple(
699
+ v
700
+ for v in [hidden_states, all_hidden_states, all_self_attentions, all_reshaped_hidden_states]
701
+ if v is not None
702
+ )
703
+ return HieraEncoderOutput(
704
+ last_hidden_state=hidden_states,
705
+ hidden_states=all_hidden_states,
706
+ attentions=all_self_attentions,
707
+ reshaped_hidden_states=all_reshaped_hidden_states,
708
+ )
709
+
710
+
711
+ def unroll(
712
+ hidden_states: torch.Tensor, image_shape: tuple[int, int], patch_stride: tuple[int, int], schedule: list[list[int]]
713
+ ) -> torch.Tensor:
714
+ """
715
+ Reorders the tokens such that patches are contiguous in memory.
716
+ E.g., given [batch_size, (height, width), hidden_size] and stride of (stride, stride), this will re-order the tokens as
717
+ [batch_size, (stride, stride, height // stride, width // stride), hidden_size]
718
+
719
+ This allows operations like Max2d to be computed as x.view(batch_size, stride*stride, -1, hidden_size).max(dim=1).
720
+ Not only is this faster, but it also makes it easy to support inputs of arbitrary
721
+ dimensions in addition to patch-wise sparsity.
722
+
723
+ Performing this operation multiple times in sequence puts entire windows as contiguous
724
+ in memory. For instance, if you applied the stride (2, 2) 3 times, entire windows of
725
+ size 8x8 would be contiguous in memory, allowing operations like mask unit attention
726
+ computed easily and efficiently, while also allowing max to be applied sequentially.
727
+
728
+ Note: This means that intermediate values of the model are not in height x width order, so they
729
+ need to be re-rolled if you want to use the intermediate values as a height x width feature map.
730
+ The last block of the network is fine though, since by then the strides are all consumed.
731
+ """
732
+ batch_size, _, hidden_size = hidden_states.shape
733
+
734
+ size = [i // s for i, s in zip(image_shape, patch_stride)]
735
+
736
+ current_size = size
737
+ hidden_states = hidden_states.view(*([batch_size] + current_size + [hidden_size]))
738
+
739
+ for strides in schedule:
740
+ # Move patches with the given strides to the batch dimension
741
+
742
+ # Create a view of the tensor with the patch stride as separate dims
743
+ # For example in 2d: [batch_size, height // stride, stride, width // stride, stride, C]
744
+ current_size = [i // s for i, s in zip(current_size, strides)]
745
+ # initialize new_shape with [height // stride, stride, width // stride, stride]
746
+ new_shape = [item for pair in zip(current_size, strides) for item in pair]
747
+ # add batch_size and hidden_size to new_shape
748
+ new_shape = [batch_size] + new_shape + [hidden_size]
749
+ hidden_states = hidden_states.view(new_shape)
750
+
751
+ # Move the patch stride into the batch dimension
752
+ # For example in 2d: [batch_size, stride, stride, height // stride, width // stride, hidden_size]
753
+ num_dims = len(new_shape)
754
+ permute = [0] + list(range(2, num_dims - 1, 2)) + list(range(1, num_dims - 1, 2)) + [num_dims - 1]
755
+ hidden_states = hidden_states.permute(permute)
756
+
757
+ # Now finally flatten the relevant dims into the batch dimension
758
+ hidden_states = hidden_states.flatten(0, len(strides))
759
+ batch_size *= math.prod(strides)
760
+
761
+ hidden_states = hidden_states.reshape(-1, math.prod(size), hidden_size)
762
+ return hidden_states
763
+
764
+
765
+ @auto_docstring
766
+ class HieraPreTrainedModel(PreTrainedModel):
767
+ config: HieraConfig
768
+ base_model_prefix = "hiera"
769
+ main_input_name = "pixel_values"
770
+ input_modalities = ("image",)
771
+ supports_gradient_checkpointing = True
772
+
773
+ @torch.no_grad()
774
+ def _init_weights(self, module) -> None:
775
+ """Initialize the weights"""
776
+ std = self.config.initializer_range
777
+
778
+ if isinstance(module, HieraEmbeddings):
779
+ init.trunc_normal_(module.position_embeddings, std=std)
780
+
781
+ elif isinstance(module, HieraDecoder):
782
+ init.trunc_normal_(module.mask_token, std=std)
783
+ init.trunc_normal_(module.decoder_position_embeddings, std=std)
784
+
785
+ elif isinstance(module, (nn.Linear, nn.Conv1d, nn.Conv2d)):
786
+ init.trunc_normal_(module.weight, std=std)
787
+ if module.bias is not None:
788
+ init.constant_(module.bias, std)
789
+
790
+ elif isinstance(module, nn.LayerNorm):
791
+ init.constant_(module.bias, std)
792
+ init.constant_(module.weight, self.config.layer_norm_init)
793
+
794
+
795
+ class HieraPooler(nn.Module):
796
+ def __init__(self, config: HieraConfig):
797
+ super().__init__()
798
+ num_features = int(config.embed_dim * config.embed_dim_multiplier ** (len(config.depths) - 1))
799
+ self.layernorm = nn.LayerNorm(num_features, eps=config.layer_norm_eps)
800
+ self.pooler = nn.AdaptiveAvgPool1d(1)
801
+
802
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
803
+ hidden_states = hidden_states.transpose(1, 2)
804
+ pooled_output = self.pooler(hidden_states)
805
+ pooled_output = torch.flatten(pooled_output, 1)
806
+ pooled_output = self.layernorm(pooled_output)
807
+ return pooled_output
808
+
809
+
810
+ @auto_docstring
811
+ class HieraModel(HieraPreTrainedModel):
812
+ def __init__(self, config: HieraConfig, add_pooling_layer: bool = True, is_mae: bool = False):
813
+ r"""
814
+ add_pooling_layer (`bool`, *optional*, defaults to `True`):
815
+ Whether or not to apply pooling layer.
816
+ is_mae (`bool`, *optional*, defaults to `False`):
817
+ Whether or not to run the model on MAE mode.
818
+ """
819
+ super().__init__(config)
820
+ self.num_features = int(config.embed_dim * config.embed_dim_multiplier ** (len(config.depths) - 1))
821
+
822
+ self.embeddings = HieraEmbeddings(config, is_mae=is_mae)
823
+ self.encoder = HieraEncoder(config)
824
+
825
+ self.unroll_schedule = [config.query_stride] * len(config.depths[:-1])
826
+
827
+ self.pooler = HieraPooler(config) if add_pooling_layer else None
828
+
829
+ # Initialize weights and apply final processing
830
+ self.post_init()
831
+
832
+ def get_input_embeddings(self) -> HieraPatchEmbeddings:
833
+ return self.embeddings.patch_embeddings
834
+
835
+ @auto_docstring
836
+ def forward(
837
+ self,
838
+ pixel_values: torch.Tensor | None = None,
839
+ noise: torch.FloatTensor | None = None,
840
+ output_attentions: bool | None = None,
841
+ output_hidden_states: bool | None = None,
842
+ interpolate_pos_encoding: bool | None = None,
843
+ return_dict: bool | None = None,
844
+ **kwargs,
845
+ ) -> tuple | BaseModelOutputWithPooling:
846
+ r"""
847
+ noise (`torch.FloatTensor` of shape `(batch_size, num_mask_units)`, *optional*):
848
+ Mainly used for testing purposes to control randomness and maintain the reproducibility
849
+ """
850
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
851
+ output_hidden_states = (
852
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
853
+ )
854
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
855
+
856
+ if pixel_values is None:
857
+ raise ValueError("You have to specify pixel_values")
858
+
859
+ embedding_output, bool_masked_pos, ids_restore = self.embeddings(
860
+ pixel_values, interpolate_pos_encoding=interpolate_pos_encoding, noise=noise
861
+ )
862
+
863
+ image_shape = (pixel_values.shape[-2], pixel_values.shape[-1])
864
+ hidden_states = unroll(
865
+ embedding_output,
866
+ image_shape=image_shape,
867
+ patch_stride=self.config.patch_stride,
868
+ schedule=self.unroll_schedule,
869
+ )
870
+
871
+ # Discard masked tokens if bool_masked_pos is provided
872
+ if bool_masked_pos is not None:
873
+ mask_unit_area = math.prod(self.config.masked_unit_size)
874
+ batch_size, _, hidden_size = hidden_states.shape
875
+ positions = bool_masked_pos.unsqueeze(-1).tile(1, mask_unit_area, hidden_size)
876
+ hidden_states = hidden_states[positions]
877
+ hidden_states = hidden_states.view(batch_size, -1, hidden_size)
878
+
879
+ encoder_outputs = self.encoder(
880
+ hidden_states,
881
+ bool_masked_pos=bool_masked_pos,
882
+ output_attentions=output_attentions,
883
+ output_hidden_states=output_hidden_states,
884
+ return_dict=return_dict,
885
+ )
886
+ sequence_output = encoder_outputs[0]
887
+ pooled_output = None
888
+ if self.pooler is not None:
889
+ pooled_output = self.pooler(sequence_output)
890
+
891
+ if not return_dict:
892
+ head_outputs = (sequence_output, pooled_output) if pooled_output is not None else (sequence_output,)
893
+ head_outputs = (
894
+ head_outputs + (bool_masked_pos, ids_restore) if bool_masked_pos is not None else head_outputs
895
+ )
896
+ return head_outputs + encoder_outputs[1:]
897
+
898
+ return HieraModelOutput(
899
+ last_hidden_state=sequence_output,
900
+ pooler_output=pooled_output,
901
+ bool_masked_pos=bool_masked_pos,
902
+ ids_restore=ids_restore,
903
+ hidden_states=encoder_outputs.hidden_states,
904
+ attentions=encoder_outputs.attentions,
905
+ reshaped_hidden_states=encoder_outputs.reshaped_hidden_states,
906
+ )
907
+
908
+
909
+ class HieraDecoder(nn.Module):
910
+ def __init__(self, config: HieraConfig):
911
+ super().__init__()
912
+ num_features = int(config.embed_dim * config.embed_dim_multiplier ** (len(config.depths) - 1))
913
+ tokens_spatial_shape = [i // s for i, s in zip(config.image_size, config.patch_stride)]
914
+ self.tokens_spatial_shape_final = [
915
+ i // s ** (config.num_query_pool) for i, s in zip(tokens_spatial_shape, config.query_stride)
916
+ ]
917
+ self.mask_unit_spatial_shape_final = [
918
+ i // s ** (config.num_query_pool) for i, s in zip(config.masked_unit_size, config.query_stride)
919
+ ]
920
+
921
+ self.decoder_embeddings = nn.Linear(num_features, config.decoder_hidden_size)
922
+
923
+ self.mask_token = nn.Parameter(torch.zeros(1, 1, config.decoder_hidden_size))
924
+
925
+ self.decoder_position_embeddings = nn.Parameter(
926
+ torch.zeros(1, math.prod(self.tokens_spatial_shape_final), config.decoder_hidden_size)
927
+ )
928
+
929
+ self.decoder_block = HieraStage(
930
+ config=config,
931
+ hidden_size=config.decoder_hidden_size,
932
+ hidden_size_output=config.decoder_hidden_size,
933
+ num_heads=config.decoder_num_heads,
934
+ depth=config.decoder_depth,
935
+ use_mask_unit_attn=False,
936
+ drop_path=[0.0] * config.decoder_depth,
937
+ query_stride=[1] * config.decoder_depth,
938
+ window_size=0,
939
+ )
940
+
941
+ self.decoder_norm = nn.LayerNorm(config.decoder_hidden_size, eps=config.layer_norm_eps)
942
+
943
+ # patch stride of prediction
944
+ self.pred_stride = config.patch_stride[-1] * (config.query_stride[-1] ** config.num_query_pool)
945
+ pred_dim = (self.pred_stride ** len(config.query_stride)) * config.num_channels
946
+
947
+ self.decoder_pred = nn.Linear(config.decoder_hidden_size, pred_dim)
948
+
949
+ def forward(
950
+ self,
951
+ encoder_hidden_states: torch.Tensor,
952
+ bool_masked_pos: torch.BoolTensor,
953
+ output_attentions: bool = False,
954
+ ) -> tuple[torch.Tensor, torch.BoolTensor]:
955
+ # Embed tokens
956
+ hidden_states = self.decoder_embeddings(encoder_hidden_states)
957
+
958
+ # Combine visible and bool_masked_pos tokens
959
+
960
+ # hidden_states : [batch_size, num_mask_units_visible, *mask_unit_spatial_shape_final, decoder_hidden_size]
961
+ # bool_masked_pos: [batch_size, num_mask_units]
962
+ mask_unit_height, mask_unit_width, decoder_hidden_size = hidden_states.shape[2:]
963
+ batch_size, num_mask_units = bool_masked_pos.shape
964
+
965
+ decoder_hidden_states = torch.zeros(
966
+ batch_size,
967
+ num_mask_units,
968
+ mask_unit_height,
969
+ mask_unit_width,
970
+ decoder_hidden_size,
971
+ device=hidden_states.device,
972
+ dtype=hidden_states.dtype,
973
+ )
974
+ mask_tokens = self.mask_token.view(1, 1, 1, 1, -1)
975
+ bool_masked_pos = bool_masked_pos.reshape(batch_size, num_mask_units, 1, 1, 1)
976
+ bool_masked_pos = bool_masked_pos.expand(-1, -1, mask_unit_height, mask_unit_width, decoder_hidden_size)
977
+ decoder_hidden_states[bool_masked_pos] = hidden_states.flatten()
978
+ decoder_hidden_states = (
979
+ 1 - bool_masked_pos.float()
980
+ ) * mask_tokens + bool_masked_pos.float() * decoder_hidden_states
981
+
982
+ # Get back spatial order
983
+ hidden_states = undo_windowing(
984
+ decoder_hidden_states,
985
+ self.tokens_spatial_shape_final,
986
+ self.mask_unit_spatial_shape_final,
987
+ )
988
+ bool_masked_pos = undo_windowing(
989
+ bool_masked_pos[..., 0:1],
990
+ self.tokens_spatial_shape_final,
991
+ self.mask_unit_spatial_shape_final,
992
+ )
993
+
994
+ # Flatten
995
+ hidden_states = hidden_states.reshape(hidden_states.shape[0], -1, hidden_states.shape[-1])
996
+ bool_masked_pos = bool_masked_pos.view(hidden_states.shape[0], -1)
997
+
998
+ # Add pos embed
999
+ hidden_states = hidden_states + self.decoder_position_embeddings
1000
+
1001
+ # Apply decoder blocks
1002
+ hidden_states, attn_weights = self.decoder_block(hidden_states, output_attentions=output_attentions)
1003
+ hidden_states = self.decoder_norm(hidden_states)
1004
+
1005
+ # Predictor projection
1006
+ hidden_states = self.decoder_pred(hidden_states)
1007
+
1008
+ return hidden_states, bool_masked_pos
1009
+
1010
+
1011
+ class HieraMultiScaleHead(nn.Module):
1012
+ def __init__(self, config: HieraConfig):
1013
+ super().__init__()
1014
+ self.mask_unit_spatial_shape_final = [
1015
+ i // s ** (config.num_query_pool) for i, s in zip(config.masked_unit_size, config.query_stride)
1016
+ ]
1017
+ self.stage_dimensions = [
1018
+ int(config.embed_dim * config.embed_dim_multiplier**i) for i in range(len(config.depths))
1019
+ ]
1020
+ current_masked_unit_size = config.masked_unit_size
1021
+ self.multi_scale_fusion_heads = nn.ModuleList()
1022
+
1023
+ for idx in range(config.num_query_pool):
1024
+ kernel = [i // s for i, s in zip(current_masked_unit_size, self.mask_unit_spatial_shape_final)]
1025
+ current_masked_unit_size = [i // s for i, s in zip(current_masked_unit_size, config.query_stride)]
1026
+ self.multi_scale_fusion_heads.append(
1027
+ nn.Conv2d(
1028
+ self.stage_dimensions[idx],
1029
+ self.stage_dimensions[-1],
1030
+ kernel_size=kernel,
1031
+ stride=kernel,
1032
+ )
1033
+ )
1034
+ self.multi_scale_fusion_heads.append(nn.Identity())
1035
+
1036
+ def apply_fusion_head(self, head: nn.Module, hidden_states: torch.Tensor) -> torch.Tensor:
1037
+ if isinstance(head, nn.Identity):
1038
+ return hidden_states
1039
+
1040
+ batch_size, num_mask_units, mask_unit_height, mask_unit_width, hidden_size = hidden_states.shape
1041
+ # From: [batch_size, num_mask_units, mask_unit_height, mask_unit_width, hidden_size]
1042
+ # To: head([batch_size * num_mask_units, hidden_size, mask_unit_height, mask_unit_width])
1043
+ hidden_states = hidden_states.reshape(
1044
+ batch_size * num_mask_units, mask_unit_height, mask_unit_width, hidden_size
1045
+ )
1046
+ hidden_states = hidden_states.permute(0, 3, 1, 2)
1047
+ hidden_states = head(hidden_states)
1048
+
1049
+ # Restore original layout
1050
+ hidden_states = hidden_states.permute(0, 2, 3, 1)
1051
+ mask_unit_height_final, mask_unit_width_final, hidden_size = hidden_states.shape[1:]
1052
+ hidden_states = hidden_states.reshape(
1053
+ batch_size, num_mask_units, mask_unit_height_final, mask_unit_width_final, hidden_size
1054
+ )
1055
+
1056
+ return hidden_states
1057
+
1058
+ def forward(self, feature_maps: list[torch.Tensor]) -> torch.Tensor:
1059
+ # Multi-scale fusion
1060
+ hidden_states = 0.0
1061
+ for head, feature_map in zip(self.multi_scale_fusion_heads, feature_maps):
1062
+ hidden_states = hidden_states + self.apply_fusion_head(head, feature_map)
1063
+
1064
+ return hidden_states
1065
+
1066
+
1067
+ @auto_docstring(
1068
+ custom_intro="""
1069
+ The Hiera Model transformer with the decoder on top for self-supervised pre-training.
1070
+
1071
+ <Tip>
1072
+
1073
+ Note that we provide a script to pre-train this model on custom data in our [examples
1074
+ directory](https://github.com/huggingface/transformers/tree/main/examples/pytorch/image-pretraining).
1075
+
1076
+ </Tip>
1077
+ """
1078
+ )
1079
+ class HieraForPreTraining(HieraPreTrainedModel):
1080
+ def __init__(self, config: HieraConfig) -> None:
1081
+ super().__init__(config)
1082
+ # Encoder
1083
+ self.hiera = HieraModel(config, add_pooling_layer=False, is_mae=True)
1084
+ self.encoder_norm = nn.LayerNorm(self.hiera.num_features, eps=config.layer_norm_eps)
1085
+ # Multi-scale fusion heads
1086
+ self.multiscale_fusion = HieraMultiScaleHead(config)
1087
+ # Decoder
1088
+ self.decoder = HieraDecoder(config)
1089
+ self.pred_stride = self.decoder.pred_stride
1090
+
1091
+ # Initialize weights and apply final processing
1092
+ self.post_init()
1093
+
1094
+ def get_pixel_label_2d(self, pixel_values: torch.Tensor, bool_masked_pos: torch.BoolTensor) -> torch.Tensor:
1095
+ # bool_masked_pos (boolean tensor): True means *masked*
1096
+ pixel_values = pixel_values.permute(0, 2, 3, 1)
1097
+
1098
+ size = self.pred_stride
1099
+ label = pixel_values.unfold(1, size, size).unfold(2, size, size)
1100
+ label = label.flatten(1, 2).flatten(2)
1101
+ label = label[bool_masked_pos]
1102
+ if self.config.normalize_pixel_loss:
1103
+ mean = label.mean(dim=-1, keepdim=True)
1104
+ var = label.var(dim=-1, keepdim=True)
1105
+ label = (label - mean) / (var + 1.0e-6) ** 0.5
1106
+
1107
+ return label
1108
+
1109
+ def forward_loss(self, pixel_values: torch.Tensor, logits: torch.Tensor, bool_masked_pos: torch.BoolTensor):
1110
+ # We invert the bool_masked_pos such that 1.0 is *masked*
1111
+ bool_masked_pos = ~bool_masked_pos
1112
+ label = self.get_pixel_label_2d(pixel_values, bool_masked_pos)
1113
+
1114
+ logits = logits[bool_masked_pos]
1115
+ loss = (logits - label) ** 2
1116
+ loss = loss.mean()
1117
+
1118
+ return loss
1119
+
1120
+ @auto_docstring
1121
+ def forward(
1122
+ self,
1123
+ pixel_values: torch.Tensor | None = None,
1124
+ noise: torch.FloatTensor | None = None,
1125
+ output_attentions: bool | None = None,
1126
+ output_hidden_states: bool | None = None,
1127
+ interpolate_pos_encoding: bool | None = None,
1128
+ return_dict: bool | None = None,
1129
+ **kwargs,
1130
+ ) -> tuple | HieraForPreTrainingOutput:
1131
+ r"""
1132
+ noise (`torch.FloatTensor` of shape `(batch_size, num_mask_units)`, *optional*):
1133
+ Mainly used for testing purposes to control randomness and maintain the reproducibility
1134
+
1135
+ Examples:
1136
+ ```python
1137
+ >>> from transformers import AutoImageProcessor, HieraForPreTraining
1138
+ >>> import torch
1139
+ >>> from PIL import Image
1140
+ >>> import httpx
1141
+ >>> from io import BytesIO
1142
+
1143
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1144
+ >>> with httpx.stream("GET", url) as response:
1145
+ ... image = Image.open(BytesIO(response.read()))
1146
+
1147
+ >>> image_processor = AutoImageProcessor.from_pretrained("facebook/hiera-tiny-224-mae-hf")
1148
+ >>> model = HieraForPreTraining.from_pretrained("facebook/hiera-tiny-224-mae-hf")
1149
+
1150
+ >>> inputs = image_processor(images=image, return_tensors="pt")
1151
+
1152
+ >>> outputs = model(**inputs)
1153
+ >>> logits = outputs.logits
1154
+ >>> loss = outputs.loss
1155
+ >>> print(list(logits.shape))
1156
+ [1, 196, 768]
1157
+ ```"""
1158
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1159
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1160
+ output_hidden_states = (
1161
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1162
+ )
1163
+
1164
+ outputs = self.hiera(
1165
+ pixel_values,
1166
+ noise=noise,
1167
+ output_attentions=output_attentions,
1168
+ output_hidden_states=True,
1169
+ interpolate_pos_encoding=interpolate_pos_encoding,
1170
+ return_dict=return_dict,
1171
+ )
1172
+
1173
+ feature_maps = outputs[-1]
1174
+ bool_masked_pos = outputs[1]
1175
+ ids_to_restore = outputs[2]
1176
+ # Take only the query pooled and last hidden states
1177
+ feature_maps = feature_maps[1 : self.hiera.config.num_query_pool + 1] + (feature_maps[-1],)
1178
+ fused_hidden_states = self.multiscale_fusion(feature_maps)
1179
+ fused_hidden_states = self.encoder_norm(fused_hidden_states)
1180
+
1181
+ # Reconstruct pixel values
1182
+ logits, bool_masked_pos = self.decoder(
1183
+ fused_hidden_states,
1184
+ bool_masked_pos=bool_masked_pos,
1185
+ output_attentions=output_attentions,
1186
+ )
1187
+
1188
+ loss = self.forward_loss(pixel_values, logits, bool_masked_pos)
1189
+
1190
+ if not return_dict:
1191
+ output = (logits, bool_masked_pos, ids_to_restore)
1192
+ if output_hidden_states:
1193
+ output = output + (outputs[3],)
1194
+ if output_attentions:
1195
+ output = output + (outputs[4],)
1196
+ if output_hidden_states:
1197
+ output = output + (outputs[-1],)
1198
+ return ((loss,) + output) if loss is not None else output
1199
+
1200
+ return HieraForPreTrainingOutput(
1201
+ loss=loss,
1202
+ logits=logits,
1203
+ bool_masked_pos=bool_masked_pos,
1204
+ ids_restore=ids_to_restore,
1205
+ hidden_states=outputs.hidden_states if output_hidden_states else None,
1206
+ attentions=outputs.attentions,
1207
+ reshaped_hidden_states=outputs.reshaped_hidden_states if output_hidden_states else None,
1208
+ )
1209
+
1210
+
1211
+ @auto_docstring(
1212
+ custom_intro="""
1213
+ Hiera Model transformer with an image classification head on top (a linear layer on top of the final hidden state with
1214
+ average pooling) e.g. for ImageNet.
1215
+
1216
+ <Tip>
1217
+
1218
+ Note that it's possible to fine-tune Hiera on higher resolution images than the ones it has been trained on, by
1219
+ setting `interpolate_pos_encoding` to `True` in the forward of the model. This will interpolate the pre-trained
1220
+ position embeddings to the higher resolution.
1221
+
1222
+ </Tip>
1223
+ """
1224
+ )
1225
+ class HieraForImageClassification(HieraPreTrainedModel):
1226
+ def __init__(self, config: HieraConfig) -> None:
1227
+ super().__init__(config)
1228
+
1229
+ self.num_labels = config.num_labels
1230
+ self.hiera = HieraModel(config, add_pooling_layer=True, is_mae=False)
1231
+
1232
+ # Classifier head
1233
+ self.classifier = (
1234
+ nn.Linear(self.hiera.num_features, config.num_labels) if config.num_labels > 0 else nn.Identity()
1235
+ )
1236
+
1237
+ # Initialize weights and apply final processing
1238
+ self.post_init()
1239
+
1240
+ @auto_docstring
1241
+ def forward(
1242
+ self,
1243
+ pixel_values,
1244
+ labels: torch.Tensor | None = None,
1245
+ output_attentions: bool | None = None,
1246
+ output_hidden_states: bool | None = None,
1247
+ interpolate_pos_encoding: bool | None = None,
1248
+ return_dict: bool | None = None,
1249
+ **kwargs,
1250
+ ) -> tuple | HieraForImageClassificationOutput:
1251
+ r"""
1252
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1253
+ Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
1254
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1255
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1256
+ """
1257
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1258
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1259
+ output_hidden_states = (
1260
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1261
+ )
1262
+
1263
+ outputs = self.hiera(
1264
+ pixel_values,
1265
+ output_attentions=output_attentions,
1266
+ output_hidden_states=output_hidden_states,
1267
+ interpolate_pos_encoding=interpolate_pos_encoding,
1268
+ return_dict=return_dict,
1269
+ )
1270
+
1271
+ pooled_output = outputs[1]
1272
+
1273
+ logits = self.classifier(pooled_output)
1274
+
1275
+ loss = None
1276
+ if labels is not None:
1277
+ loss = self.loss_function(labels, logits, self.config)
1278
+
1279
+ if not return_dict:
1280
+ output = (logits,) + outputs[2:]
1281
+ return ((loss,) + output) if loss is not None else output
1282
+
1283
+ return HieraForImageClassificationOutput(
1284
+ loss=loss,
1285
+ logits=logits,
1286
+ hidden_states=outputs.hidden_states,
1287
+ attentions=outputs.attentions,
1288
+ reshaped_hidden_states=outputs.reshaped_hidden_states,
1289
+ )
1290
+
1291
+
1292
+ @auto_docstring(
1293
+ custom_intro="""
1294
+ Hiera backbone, to be used with frameworks like DETR and MaskFormer.
1295
+ """
1296
+ )
1297
+ class HieraBackbone(BackboneMixin, HieraPreTrainedModel):
1298
+ def __init__(self, config: HieraConfig):
1299
+ super().__init__(config)
1300
+
1301
+ self.num_features = [config.embed_dim] + [
1302
+ int(config.embed_dim * config.embed_dim_multiplier**i) for i in range(len(config.depths))
1303
+ ]
1304
+ self.embeddings = HieraEmbeddings(config, is_mae=False)
1305
+ self.encoder = HieraEncoder(config)
1306
+
1307
+ # Add layer norms to hidden states of out_features
1308
+ hidden_states_norms = {}
1309
+ for stage, num_channels in zip(self.out_features, self.channels):
1310
+ hidden_states_norms[stage] = nn.LayerNorm(num_channels)
1311
+ self.hidden_states_norms = nn.ModuleDict(hidden_states_norms)
1312
+
1313
+ # Initialize weights and apply final processing
1314
+ self.post_init()
1315
+
1316
+ def get_input_embeddings(self):
1317
+ return self.embeddings.patch_embeddings
1318
+
1319
+ @can_return_tuple
1320
+ @filter_output_hidden_states
1321
+ def forward(
1322
+ self,
1323
+ pixel_values: torch.Tensor,
1324
+ output_hidden_states: bool | None = None,
1325
+ output_attentions: bool | None = None,
1326
+ return_dict: bool | None = None,
1327
+ **kwargs,
1328
+ ) -> BackboneOutput:
1329
+ """
1330
+ Returns:
1331
+
1332
+ Examples:
1333
+
1334
+ ```python
1335
+ >>> from transformers import AutoImageProcessor, AutoBackbone
1336
+ >>> import torch
1337
+ >>> from PIL import Image
1338
+ >>> import httpx
1339
+ >>> from io import BytesIO
1340
+
1341
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1342
+ >>> with httpx.stream("GET", url) as response:
1343
+ ... image = Image.open(BytesIO(response.read()))
1344
+
1345
+ >>> processor = AutoImageProcessor.from_pretrained("facebook/hiera-tiny-224-hf")
1346
+ >>> model = AutoBackbone.from_pretrained(
1347
+ ... "facebook/hiera-tiny-224-hf", out_features=["stage1", "stage2", "stage3", "stage4"]
1348
+ ... )
1349
+
1350
+ >>> inputs = processor(image, return_tensors="pt")
1351
+ >>> outputs = model(**inputs)
1352
+ >>> feature_maps = outputs.feature_maps
1353
+ >>> list(feature_maps[-1].shape)
1354
+ [1, 768, 7, 7]
1355
+ ```"""
1356
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1357
+ output_hidden_states = (
1358
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1359
+ )
1360
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1361
+
1362
+ embedding_output, _, _ = self.embeddings(pixel_values)
1363
+
1364
+ outputs = self.encoder(
1365
+ embedding_output,
1366
+ output_attentions=output_attentions,
1367
+ output_hidden_states=True,
1368
+ return_dict=return_dict,
1369
+ )
1370
+
1371
+ hidden_states = outputs[-1]
1372
+
1373
+ feature_maps = ()
1374
+ for stage, hidden_state in zip(self.stage_names, hidden_states):
1375
+ if stage in self.out_features:
1376
+ batch_size, height, width, num_channels = hidden_state.shape
1377
+ hidden_state = hidden_state.view(batch_size, height * width, num_channels)
1378
+ hidden_state = self.hidden_states_norms[stage](hidden_state)
1379
+ hidden_state = hidden_state.view(batch_size, height, width, num_channels)
1380
+ hidden_state = hidden_state.permute(0, 3, 1, 2).contiguous()
1381
+ feature_maps += (hidden_state,)
1382
+
1383
+ if not return_dict:
1384
+ output = (feature_maps,)
1385
+ if output_hidden_states:
1386
+ output += (outputs[1],)
1387
+ if output_attentions:
1388
+ output += (outputs[2],)
1389
+ return output
1390
+
1391
+ return BackboneOutput(
1392
+ feature_maps=feature_maps,
1393
+ hidden_states=outputs[1] if output_hidden_states else None,
1394
+ attentions=outputs[2] if output_attentions else None,
1395
+ )
1396
+
1397
+
1398
+ __all__ = ["HieraForImageClassification", "HieraForPreTraining", "HieraBackbone", "HieraModel", "HieraPreTrainedModel"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/hyperclovax/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 NAVER CLOUD Corp. and The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_hyperclovax import *
22
+ from .modeling_hyperclovax import *
23
+ else:
24
+ import sys
25
+
26
+ _file = globals()["__file__"]
27
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/hyperclovax/configuration_hyperclovax.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/hyperclovax/modular_hyperclovax.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_hyperclovax.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # Copyright 2026 NAVER CLOUD Corp. and The HuggingFace Inc. team. All rights reserved.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ from huggingface_hub.dataclasses import strict
21
+
22
+ from ...configuration_utils import PreTrainedConfig
23
+ from ...modeling_rope_utils import RopeParameters
24
+ from ...utils import auto_docstring
25
+
26
+
27
+ @auto_docstring(checkpoint="naver-hyperclovax/HyperCLOVAX-SEED-Think-14B")
28
+ @strict
29
+ class HyperCLOVAXConfig(PreTrainedConfig):
30
+ r"""
31
+ embedding_multiplier (`float`, *optional*, defaults to `1.0`):
32
+ Scaling factor applied to the token embedding outputs. Used in MuP to control the
33
+ scale of the embedding activations.
34
+ logits_scaling (`float`, *optional*, defaults to `1.0`):
35
+ Scaling factor **multiplied** to the final logits before loss computation or sampling.
36
+ Used in MuP to ensure consistent output scale across model sizes. Note: unlike
37
+ [`GraniteConfig`], this is a multiplier, not a divisor.
38
+ residual_multiplier (`float`, *optional*, defaults to `1.0`):
39
+ Scaling factor applied to each sub-layer output before adding to the residual stream.
40
+ Used in Maximal Update Parametrization (MuP) to stabilize training across model sizes.
41
+ attention_multiplier (`float`, *optional*, defaults to `head_dim ** -0.5`):
42
+ Scaling factor applied to attention logits before softmax, replacing the standard
43
+ `1 / sqrt(head_dim)` scaling. Set explicitly for MuP-based training; when `None`,
44
+ defaults to the standard value.
45
+ use_post_norm (`bool`, *optional*, defaults to `True`):
46
+ Whether to apply an extra RMSNorm after each sub-layer output (Peri-Layer Normalization).
47
+
48
+ ```python
49
+ >>> from transformers import HyperCLOVAXModel, HyperCLOVAXConfig
50
+
51
+ >>> # Initializing a HyperCLOVAX style configuration
52
+ >>> configuration = HyperCLOVAXConfig()
53
+
54
+ >>> # Initializing a model from the configuration
55
+ >>> model = HyperCLOVAXModel(configuration)
56
+
57
+ >>> # Accessing the model configuration
58
+ >>> configuration = model.config
59
+ ```"""
60
+
61
+ model_type = "hyperclovax"
62
+ keys_to_ignore_at_inference = ["past_key_values"]
63
+ # Default tensor parallel plan for base model `HyperCLOVAXModel`
64
+ base_model_tp_plan = {
65
+ "layers.*.self_attn.q_proj": "colwise",
66
+ "layers.*.self_attn.k_proj": "colwise",
67
+ "layers.*.self_attn.v_proj": "colwise",
68
+ "layers.*.self_attn.o_proj": "rowwise",
69
+ "layers.*.mlp.gate_proj": "colwise",
70
+ "layers.*.mlp.up_proj": "colwise",
71
+ "layers.*.mlp.down_proj": "rowwise",
72
+ }
73
+ base_model_pp_plan = {
74
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
75
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
76
+ "norm": (["hidden_states"], ["hidden_states"]),
77
+ }
78
+
79
+ vocab_size: int = 32000
80
+ hidden_size: int = 4096
81
+ intermediate_size: int = 11008
82
+ num_hidden_layers: int = 32
83
+ num_attention_heads: int = 32
84
+ num_key_value_heads: int | None = None
85
+ hidden_act: str = "silu"
86
+ max_position_embeddings: int = 2048
87
+ initializer_range: float = 0.02
88
+ rms_norm_eps: float = 1e-6
89
+ use_cache: bool = True
90
+ pad_token_id: int | None = None
91
+ bos_token_id: int | None = 1
92
+ eos_token_id: int | list[int] | None = 2
93
+ tie_word_embeddings: bool = False
94
+ rope_parameters: RopeParameters | dict | None = None
95
+ attention_bias: bool = False
96
+ attention_dropout: float | int = 0.0
97
+ mlp_bias: bool = False
98
+ embedding_multiplier: float | int = 1.0
99
+ logits_scaling: float | int = 1.0
100
+ residual_multiplier: float | int = 1.0
101
+
102
+ # MuP scaling factors: None means "resolve to the mathematically equivalent default".
103
+ attention_multiplier: float | None = None
104
+
105
+ head_dim: int | None = None
106
+
107
+ # Peri-Layer Normalization
108
+ use_post_norm: bool = True
109
+
110
+ def __post_init__(
111
+ self,
112
+ **kwargs,
113
+ ):
114
+ if self.head_dim is None:
115
+ self.head_dim = self.hidden_size // self.num_attention_heads
116
+ if self.num_key_value_heads is None:
117
+ self.num_key_value_heads = self.num_attention_heads
118
+
119
+ super().__post_init__(**kwargs)
120
+
121
+ # Resolve None MuP values to their mathematically equivalent defaults.
122
+ if self.attention_multiplier is None:
123
+ self.attention_multiplier = self.head_dim**-0.5
124
+
125
+ def validate_architecture(self):
126
+ """Validates that `hidden_size` is divisible by `num_attention_heads`."""
127
+ if self.hidden_size % self.num_attention_heads != 0:
128
+ raise ValueError(
129
+ f"The hidden size ({self.hidden_size}) is not a multiple of the number of attention "
130
+ f"heads ({self.num_attention_heads})."
131
+ )
132
+
133
+
134
+ __all__ = ["HyperCLOVAXConfig"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/hyperclovax/modeling_hyperclovax.py ADDED
@@ -0,0 +1,526 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/hyperclovax/modular_hyperclovax.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_hyperclovax.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # Copyright 2026 NAVER CLOUD Corp. and The HuggingFace Inc. team. All rights reserved.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+
21
+ from collections.abc import Callable
22
+ from typing import Optional
23
+
24
+ import torch
25
+ import torch.nn as nn
26
+
27
+ from ...activations import ACT2FN
28
+ from ...cache_utils import Cache, DynamicCache
29
+ from ...generation import GenerationMixin
30
+ from ...integrations import use_kernel_forward_from_hub, use_kernel_func_from_hub, use_kernelized_func
31
+ from ...masking_utils import create_causal_mask
32
+ from ...modeling_layers import GradientCheckpointingLayer
33
+ from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
34
+ from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
35
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
36
+ from ...processing_utils import Unpack
37
+ from ...utils import TransformersKwargs, auto_docstring, can_return_tuple
38
+ from ...utils.generic import maybe_autocast, merge_with_config_defaults
39
+ from ...utils.output_capturing import capture_outputs
40
+ from .configuration_hyperclovax import HyperCLOVAXConfig
41
+
42
+
43
+ @use_kernel_forward_from_hub("RMSNorm")
44
+ class HyperCLOVAXRMSNorm(nn.Module):
45
+ def __init__(self, hidden_size, eps: float = 1e-6) -> None:
46
+ """
47
+ HyperCLOVAXRMSNorm is equivalent to T5LayerNorm
48
+ """
49
+ super().__init__()
50
+ self.weight = nn.Parameter(torch.ones(hidden_size))
51
+ self.variance_epsilon = eps
52
+
53
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
54
+ input_dtype = hidden_states.dtype
55
+ hidden_states = hidden_states.to(torch.float32)
56
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
57
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
58
+ return self.weight * hidden_states.to(input_dtype)
59
+
60
+ def extra_repr(self):
61
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
62
+
63
+
64
+ class HyperCLOVAXRotaryEmbedding(nn.Module):
65
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
66
+
67
+ def __init__(self, config: HyperCLOVAXConfig, device=None):
68
+ super().__init__()
69
+ self.max_seq_len_cached = config.max_position_embeddings
70
+ self.original_max_seq_len = config.max_position_embeddings
71
+
72
+ self.config = config
73
+
74
+ self.rope_type = self.config.rope_parameters["rope_type"]
75
+ rope_init_fn: Callable = self.compute_default_rope_parameters
76
+ if self.rope_type != "default":
77
+ rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
78
+ inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
79
+
80
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
81
+ self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
82
+
83
+ @staticmethod
84
+ def compute_default_rope_parameters(
85
+ config: HyperCLOVAXConfig | None = None,
86
+ device: Optional["torch.device"] = None,
87
+ seq_len: int | None = None,
88
+ ) -> tuple["torch.Tensor", float]:
89
+ """
90
+ Computes the inverse frequencies according to the original RoPE implementation
91
+ Args:
92
+ config ([`~transformers.PreTrainedConfig`]):
93
+ The model configuration.
94
+ device (`torch.device`):
95
+ The device to use for initialization of the inverse frequencies.
96
+ seq_len (`int`, *optional*):
97
+ The current sequence length. Unused for this type of RoPE.
98
+ Returns:
99
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
100
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
101
+ """
102
+ base = config.rope_parameters["rope_theta"]
103
+ dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
104
+
105
+ attention_factor = 1.0 # Unused in this type of RoPE
106
+
107
+ # Compute the inverse frequencies
108
+ inv_freq = 1.0 / (
109
+ base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
110
+ )
111
+ return inv_freq, attention_factor
112
+
113
+ @torch.no_grad()
114
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
115
+ def forward(self, x, position_ids):
116
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
117
+ position_ids_expanded = position_ids[:, None, :].float()
118
+
119
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
120
+ with maybe_autocast(device_type=device_type, enabled=False): # Force float32
121
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
122
+ emb = torch.cat((freqs, freqs), dim=-1)
123
+ cos = emb.cos() * self.attention_scaling
124
+ sin = emb.sin() * self.attention_scaling
125
+
126
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
127
+
128
+
129
+ def rotate_half(x):
130
+ """Rotates half the hidden dims of the input."""
131
+ x1 = x[..., : x.shape[-1] // 2]
132
+ x2 = x[..., x.shape[-1] // 2 :]
133
+ return torch.cat((-x2, x1), dim=-1)
134
+
135
+
136
+ @use_kernel_func_from_hub("rotary_pos_emb")
137
+ def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
138
+ """Applies Rotary Position Embedding to the query and key tensors.
139
+
140
+ Args:
141
+ q (`torch.Tensor`): The query tensor.
142
+ k (`torch.Tensor`): The key tensor.
143
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
144
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
145
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
146
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
147
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
148
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
149
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
150
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
151
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
152
+ Returns:
153
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
154
+ """
155
+ cos = cos.unsqueeze(unsqueeze_dim)
156
+ sin = sin.unsqueeze(unsqueeze_dim)
157
+ q_embed = (q * cos) + (rotate_half(q) * sin)
158
+ k_embed = (k * cos) + (rotate_half(k) * sin)
159
+ return q_embed, k_embed
160
+
161
+
162
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
163
+ """
164
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
165
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
166
+ """
167
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
168
+ if n_rep == 1:
169
+ return hidden_states
170
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
171
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
172
+
173
+
174
+ def eager_attention_forward(
175
+ module: nn.Module,
176
+ query: torch.Tensor,
177
+ key: torch.Tensor,
178
+ value: torch.Tensor,
179
+ attention_mask: torch.Tensor | None,
180
+ scaling: float,
181
+ dropout: float = 0.0,
182
+ **kwargs: Unpack[TransformersKwargs],
183
+ ):
184
+ key_states = repeat_kv(key, module.num_key_value_groups)
185
+ value_states = repeat_kv(value, module.num_key_value_groups)
186
+
187
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
188
+ if attention_mask is not None:
189
+ attn_weights = attn_weights + attention_mask
190
+
191
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
192
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
193
+ attn_output = torch.matmul(attn_weights, value_states)
194
+ attn_output = attn_output.transpose(1, 2).contiguous()
195
+
196
+ return attn_output, attn_weights
197
+
198
+
199
+ @use_kernelized_func(apply_rotary_pos_emb)
200
+ class HyperCLOVAXAttention(nn.Module):
201
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
202
+
203
+ def __init__(self, config: HyperCLOVAXConfig, layer_idx: int | None = None):
204
+ super().__init__()
205
+ self.config = config
206
+ self.layer_idx = layer_idx
207
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
208
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
209
+ self.scaling = config.attention_multiplier
210
+ self.attention_dropout = config.attention_dropout
211
+ self.is_causal = True
212
+
213
+ self.q_proj = nn.Linear(
214
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
215
+ )
216
+ self.k_proj = nn.Linear(
217
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
218
+ )
219
+ self.v_proj = nn.Linear(
220
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
221
+ )
222
+ self.o_proj = nn.Linear(
223
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
224
+ )
225
+
226
+ def forward(
227
+ self,
228
+ hidden_states: torch.Tensor,
229
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
230
+ attention_mask: torch.Tensor | None = None,
231
+ past_key_values: Cache | None = None,
232
+ **kwargs: Unpack[TransformersKwargs],
233
+ ) -> tuple[torch.Tensor, torch.Tensor]:
234
+ input_shape = hidden_states.shape[:-1]
235
+ hidden_shape = (*input_shape, -1, self.head_dim)
236
+
237
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
238
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
239
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
240
+
241
+ cos, sin = position_embeddings
242
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
243
+
244
+ if past_key_values is not None:
245
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
246
+
247
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
248
+ self.config._attn_implementation, eager_attention_forward
249
+ )
250
+
251
+ attn_output, attn_weights = attention_interface(
252
+ self,
253
+ query_states,
254
+ key_states,
255
+ value_states,
256
+ attention_mask,
257
+ dropout=0.0 if not self.training else self.attention_dropout,
258
+ scaling=self.scaling,
259
+ **kwargs,
260
+ )
261
+
262
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
263
+ attn_output = self.o_proj(attn_output)
264
+ return attn_output, attn_weights
265
+
266
+
267
+ class HyperCLOVAXMLP(nn.Module):
268
+ def __init__(self, config):
269
+ super().__init__()
270
+ self.config = config
271
+ self.hidden_size = config.hidden_size
272
+ self.intermediate_size = config.intermediate_size
273
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
274
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
275
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
276
+ self.act_fn = ACT2FN[config.hidden_act]
277
+
278
+ def forward(self, x):
279
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
280
+ return down_proj
281
+
282
+
283
+ class HyperCLOVAXDecoderLayer(GradientCheckpointingLayer):
284
+ def __init__(self, config: HyperCLOVAXConfig, layer_idx: int):
285
+ super().__init__()
286
+ self.hidden_size = config.hidden_size
287
+ self.self_attn = HyperCLOVAXAttention(config=config, layer_idx=layer_idx)
288
+
289
+ self.mlp = HyperCLOVAXMLP(config)
290
+ self.input_layernorm = HyperCLOVAXRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
291
+ self.post_attention_layernorm = HyperCLOVAXRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
292
+ self.residual_multiplier = config.residual_multiplier
293
+ # Optional Peri-Layer Normalization: additional RMSNorm after each sub-layer output
294
+ self.post_norm1 = (
295
+ HyperCLOVAXRMSNorm(config.hidden_size, eps=config.rms_norm_eps) if config.use_post_norm else nn.Identity()
296
+ )
297
+ self.post_norm2 = (
298
+ HyperCLOVAXRMSNorm(config.hidden_size, eps=config.rms_norm_eps) if config.use_post_norm else nn.Identity()
299
+ )
300
+
301
+ def forward(
302
+ self,
303
+ hidden_states: torch.Tensor,
304
+ attention_mask: torch.Tensor | None = None,
305
+ position_ids: torch.LongTensor | None = None,
306
+ past_key_values: Cache | None = None,
307
+ use_cache: bool | None = False,
308
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
309
+ **kwargs: Unpack[TransformersKwargs],
310
+ ) -> torch.Tensor:
311
+ """
312
+ Args:
313
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
314
+ attention_mask (`torch.FloatTensor`, *optional*):
315
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
316
+ query_sequence_length, key_sequence_length)` if default attention is used.
317
+ output_attentions (`bool`, *optional*):
318
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
319
+ returned tensors for more detail.
320
+ use_cache (`bool`, *optional*):
321
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
322
+ (see `past_key_values`).
323
+ past_key_values (`Cache`, *optional*): cached past key and value projection states
324
+ position_embeddings (`tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
325
+ Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
326
+ with `head_dim` being the embedding dimension of each attention head.
327
+ kwargs (`dict`, *optional*):
328
+ Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
329
+ into the model
330
+ """
331
+ residual = hidden_states
332
+ hidden_states = self.input_layernorm(hidden_states)
333
+ # Self Attention
334
+ hidden_states, _ = self.self_attn(
335
+ hidden_states=hidden_states,
336
+ attention_mask=attention_mask,
337
+ position_ids=position_ids,
338
+ past_key_values=past_key_values,
339
+ use_cache=use_cache,
340
+ position_embeddings=position_embeddings,
341
+ **kwargs,
342
+ )
343
+ hidden_states = self.post_norm1(hidden_states)
344
+ hidden_states = residual + hidden_states * self.residual_multiplier
345
+
346
+ # Fully Connected
347
+ residual = hidden_states
348
+ hidden_states = self.post_attention_layernorm(hidden_states)
349
+ hidden_states = self.mlp(hidden_states)
350
+ hidden_states = self.post_norm2(hidden_states)
351
+ hidden_states = residual + hidden_states * self.residual_multiplier
352
+ return hidden_states
353
+
354
+
355
+ @auto_docstring
356
+ class HyperCLOVAXPreTrainedModel(PreTrainedModel):
357
+ config: HyperCLOVAXConfig
358
+ base_model_prefix = "model"
359
+ supports_gradient_checkpointing = True
360
+ _no_split_modules = ["HyperCLOVAXDecoderLayer"]
361
+ _skip_keys_device_placement = ["past_key_values"]
362
+ _supports_flash_attn = True
363
+ _supports_sdpa = True
364
+ _supports_flex_attn = True
365
+
366
+ _can_compile_fullgraph = True
367
+ _supports_attention_backend = True
368
+ _can_record_outputs = {
369
+ "hidden_states": HyperCLOVAXDecoderLayer,
370
+ "attentions": HyperCLOVAXAttention,
371
+ }
372
+
373
+
374
+ @auto_docstring
375
+ class HyperCLOVAXModel(HyperCLOVAXPreTrainedModel):
376
+ def __init__(self, config: HyperCLOVAXConfig):
377
+ super().__init__(config)
378
+ self.padding_idx = config.pad_token_id
379
+ self.vocab_size = config.vocab_size
380
+
381
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
382
+ self.layers = nn.ModuleList(
383
+ [HyperCLOVAXDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
384
+ )
385
+ self.norm = HyperCLOVAXRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
386
+ self.rotary_emb = HyperCLOVAXRotaryEmbedding(config=config)
387
+ self.gradient_checkpointing = False
388
+ self.embedding_multiplier = config.embedding_multiplier
389
+
390
+ # Initialize weights and apply final processing
391
+ self.post_init()
392
+
393
+ @merge_with_config_defaults
394
+ @capture_outputs
395
+ @auto_docstring
396
+ def forward(
397
+ self,
398
+ input_ids: torch.LongTensor | None = None,
399
+ attention_mask: torch.Tensor | None = None,
400
+ position_ids: torch.LongTensor | None = None,
401
+ past_key_values: Cache | None = None,
402
+ inputs_embeds: torch.FloatTensor | None = None,
403
+ use_cache: bool | None = None,
404
+ **kwargs: Unpack[TransformersKwargs],
405
+ ) -> BaseModelOutputWithPast:
406
+ if (input_ids is None) ^ (inputs_embeds is not None):
407
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
408
+
409
+ if inputs_embeds is None:
410
+ inputs_embeds = self.embed_tokens(input_ids)
411
+
412
+ inputs_embeds = inputs_embeds * self.embedding_multiplier
413
+
414
+ if use_cache and past_key_values is None:
415
+ past_key_values = DynamicCache(config=self.config)
416
+
417
+ if position_ids is None:
418
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
419
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
420
+ position_ids = position_ids.unsqueeze(0)
421
+
422
+ causal_mask = create_causal_mask(
423
+ config=self.config,
424
+ inputs_embeds=inputs_embeds,
425
+ attention_mask=attention_mask,
426
+ past_key_values=past_key_values,
427
+ position_ids=position_ids,
428
+ )
429
+
430
+ hidden_states = inputs_embeds
431
+ position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
432
+
433
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
434
+ hidden_states = decoder_layer(
435
+ hidden_states,
436
+ attention_mask=causal_mask,
437
+ position_ids=position_ids,
438
+ past_key_values=past_key_values,
439
+ use_cache=use_cache,
440
+ position_embeddings=position_embeddings,
441
+ **kwargs,
442
+ )
443
+
444
+ hidden_states = self.norm(hidden_states)
445
+
446
+ return BaseModelOutputWithPast(
447
+ last_hidden_state=hidden_states,
448
+ past_key_values=past_key_values,
449
+ )
450
+
451
+
452
+ @auto_docstring
453
+ class HyperCLOVAXForCausalLM(HyperCLOVAXPreTrainedModel, GenerationMixin):
454
+ _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
455
+ _tp_plan = {"lm_head": "colwise_gather_output"}
456
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
457
+
458
+ def __init__(self, config):
459
+ super().__init__(config)
460
+ self.model = HyperCLOVAXModel(config)
461
+ self.vocab_size = config.vocab_size
462
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
463
+
464
+ # Initialize weights and apply final processing
465
+ self.post_init()
466
+
467
+ @can_return_tuple
468
+ @auto_docstring
469
+ def forward(
470
+ self,
471
+ input_ids: torch.LongTensor | None = None,
472
+ attention_mask: torch.Tensor | None = None,
473
+ position_ids: torch.LongTensor | None = None,
474
+ past_key_values: Cache | None = None,
475
+ inputs_embeds: torch.FloatTensor | None = None,
476
+ labels: torch.LongTensor | None = None,
477
+ use_cache: bool | None = None,
478
+ logits_to_keep: int | torch.Tensor = 0,
479
+ **kwargs: Unpack[TransformersKwargs],
480
+ ) -> CausalLMOutputWithPast:
481
+ r"""
482
+ Example:
483
+
484
+ ```python
485
+ >>> from transformers import AutoTokenizer, HyperCLOVAXForCausalLM
486
+
487
+ >>> model = HyperCLOVAXForCausalLM.from_pretrained("naver-hyperclovax/HyperCLOVAX-SEED-Think-14B")
488
+ >>> tokenizer = AutoTokenizer.from_pretrained("naver-hyperclovax/HyperCLOVAX-SEED-Think-14B")
489
+
490
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
491
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
492
+
493
+ >>> # Generate
494
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
495
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
496
+ "Hey, are you conscious? Can you talk to me? Are you okay?" The man was confused and answered, "Yes." Then the woman asked.
497
+ ```"""
498
+ outputs = self.model(
499
+ input_ids=input_ids,
500
+ attention_mask=attention_mask,
501
+ position_ids=position_ids,
502
+ past_key_values=past_key_values,
503
+ inputs_embeds=inputs_embeds,
504
+ use_cache=use_cache,
505
+ **kwargs,
506
+ )
507
+
508
+ hidden_states = outputs.last_hidden_state
509
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
510
+ # MuP: multiply logits by logits_scaling (cf. GraniteForCausalLM which divides)
511
+ logits = self.lm_head(hidden_states[:, slice_indices, :]) * self.config.logits_scaling
512
+
513
+ loss = None
514
+ if labels is not None:
515
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
516
+
517
+ return CausalLMOutputWithPast(
518
+ loss=loss,
519
+ logits=logits,
520
+ past_key_values=outputs.past_key_values,
521
+ hidden_states=outputs.hidden_states,
522
+ attentions=outputs.attentions,
523
+ )
524
+
525
+
526
+ __all__ = ["HyperCLOVAXPreTrainedModel", "HyperCLOVAXModel", "HyperCLOVAXForCausalLM"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/ibert/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_ibert import *
22
+ from .modeling_ibert import *
23
+ else:
24
+ import sys
25
+
26
+ _file = globals()["__file__"]
27
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/ibert/configuration_ibert.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 The I-BERT Authors (Sehoon Kim, Amir Gholami, Zhewei Yao,
2
+ # Michael Mahoney, Kurt Keutzer - UC Berkeley) and The HuggingFace Inc. team.
3
+ # Copyright (c) 20121, NVIDIA CORPORATION. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """I-BERT configuration"""
17
+
18
+ from huggingface_hub.dataclasses import strict
19
+
20
+ from ...configuration_utils import PreTrainedConfig
21
+ from ...utils import auto_docstring
22
+
23
+
24
+ @auto_docstring(checkpoint="kssteven/ibert-roberta-base")
25
+ @strict
26
+ class IBertConfig(PreTrainedConfig):
27
+ r"""
28
+ type_vocab_size (`int`, *optional*, defaults to 2):
29
+ The vocabulary size of the `token_type_ids` passed when calling [`IBertModel`]
30
+ quant_mode (`bool`, *optional*, defaults to `False`):
31
+ Whether to quantize the model or not.
32
+ force_dequant (`str`, *optional*, defaults to `"none"`):
33
+ Force dequantize specific nonlinear layer. Dequantized layers are then executed with full precision.
34
+ `"none"`, `"gelu"`, `"softmax"`, `"layernorm"` and `"nonlinear"` are supported. As default, it is set as
35
+ `"none"`, which does not dequantize any layers. Please specify `"gelu"`, `"softmax"`, or `"layernorm"` to
36
+ dequantize GELU, Softmax, or LayerNorm, respectively. `"nonlinear"` will dequantize all nonlinear layers,
37
+ i.e., GELU, Softmax, and LayerNorm.
38
+ """
39
+
40
+ model_type = "ibert"
41
+
42
+ vocab_size: int = 30522
43
+ hidden_size: int = 768
44
+ num_hidden_layers: int = 12
45
+ num_attention_heads: int = 12
46
+ intermediate_size: int = 3072
47
+ hidden_act: str = "gelu"
48
+ hidden_dropout_prob: float | int = 0.1
49
+ attention_probs_dropout_prob: float | int = 0.1
50
+ max_position_embeddings: int = 512
51
+ type_vocab_size: int = 2
52
+ initializer_range: float = 0.02
53
+ layer_norm_eps: float = 1e-12
54
+ pad_token_id: int | None = 1
55
+ bos_token_id: int | None = 0
56
+ eos_token_id: int | list[int] | None = 2
57
+ quant_mode: bool = False
58
+ force_dequant: str = "none"
59
+ tie_word_embeddings: bool = True
60
+
61
+
62
+ __all__ = ["IBertConfig"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/ibert/modeling_ibert.py ADDED
@@ -0,0 +1,1202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 The I-BERT Authors (Sehoon Kim, Amir Gholami, Zhewei Yao,
2
+ # Michael Mahoney, Kurt Keutzer - UC Berkeley) and The HuggingFace Inc. team.
3
+ # Copyright (c) 20121, NVIDIA CORPORATION. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ """PyTorch I-BERT model."""
18
+
19
+ import math
20
+
21
+ import torch
22
+ from torch import nn
23
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
24
+
25
+ from ... import initialization as init
26
+ from ...activations import gelu
27
+ from ...masking_utils import create_bidirectional_mask
28
+ from ...modeling_outputs import (
29
+ BaseModelOutputWithPastAndCrossAttentions,
30
+ BaseModelOutputWithPoolingAndCrossAttentions,
31
+ MaskedLMOutput,
32
+ MultipleChoiceModelOutput,
33
+ QuestionAnsweringModelOutput,
34
+ SequenceClassifierOutput,
35
+ TokenClassifierOutput,
36
+ )
37
+ from ...modeling_utils import PreTrainedModel
38
+ from ...utils import auto_docstring, logging
39
+ from .configuration_ibert import IBertConfig
40
+ from .quant_modules import IntGELU, IntLayerNorm, IntSoftmax, QuantAct, QuantEmbedding, QuantLinear
41
+
42
+
43
+ logger = logging.get_logger(__name__)
44
+
45
+
46
+ class IBertEmbeddings(nn.Module):
47
+ """
48
+ Same as BertEmbeddings with a tiny tweak for positional embeddings indexing.
49
+ """
50
+
51
+ def __init__(self, config):
52
+ super().__init__()
53
+ self.quant_mode = config.quant_mode
54
+ self.embedding_bit = 8
55
+ self.embedding_act_bit = 16
56
+ self.act_bit = 8
57
+ self.ln_input_bit = 22
58
+ self.ln_output_bit = 32
59
+
60
+ self.word_embeddings = QuantEmbedding(
61
+ config.vocab_size,
62
+ config.hidden_size,
63
+ padding_idx=config.pad_token_id,
64
+ weight_bit=self.embedding_bit,
65
+ quant_mode=self.quant_mode,
66
+ )
67
+ self.token_type_embeddings = QuantEmbedding(
68
+ config.type_vocab_size, config.hidden_size, weight_bit=self.embedding_bit, quant_mode=self.quant_mode
69
+ )
70
+
71
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
72
+ self.register_buffer(
73
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
74
+ )
75
+
76
+ # End copy
77
+ self.padding_idx = config.pad_token_id
78
+ self.position_embeddings = QuantEmbedding(
79
+ config.max_position_embeddings,
80
+ config.hidden_size,
81
+ padding_idx=self.padding_idx,
82
+ weight_bit=self.embedding_bit,
83
+ quant_mode=self.quant_mode,
84
+ )
85
+
86
+ # Integer-only addition between embeddings
87
+ self.embeddings_act1 = QuantAct(self.embedding_act_bit, quant_mode=self.quant_mode)
88
+ self.embeddings_act2 = QuantAct(self.embedding_act_bit, quant_mode=self.quant_mode)
89
+
90
+ self.LayerNorm = IntLayerNorm(
91
+ config.hidden_size,
92
+ eps=config.layer_norm_eps,
93
+ output_bit=self.ln_output_bit,
94
+ quant_mode=self.quant_mode,
95
+ force_dequant=config.force_dequant,
96
+ )
97
+ self.output_activation = QuantAct(self.act_bit, quant_mode=self.quant_mode)
98
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
99
+
100
+ def forward(
101
+ self, input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None, past_key_values_length=0
102
+ ):
103
+ if position_ids is None:
104
+ if input_ids is not None:
105
+ # Create the position ids from the input token ids. Any padded tokens remain padded.
106
+ position_ids = create_position_ids_from_input_ids(
107
+ input_ids, self.padding_idx, past_key_values_length
108
+ ).to(input_ids.device)
109
+ else:
110
+ position_ids = self.create_position_ids_from_inputs_embeds(inputs_embeds)
111
+
112
+ if input_ids is not None:
113
+ input_shape = input_ids.size()
114
+ else:
115
+ input_shape = inputs_embeds.size()[:-1]
116
+
117
+ if token_type_ids is None:
118
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
119
+
120
+ if inputs_embeds is None:
121
+ inputs_embeds, inputs_embeds_scaling_factor = self.word_embeddings(input_ids)
122
+ else:
123
+ inputs_embeds_scaling_factor = None
124
+ token_type_embeddings, token_type_embeddings_scaling_factor = self.token_type_embeddings(token_type_ids)
125
+
126
+ embeddings, embeddings_scaling_factor = self.embeddings_act1(
127
+ inputs_embeds,
128
+ inputs_embeds_scaling_factor,
129
+ identity=token_type_embeddings,
130
+ identity_scaling_factor=token_type_embeddings_scaling_factor,
131
+ )
132
+
133
+ position_embeddings, position_embeddings_scaling_factor = self.position_embeddings(position_ids)
134
+ embeddings, embeddings_scaling_factor = self.embeddings_act1(
135
+ embeddings,
136
+ embeddings_scaling_factor,
137
+ identity=position_embeddings,
138
+ identity_scaling_factor=position_embeddings_scaling_factor,
139
+ )
140
+
141
+ embeddings, embeddings_scaling_factor = self.LayerNorm(embeddings, embeddings_scaling_factor)
142
+ embeddings = self.dropout(embeddings)
143
+ embeddings, embeddings_scaling_factor = self.output_activation(embeddings, embeddings_scaling_factor)
144
+ return embeddings, embeddings_scaling_factor
145
+
146
+ def create_position_ids_from_inputs_embeds(self, inputs_embeds):
147
+ """
148
+ We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids.
149
+
150
+ Args:
151
+ inputs_embeds: torch.Tensor
152
+
153
+ Returns: torch.Tensor
154
+ """
155
+ input_shape = inputs_embeds.size()[:-1]
156
+ sequence_length = input_shape[1]
157
+
158
+ position_ids = torch.arange(
159
+ self.padding_idx + 1, sequence_length + self.padding_idx + 1, dtype=torch.long, device=inputs_embeds.device
160
+ )
161
+ return position_ids.unsqueeze(0).expand(input_shape)
162
+
163
+
164
+ class IBertSelfAttention(nn.Module):
165
+ def __init__(self, config):
166
+ super().__init__()
167
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
168
+ raise ValueError(
169
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
170
+ f"heads ({config.num_attention_heads})"
171
+ )
172
+ self.quant_mode = config.quant_mode
173
+ self.weight_bit = 8
174
+ self.bias_bit = 32
175
+ self.act_bit = 8
176
+
177
+ self.num_attention_heads = config.num_attention_heads
178
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
179
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
180
+
181
+ # Q, K, V Linear layers
182
+ self.query = QuantLinear(
183
+ config.hidden_size,
184
+ self.all_head_size,
185
+ bias=True,
186
+ weight_bit=self.weight_bit,
187
+ bias_bit=self.bias_bit,
188
+ quant_mode=self.quant_mode,
189
+ per_channel=True,
190
+ )
191
+ self.key = QuantLinear(
192
+ config.hidden_size,
193
+ self.all_head_size,
194
+ bias=True,
195
+ weight_bit=self.weight_bit,
196
+ bias_bit=self.bias_bit,
197
+ quant_mode=self.quant_mode,
198
+ per_channel=True,
199
+ )
200
+ self.value = QuantLinear(
201
+ config.hidden_size,
202
+ self.all_head_size,
203
+ bias=True,
204
+ weight_bit=self.weight_bit,
205
+ bias_bit=self.bias_bit,
206
+ quant_mode=self.quant_mode,
207
+ per_channel=True,
208
+ )
209
+
210
+ # Requantization (32bit -> 8bit) for Q, K, V activations
211
+ self.query_activation = QuantAct(self.act_bit, quant_mode=self.quant_mode)
212
+ self.key_activation = QuantAct(self.act_bit, quant_mode=self.quant_mode)
213
+ self.value_activation = QuantAct(self.act_bit, quant_mode=self.quant_mode)
214
+ self.output_activation = QuantAct(self.act_bit, quant_mode=self.quant_mode)
215
+
216
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
217
+
218
+ self.softmax = IntSoftmax(self.act_bit, quant_mode=self.quant_mode, force_dequant=config.force_dequant)
219
+
220
+ def forward(
221
+ self,
222
+ hidden_states,
223
+ hidden_states_scaling_factor,
224
+ attention_mask=None,
225
+ output_attentions=False,
226
+ ):
227
+ # Projection
228
+ mixed_query_layer, mixed_query_layer_scaling_factor = self.query(hidden_states, hidden_states_scaling_factor)
229
+ mixed_key_layer, mixed_key_layer_scaling_factor = self.key(hidden_states, hidden_states_scaling_factor)
230
+ mixed_value_layer, mixed_value_layer_scaling_factor = self.value(hidden_states, hidden_states_scaling_factor)
231
+
232
+ # Requantization
233
+ query_layer, query_layer_scaling_factor = self.query_activation(
234
+ mixed_query_layer, mixed_query_layer_scaling_factor
235
+ )
236
+ key_layer, key_layer_scaling_factor = self.key_activation(mixed_key_layer, mixed_key_layer_scaling_factor)
237
+ value_layer, value_layer_scaling_factor = self.value_activation(
238
+ mixed_value_layer, mixed_value_layer_scaling_factor
239
+ )
240
+
241
+ # Transpose
242
+ input_shape = hidden_states.shape[:-1]
243
+ hidden_shape = (*input_shape, -1, self.attention_head_size)
244
+ query_layer = query_layer.view(hidden_shape).transpose(1, 2)
245
+ key_layer = key_layer.view(hidden_shape).transpose(1, 2)
246
+ value_layer = value_layer.view(hidden_shape).transpose(1, 2)
247
+
248
+ # Take the dot product between "query" and "key" to get the raw attention scores.
249
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
250
+ scale = math.sqrt(self.attention_head_size)
251
+ attention_scores = attention_scores / scale
252
+ if self.quant_mode:
253
+ attention_scores_scaling_factor = query_layer_scaling_factor * key_layer_scaling_factor / scale
254
+ else:
255
+ attention_scores_scaling_factor = None
256
+
257
+ if attention_mask is not None:
258
+ # Apply the attention mask is (precomputed for all layers in IBertModel forward() function)
259
+ attention_scores = attention_scores + attention_mask
260
+
261
+ # Normalize the attention scores to probabilities.
262
+ attention_probs, attention_probs_scaling_factor = self.softmax(
263
+ attention_scores, attention_scores_scaling_factor
264
+ )
265
+
266
+ # This is actually dropping out entire tokens to attend to, which might
267
+ # seem a bit unusual, but is taken from the original Transformer paper.
268
+ attention_probs = self.dropout(attention_probs)
269
+
270
+ context_layer = torch.matmul(attention_probs, value_layer)
271
+ if attention_probs_scaling_factor is not None:
272
+ context_layer_scaling_factor = attention_probs_scaling_factor * value_layer_scaling_factor
273
+ else:
274
+ context_layer_scaling_factor = None
275
+
276
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
277
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
278
+ context_layer = context_layer.view(*new_context_layer_shape)
279
+
280
+ # requantization: 32-bit -> 8-bit
281
+ context_layer, context_layer_scaling_factor = self.output_activation(
282
+ context_layer, context_layer_scaling_factor
283
+ )
284
+
285
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
286
+ output_scaling_factor = (
287
+ (context_layer_scaling_factor, attention_probs_scaling_factor)
288
+ if output_attentions
289
+ else (context_layer_scaling_factor,)
290
+ )
291
+
292
+ return outputs, output_scaling_factor
293
+
294
+
295
+ class IBertSelfOutput(nn.Module):
296
+ def __init__(self, config):
297
+ super().__init__()
298
+ self.quant_mode = config.quant_mode
299
+ self.act_bit = 8
300
+ self.weight_bit = 8
301
+ self.bias_bit = 32
302
+ self.ln_input_bit = 22
303
+ self.ln_output_bit = 32
304
+
305
+ self.dense = QuantLinear(
306
+ config.hidden_size,
307
+ config.hidden_size,
308
+ bias=True,
309
+ weight_bit=self.weight_bit,
310
+ bias_bit=self.bias_bit,
311
+ quant_mode=self.quant_mode,
312
+ per_channel=True,
313
+ )
314
+ self.ln_input_act = QuantAct(self.ln_input_bit, quant_mode=self.quant_mode)
315
+ self.LayerNorm = IntLayerNorm(
316
+ config.hidden_size,
317
+ eps=config.layer_norm_eps,
318
+ output_bit=self.ln_output_bit,
319
+ quant_mode=self.quant_mode,
320
+ force_dequant=config.force_dequant,
321
+ )
322
+ self.output_activation = QuantAct(self.act_bit, quant_mode=self.quant_mode)
323
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
324
+
325
+ def forward(self, hidden_states, hidden_states_scaling_factor, input_tensor, input_tensor_scaling_factor):
326
+ hidden_states, hidden_states_scaling_factor = self.dense(hidden_states, hidden_states_scaling_factor)
327
+ hidden_states = self.dropout(hidden_states)
328
+ hidden_states, hidden_states_scaling_factor = self.ln_input_act(
329
+ hidden_states,
330
+ hidden_states_scaling_factor,
331
+ identity=input_tensor,
332
+ identity_scaling_factor=input_tensor_scaling_factor,
333
+ )
334
+ hidden_states, hidden_states_scaling_factor = self.LayerNorm(hidden_states, hidden_states_scaling_factor)
335
+
336
+ hidden_states, hidden_states_scaling_factor = self.output_activation(
337
+ hidden_states, hidden_states_scaling_factor
338
+ )
339
+ return hidden_states, hidden_states_scaling_factor
340
+
341
+
342
+ class IBertAttention(nn.Module):
343
+ def __init__(self, config):
344
+ super().__init__()
345
+ self.quant_mode = config.quant_mode
346
+ self.self = IBertSelfAttention(config)
347
+ self.output = IBertSelfOutput(config)
348
+
349
+ def forward(
350
+ self,
351
+ hidden_states,
352
+ hidden_states_scaling_factor,
353
+ attention_mask=None,
354
+ output_attentions=False,
355
+ ):
356
+ self_outputs, self_outputs_scaling_factor = self.self(
357
+ hidden_states,
358
+ hidden_states_scaling_factor,
359
+ attention_mask,
360
+ output_attentions,
361
+ )
362
+ attention_output, attention_output_scaling_factor = self.output(
363
+ self_outputs[0], self_outputs_scaling_factor[0], hidden_states, hidden_states_scaling_factor
364
+ )
365
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
366
+ outputs_scaling_factor = (attention_output_scaling_factor,) + self_outputs_scaling_factor[1:]
367
+ return outputs, outputs_scaling_factor
368
+
369
+
370
+ class IBertIntermediate(nn.Module):
371
+ def __init__(self, config):
372
+ super().__init__()
373
+ self.quant_mode = config.quant_mode
374
+ self.act_bit = 8
375
+ self.weight_bit = 8
376
+ self.bias_bit = 32
377
+ self.dense = QuantLinear(
378
+ config.hidden_size,
379
+ config.intermediate_size,
380
+ bias=True,
381
+ weight_bit=self.weight_bit,
382
+ bias_bit=self.bias_bit,
383
+ quant_mode=self.quant_mode,
384
+ per_channel=True,
385
+ )
386
+ if config.hidden_act != "gelu":
387
+ raise ValueError("I-BERT only supports 'gelu' for `config.hidden_act`")
388
+ self.intermediate_act_fn = IntGELU(quant_mode=self.quant_mode, force_dequant=config.force_dequant)
389
+ self.output_activation = QuantAct(self.act_bit, quant_mode=self.quant_mode)
390
+
391
+ def forward(self, hidden_states, hidden_states_scaling_factor):
392
+ hidden_states, hidden_states_scaling_factor = self.dense(hidden_states, hidden_states_scaling_factor)
393
+ hidden_states, hidden_states_scaling_factor = self.intermediate_act_fn(
394
+ hidden_states, hidden_states_scaling_factor
395
+ )
396
+
397
+ # Requantization: 32bit -> 8-bit
398
+ hidden_states, hidden_states_scaling_factor = self.output_activation(
399
+ hidden_states, hidden_states_scaling_factor
400
+ )
401
+ return hidden_states, hidden_states_scaling_factor
402
+
403
+
404
+ class IBertOutput(nn.Module):
405
+ def __init__(self, config):
406
+ super().__init__()
407
+ self.quant_mode = config.quant_mode
408
+ self.act_bit = 8
409
+ self.weight_bit = 8
410
+ self.bias_bit = 32
411
+ self.ln_input_bit = 22
412
+ self.ln_output_bit = 32
413
+
414
+ self.dense = QuantLinear(
415
+ config.intermediate_size,
416
+ config.hidden_size,
417
+ bias=True,
418
+ weight_bit=self.weight_bit,
419
+ bias_bit=self.bias_bit,
420
+ quant_mode=self.quant_mode,
421
+ per_channel=True,
422
+ )
423
+ self.ln_input_act = QuantAct(self.ln_input_bit, quant_mode=self.quant_mode)
424
+ self.LayerNorm = IntLayerNorm(
425
+ config.hidden_size,
426
+ eps=config.layer_norm_eps,
427
+ output_bit=self.ln_output_bit,
428
+ quant_mode=self.quant_mode,
429
+ force_dequant=config.force_dequant,
430
+ )
431
+ self.output_activation = QuantAct(self.act_bit, quant_mode=self.quant_mode)
432
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
433
+
434
+ def forward(self, hidden_states, hidden_states_scaling_factor, input_tensor, input_tensor_scaling_factor):
435
+ hidden_states, hidden_states_scaling_factor = self.dense(hidden_states, hidden_states_scaling_factor)
436
+ hidden_states = self.dropout(hidden_states)
437
+ hidden_states, hidden_states_scaling_factor = self.ln_input_act(
438
+ hidden_states,
439
+ hidden_states_scaling_factor,
440
+ identity=input_tensor,
441
+ identity_scaling_factor=input_tensor_scaling_factor,
442
+ )
443
+ hidden_states, hidden_states_scaling_factor = self.LayerNorm(hidden_states, hidden_states_scaling_factor)
444
+
445
+ hidden_states, hidden_states_scaling_factor = self.output_activation(
446
+ hidden_states, hidden_states_scaling_factor
447
+ )
448
+ return hidden_states, hidden_states_scaling_factor
449
+
450
+
451
+ class IBertLayer(nn.Module):
452
+ def __init__(self, config):
453
+ super().__init__()
454
+ self.quant_mode = config.quant_mode
455
+ self.act_bit = 8
456
+
457
+ self.seq_len_dim = 1
458
+ self.attention = IBertAttention(config)
459
+ self.intermediate = IBertIntermediate(config)
460
+ self.output = IBertOutput(config)
461
+
462
+ self.pre_intermediate_act = QuantAct(self.act_bit, quant_mode=self.quant_mode)
463
+ self.pre_output_act = QuantAct(self.act_bit, quant_mode=self.quant_mode)
464
+
465
+ def forward(
466
+ self,
467
+ hidden_states,
468
+ hidden_states_scaling_factor,
469
+ attention_mask=None,
470
+ output_attentions=False,
471
+ ):
472
+ self_attention_outputs, self_attention_outputs_scaling_factor = self.attention(
473
+ hidden_states,
474
+ hidden_states_scaling_factor,
475
+ attention_mask,
476
+ output_attentions=output_attentions,
477
+ )
478
+ attention_output = self_attention_outputs[0]
479
+ attention_output_scaling_factor = self_attention_outputs_scaling_factor[0]
480
+
481
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
482
+
483
+ layer_output, layer_output_scaling_factor = self.feed_forward_chunk(
484
+ attention_output, attention_output_scaling_factor
485
+ )
486
+ outputs = (layer_output,) + outputs
487
+
488
+ return outputs
489
+
490
+ def feed_forward_chunk(self, attention_output, attention_output_scaling_factor):
491
+ attention_output, attention_output_scaling_factor = self.pre_intermediate_act(
492
+ attention_output, attention_output_scaling_factor
493
+ )
494
+ intermediate_output, intermediate_output_scaling_factor = self.intermediate(
495
+ attention_output, attention_output_scaling_factor
496
+ )
497
+
498
+ intermediate_output, intermediate_output_scaling_factor = self.pre_output_act(
499
+ intermediate_output, intermediate_output_scaling_factor
500
+ )
501
+ layer_output, layer_output_scaling_factor = self.output(
502
+ intermediate_output, intermediate_output_scaling_factor, attention_output, attention_output_scaling_factor
503
+ )
504
+ return layer_output, layer_output_scaling_factor
505
+
506
+
507
+ class IBertEncoder(nn.Module):
508
+ def __init__(self, config):
509
+ super().__init__()
510
+ self.config = config
511
+ self.quant_mode = config.quant_mode
512
+ self.layer = nn.ModuleList([IBertLayer(config) for _ in range(config.num_hidden_layers)])
513
+
514
+ def forward(
515
+ self,
516
+ hidden_states,
517
+ hidden_states_scaling_factor,
518
+ attention_mask=None,
519
+ output_attentions=False,
520
+ output_hidden_states=False,
521
+ return_dict=True,
522
+ ):
523
+ all_hidden_states = () if output_hidden_states else None
524
+ all_self_attentions = () if output_attentions else None
525
+ all_cross_attentions = None # `config.add_cross_attention` is not supported
526
+
527
+ for i, layer_module in enumerate(self.layer):
528
+ if output_hidden_states:
529
+ all_hidden_states = all_hidden_states + (hidden_states,)
530
+
531
+ layer_outputs = layer_module(
532
+ hidden_states,
533
+ hidden_states_scaling_factor,
534
+ attention_mask,
535
+ output_attentions,
536
+ )
537
+
538
+ hidden_states = layer_outputs[0]
539
+ if output_attentions:
540
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
541
+
542
+ if output_hidden_states:
543
+ all_hidden_states = all_hidden_states + (hidden_states,)
544
+
545
+ if not return_dict:
546
+ return tuple(
547
+ v
548
+ for v in [
549
+ hidden_states,
550
+ all_hidden_states,
551
+ all_self_attentions,
552
+ all_cross_attentions,
553
+ ]
554
+ if v is not None
555
+ )
556
+ return BaseModelOutputWithPastAndCrossAttentions(
557
+ last_hidden_state=hidden_states,
558
+ hidden_states=all_hidden_states,
559
+ attentions=all_self_attentions,
560
+ cross_attentions=all_cross_attentions,
561
+ )
562
+
563
+
564
+ class IBertPooler(nn.Module):
565
+ def __init__(self, config):
566
+ super().__init__()
567
+ self.quant_mode = config.quant_mode
568
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
569
+ self.activation = nn.Tanh()
570
+
571
+ def forward(self, hidden_states):
572
+ # We "pool" the model by simply taking the hidden state corresponding
573
+ # to the first token.
574
+ first_token_tensor = hidden_states[:, 0]
575
+ pooled_output = self.dense(first_token_tensor)
576
+ pooled_output = self.activation(pooled_output)
577
+ return pooled_output
578
+
579
+
580
+ @auto_docstring
581
+ class IBertPreTrainedModel(PreTrainedModel):
582
+ config: IBertConfig
583
+ base_model_prefix = "ibert"
584
+
585
+ @torch.no_grad()
586
+ def _init_weights(self, module):
587
+ """Initialize the weights"""
588
+ if isinstance(module, (QuantLinear, nn.Linear)):
589
+ init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
590
+ if module.bias is not None:
591
+ init.zeros_(module.bias)
592
+ if getattr(module, "weight_integer", None) is not None:
593
+ init.zeros_(module.weight_integer)
594
+ init.zeros_(module.fc_scaling_factor)
595
+ if getattr(module, "bias_integer", None) is not None:
596
+ init.zeros_(module.bias_integer)
597
+ elif isinstance(module, (QuantEmbedding, nn.Embedding)):
598
+ init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
599
+ # Here we need the check explicitly, as we slice the weight in the `zeros_` call, so it looses the flag
600
+ if module.padding_idx is not None and not getattr(module.weight, "_is_hf_initialized", False):
601
+ init.zeros_(module.weight[module.padding_idx])
602
+ if getattr(module, "weight_scaling_factor", None) is not None:
603
+ init.zeros_(module.weight_scaling_factor)
604
+ init.zeros_(module.weight_integer)
605
+ elif isinstance(module, (IntLayerNorm, nn.LayerNorm)):
606
+ init.zeros_(module.bias)
607
+ init.ones_(module.weight)
608
+ if getattr(module, "shift", None) is not None:
609
+ init.zeros_(module.shift)
610
+ elif isinstance(module, IBertLMHead):
611
+ init.zeros_(module.bias)
612
+ elif isinstance(module, IBertEmbeddings):
613
+ init.copy_(module.position_ids, torch.arange(module.position_ids.shape[-1]).expand((1, -1)))
614
+ elif isinstance(module, QuantAct):
615
+ init.constant_(module.x_min, -1e-5)
616
+ init.constant_(module.x_max, 1e-5)
617
+ init.zeros_(module.act_scaling_factor)
618
+
619
+ def resize_token_embeddings(self, new_num_tokens=None):
620
+ raise NotImplementedError("`resize_token_embeddings` is not supported for I-BERT.")
621
+
622
+
623
+ @auto_docstring
624
+ class IBertModel(IBertPreTrainedModel):
625
+ """
626
+
627
+ The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
628
+ cross-attention is added between the self-attention layers, following the architecture described in [Attention is
629
+ all you need](https://huggingface.co/papers/1706.03762) by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
630
+ Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
631
+
632
+ """
633
+
634
+ def __init__(self, config, add_pooling_layer=True):
635
+ r"""
636
+ add_pooling_layer (bool, *optional*, defaults to `True`):
637
+ Whether to add a pooling layer
638
+ """
639
+ super().__init__(config)
640
+ self.config = config
641
+ self.quant_mode = config.quant_mode
642
+
643
+ self.embeddings = IBertEmbeddings(config)
644
+ self.encoder = IBertEncoder(config)
645
+
646
+ self.pooler = IBertPooler(config) if add_pooling_layer else None
647
+
648
+ # Initialize weights and apply final processing
649
+ self.post_init()
650
+
651
+ def get_input_embeddings(self):
652
+ return self.embeddings.word_embeddings
653
+
654
+ def set_input_embeddings(self, value):
655
+ self.embeddings.word_embeddings = value
656
+
657
+ @auto_docstring
658
+ def forward(
659
+ self,
660
+ input_ids: torch.LongTensor | None = None,
661
+ attention_mask: torch.FloatTensor | None = None,
662
+ token_type_ids: torch.LongTensor | None = None,
663
+ position_ids: torch.LongTensor | None = None,
664
+ inputs_embeds: torch.FloatTensor | None = None,
665
+ output_attentions: bool | None = None,
666
+ output_hidden_states: bool | None = None,
667
+ return_dict: bool | None = None,
668
+ **kwargs,
669
+ ) -> BaseModelOutputWithPoolingAndCrossAttentions | tuple[torch.FloatTensor]:
670
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
671
+ output_hidden_states = (
672
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
673
+ )
674
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
675
+
676
+ if input_ids is not None and inputs_embeds is not None:
677
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
678
+ elif input_ids is not None:
679
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
680
+ input_shape = input_ids.size()
681
+ elif inputs_embeds is not None:
682
+ input_shape = inputs_embeds.size()[:-1]
683
+ else:
684
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
685
+
686
+ batch_size, seq_length = input_shape
687
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
688
+
689
+ if attention_mask is None:
690
+ attention_mask = torch.ones(((batch_size, seq_length)), device=device)
691
+ if token_type_ids is None:
692
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
693
+
694
+ embedding_output, embedding_output_scaling_factor = self.embeddings(
695
+ input_ids=input_ids,
696
+ position_ids=position_ids,
697
+ token_type_ids=token_type_ids,
698
+ inputs_embeds=inputs_embeds,
699
+ )
700
+
701
+ attention_mask = create_bidirectional_mask(
702
+ config=self.config,
703
+ inputs_embeds=embedding_output,
704
+ attention_mask=attention_mask,
705
+ )
706
+
707
+ encoder_outputs = self.encoder(
708
+ embedding_output,
709
+ embedding_output_scaling_factor,
710
+ attention_mask=attention_mask,
711
+ output_attentions=output_attentions,
712
+ output_hidden_states=output_hidden_states,
713
+ return_dict=return_dict,
714
+ )
715
+ sequence_output = encoder_outputs[0]
716
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
717
+
718
+ if not return_dict:
719
+ return (sequence_output, pooled_output) + encoder_outputs[1:]
720
+
721
+ return BaseModelOutputWithPoolingAndCrossAttentions(
722
+ last_hidden_state=sequence_output,
723
+ pooler_output=pooled_output,
724
+ hidden_states=encoder_outputs.hidden_states,
725
+ attentions=encoder_outputs.attentions,
726
+ cross_attentions=encoder_outputs.cross_attentions,
727
+ )
728
+
729
+
730
+ @auto_docstring
731
+ class IBertForMaskedLM(IBertPreTrainedModel):
732
+ _tied_weights_keys = {
733
+ "lm_head.decoder.weight": "ibert.embeddings.word_embeddings.weight$",
734
+ "lm_head.decoder.bias": "lm_head.bias",
735
+ }
736
+
737
+ def __init__(self, config):
738
+ super().__init__(config)
739
+
740
+ self.ibert = IBertModel(config, add_pooling_layer=False)
741
+ self.lm_head = IBertLMHead(config)
742
+
743
+ # Initialize weights and apply final processing
744
+ self.post_init()
745
+
746
+ def get_output_embeddings(self):
747
+ return self.lm_head.decoder
748
+
749
+ def set_output_embeddings(self, new_embeddings):
750
+ self.lm_head.decoder = new_embeddings
751
+ self.lm_head.bias = new_embeddings.bias
752
+
753
+ @auto_docstring
754
+ def forward(
755
+ self,
756
+ input_ids: torch.LongTensor | None = None,
757
+ attention_mask: torch.FloatTensor | None = None,
758
+ token_type_ids: torch.LongTensor | None = None,
759
+ position_ids: torch.LongTensor | None = None,
760
+ inputs_embeds: torch.FloatTensor | None = None,
761
+ labels: torch.LongTensor | None = None,
762
+ output_attentions: bool | None = None,
763
+ output_hidden_states: bool | None = None,
764
+ return_dict: bool | None = None,
765
+ **kwargs,
766
+ ) -> MaskedLMOutput | tuple[torch.FloatTensor]:
767
+ r"""
768
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
769
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
770
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
771
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
772
+ """
773
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
774
+
775
+ outputs = self.ibert(
776
+ input_ids,
777
+ attention_mask=attention_mask,
778
+ token_type_ids=token_type_ids,
779
+ position_ids=position_ids,
780
+ inputs_embeds=inputs_embeds,
781
+ output_attentions=output_attentions,
782
+ output_hidden_states=output_hidden_states,
783
+ return_dict=return_dict,
784
+ )
785
+ sequence_output = outputs[0]
786
+ prediction_scores = self.lm_head(sequence_output)
787
+
788
+ masked_lm_loss = None
789
+ if labels is not None:
790
+ loss_fct = CrossEntropyLoss()
791
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
792
+
793
+ if not return_dict:
794
+ output = (prediction_scores,) + outputs[2:]
795
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
796
+
797
+ return MaskedLMOutput(
798
+ loss=masked_lm_loss,
799
+ logits=prediction_scores,
800
+ hidden_states=outputs.hidden_states,
801
+ attentions=outputs.attentions,
802
+ )
803
+
804
+
805
+ class IBertLMHead(nn.Module):
806
+ """I-BERT Head for masked language modeling."""
807
+
808
+ def __init__(self, config):
809
+ super().__init__()
810
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
811
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
812
+
813
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size)
814
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
815
+
816
+ def forward(self, features, **kwargs):
817
+ x = self.dense(features)
818
+ x = gelu(x)
819
+ x = self.layer_norm(x)
820
+
821
+ # project back to size of vocabulary with bias
822
+ x = self.decoder(x)
823
+
824
+ return x
825
+
826
+
827
+ @auto_docstring(
828
+ custom_intro="""
829
+ I-BERT Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled
830
+ output) e.g. for GLUE tasks.
831
+ """
832
+ )
833
+ class IBertForSequenceClassification(IBertPreTrainedModel):
834
+ def __init__(self, config):
835
+ super().__init__(config)
836
+ self.num_labels = config.num_labels
837
+
838
+ self.ibert = IBertModel(config, add_pooling_layer=False)
839
+ self.classifier = IBertClassificationHead(config)
840
+
841
+ # Initialize weights and apply final processing
842
+ self.post_init()
843
+
844
+ @auto_docstring
845
+ def forward(
846
+ self,
847
+ input_ids: torch.LongTensor | None = None,
848
+ attention_mask: torch.FloatTensor | None = None,
849
+ token_type_ids: torch.LongTensor | None = None,
850
+ position_ids: torch.LongTensor | None = None,
851
+ inputs_embeds: torch.FloatTensor | None = None,
852
+ labels: torch.LongTensor | None = None,
853
+ output_attentions: bool | None = None,
854
+ output_hidden_states: bool | None = None,
855
+ return_dict: bool | None = None,
856
+ **kwargs,
857
+ ) -> SequenceClassifierOutput | tuple[torch.FloatTensor]:
858
+ r"""
859
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
860
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
861
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
862
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
863
+ """
864
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
865
+
866
+ outputs = self.ibert(
867
+ input_ids,
868
+ attention_mask=attention_mask,
869
+ token_type_ids=token_type_ids,
870
+ position_ids=position_ids,
871
+ inputs_embeds=inputs_embeds,
872
+ output_attentions=output_attentions,
873
+ output_hidden_states=output_hidden_states,
874
+ return_dict=return_dict,
875
+ )
876
+ sequence_output = outputs[0]
877
+ logits = self.classifier(sequence_output)
878
+
879
+ loss = None
880
+ if labels is not None:
881
+ if self.config.problem_type is None:
882
+ if self.num_labels == 1:
883
+ self.config.problem_type = "regression"
884
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
885
+ self.config.problem_type = "single_label_classification"
886
+ else:
887
+ self.config.problem_type = "multi_label_classification"
888
+
889
+ if self.config.problem_type == "regression":
890
+ loss_fct = MSELoss()
891
+ if self.num_labels == 1:
892
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
893
+ else:
894
+ loss = loss_fct(logits, labels)
895
+ elif self.config.problem_type == "single_label_classification":
896
+ loss_fct = CrossEntropyLoss()
897
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
898
+ elif self.config.problem_type == "multi_label_classification":
899
+ loss_fct = BCEWithLogitsLoss()
900
+ loss = loss_fct(logits, labels)
901
+ if not return_dict:
902
+ output = (logits,) + outputs[2:]
903
+ return ((loss,) + output) if loss is not None else output
904
+
905
+ return SequenceClassifierOutput(
906
+ loss=loss,
907
+ logits=logits,
908
+ hidden_states=outputs.hidden_states,
909
+ attentions=outputs.attentions,
910
+ )
911
+
912
+
913
+ @auto_docstring
914
+ class IBertForMultipleChoice(IBertPreTrainedModel):
915
+ def __init__(self, config):
916
+ super().__init__(config)
917
+
918
+ self.ibert = IBertModel(config)
919
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
920
+ self.classifier = nn.Linear(config.hidden_size, 1)
921
+
922
+ # Initialize weights and apply final processing
923
+ self.post_init()
924
+
925
+ @auto_docstring
926
+ def forward(
927
+ self,
928
+ input_ids: torch.LongTensor | None = None,
929
+ token_type_ids: torch.LongTensor | None = None,
930
+ attention_mask: torch.FloatTensor | None = None,
931
+ labels: torch.LongTensor | None = None,
932
+ position_ids: torch.LongTensor | None = None,
933
+ inputs_embeds: torch.FloatTensor | None = None,
934
+ output_attentions: bool | None = None,
935
+ output_hidden_states: bool | None = None,
936
+ return_dict: bool | None = None,
937
+ **kwargs,
938
+ ) -> MultipleChoiceModelOutput | tuple[torch.FloatTensor]:
939
+ r"""
940
+ input_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`):
941
+ Indices of input sequence tokens in the vocabulary.
942
+
943
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
944
+ [`PreTrainedTokenizer.__call__`] for details.
945
+
946
+ [What are input IDs?](../glossary#input-ids)
947
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
948
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
949
+ 1]`:
950
+
951
+ - 0 corresponds to a *sentence A* token,
952
+ - 1 corresponds to a *sentence B* token.
953
+
954
+ [What are token type IDs?](../glossary#token-type-ids)
955
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
956
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
957
+ num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
958
+ `input_ids` above)
959
+ position_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
960
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
961
+ config.max_position_embeddings - 1]`.
962
+
963
+ [What are position IDs?](../glossary#position-ids)
964
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_choices, sequence_length, hidden_size)`, *optional*):
965
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
966
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
967
+ model's internal embedding lookup matrix.
968
+ """
969
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
970
+ num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
971
+
972
+ flat_input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
973
+ flat_position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
974
+ flat_token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
975
+ flat_attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
976
+ flat_inputs_embeds = (
977
+ inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
978
+ if inputs_embeds is not None
979
+ else None
980
+ )
981
+
982
+ outputs = self.ibert(
983
+ flat_input_ids,
984
+ position_ids=flat_position_ids,
985
+ token_type_ids=flat_token_type_ids,
986
+ attention_mask=flat_attention_mask,
987
+ inputs_embeds=flat_inputs_embeds,
988
+ output_attentions=output_attentions,
989
+ output_hidden_states=output_hidden_states,
990
+ return_dict=return_dict,
991
+ )
992
+ pooled_output = outputs[1]
993
+
994
+ pooled_output = self.dropout(pooled_output)
995
+ logits = self.classifier(pooled_output)
996
+ reshaped_logits = logits.view(-1, num_choices)
997
+
998
+ loss = None
999
+ if labels is not None:
1000
+ loss_fct = CrossEntropyLoss()
1001
+ loss = loss_fct(reshaped_logits, labels)
1002
+
1003
+ if not return_dict:
1004
+ output = (reshaped_logits,) + outputs[2:]
1005
+ return ((loss,) + output) if loss is not None else output
1006
+
1007
+ return MultipleChoiceModelOutput(
1008
+ loss=loss,
1009
+ logits=reshaped_logits,
1010
+ hidden_states=outputs.hidden_states,
1011
+ attentions=outputs.attentions,
1012
+ )
1013
+
1014
+
1015
+ @auto_docstring
1016
+ class IBertForTokenClassification(IBertPreTrainedModel):
1017
+ def __init__(self, config):
1018
+ super().__init__(config)
1019
+ self.num_labels = config.num_labels
1020
+
1021
+ self.ibert = IBertModel(config, add_pooling_layer=False)
1022
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
1023
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1024
+
1025
+ # Initialize weights and apply final processing
1026
+ self.post_init()
1027
+
1028
+ @auto_docstring
1029
+ def forward(
1030
+ self,
1031
+ input_ids: torch.LongTensor | None = None,
1032
+ attention_mask: torch.FloatTensor | None = None,
1033
+ token_type_ids: torch.LongTensor | None = None,
1034
+ position_ids: torch.LongTensor | None = None,
1035
+ inputs_embeds: torch.FloatTensor | None = None,
1036
+ labels: torch.LongTensor | None = None,
1037
+ output_attentions: bool | None = None,
1038
+ output_hidden_states: bool | None = None,
1039
+ return_dict: bool | None = None,
1040
+ **kwargs,
1041
+ ) -> TokenClassifierOutput | tuple[torch.FloatTensor]:
1042
+ r"""
1043
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1044
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
1045
+ """
1046
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1047
+
1048
+ outputs = self.ibert(
1049
+ input_ids,
1050
+ attention_mask=attention_mask,
1051
+ token_type_ids=token_type_ids,
1052
+ position_ids=position_ids,
1053
+ inputs_embeds=inputs_embeds,
1054
+ output_attentions=output_attentions,
1055
+ output_hidden_states=output_hidden_states,
1056
+ return_dict=return_dict,
1057
+ )
1058
+
1059
+ sequence_output = outputs[0]
1060
+
1061
+ sequence_output = self.dropout(sequence_output)
1062
+ logits = self.classifier(sequence_output)
1063
+
1064
+ loss = None
1065
+ if labels is not None:
1066
+ loss_fct = CrossEntropyLoss()
1067
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1068
+
1069
+ if not return_dict:
1070
+ output = (logits,) + outputs[2:]
1071
+ return ((loss,) + output) if loss is not None else output
1072
+
1073
+ return TokenClassifierOutput(
1074
+ loss=loss,
1075
+ logits=logits,
1076
+ hidden_states=outputs.hidden_states,
1077
+ attentions=outputs.attentions,
1078
+ )
1079
+
1080
+
1081
+ class IBertClassificationHead(nn.Module):
1082
+ """Head for sentence-level classification tasks."""
1083
+
1084
+ def __init__(self, config):
1085
+ super().__init__()
1086
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
1087
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
1088
+ self.out_proj = nn.Linear(config.hidden_size, config.num_labels)
1089
+
1090
+ def forward(self, features, **kwargs):
1091
+ hidden_states = features[:, 0, :] # take <s> token (equiv. to [CLS])
1092
+ hidden_states = self.dropout(hidden_states)
1093
+ hidden_states = self.dense(hidden_states)
1094
+ hidden_states = torch.tanh(hidden_states)
1095
+ hidden_states = self.dropout(hidden_states)
1096
+ hidden_states = self.out_proj(hidden_states)
1097
+ return hidden_states
1098
+
1099
+
1100
+ @auto_docstring
1101
+ class IBertForQuestionAnswering(IBertPreTrainedModel):
1102
+ def __init__(self, config):
1103
+ super().__init__(config)
1104
+ self.num_labels = config.num_labels
1105
+
1106
+ self.ibert = IBertModel(config, add_pooling_layer=False)
1107
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
1108
+
1109
+ # Initialize weights and apply final processing
1110
+ self.post_init()
1111
+
1112
+ @auto_docstring
1113
+ def forward(
1114
+ self,
1115
+ input_ids: torch.LongTensor | None = None,
1116
+ attention_mask: torch.FloatTensor | None = None,
1117
+ token_type_ids: torch.LongTensor | None = None,
1118
+ position_ids: torch.LongTensor | None = None,
1119
+ inputs_embeds: torch.FloatTensor | None = None,
1120
+ start_positions: torch.LongTensor | None = None,
1121
+ end_positions: torch.LongTensor | None = None,
1122
+ output_attentions: bool | None = None,
1123
+ output_hidden_states: bool | None = None,
1124
+ return_dict: bool | None = None,
1125
+ **kwargs,
1126
+ ) -> QuestionAnsweringModelOutput | tuple[torch.FloatTensor]:
1127
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1128
+
1129
+ outputs = self.ibert(
1130
+ input_ids,
1131
+ attention_mask=attention_mask,
1132
+ token_type_ids=token_type_ids,
1133
+ position_ids=position_ids,
1134
+ inputs_embeds=inputs_embeds,
1135
+ output_attentions=output_attentions,
1136
+ output_hidden_states=output_hidden_states,
1137
+ return_dict=return_dict,
1138
+ )
1139
+
1140
+ sequence_output = outputs[0]
1141
+
1142
+ logits = self.qa_outputs(sequence_output)
1143
+ start_logits, end_logits = logits.split(1, dim=-1)
1144
+ start_logits = start_logits.squeeze(-1).contiguous()
1145
+ end_logits = end_logits.squeeze(-1).contiguous()
1146
+
1147
+ total_loss = None
1148
+ if start_positions is not None and end_positions is not None:
1149
+ # If we are on multi-GPU, split add a dimension
1150
+ if len(start_positions.size()) > 1:
1151
+ start_positions = start_positions.squeeze(-1)
1152
+ if len(end_positions.size()) > 1:
1153
+ end_positions = end_positions.squeeze(-1)
1154
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1155
+ ignored_index = start_logits.size(1)
1156
+ start_positions = start_positions.clamp(0, ignored_index)
1157
+ end_positions = end_positions.clamp(0, ignored_index)
1158
+
1159
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1160
+ start_loss = loss_fct(start_logits, start_positions)
1161
+ end_loss = loss_fct(end_logits, end_positions)
1162
+ total_loss = (start_loss + end_loss) / 2
1163
+
1164
+ if not return_dict:
1165
+ output = (start_logits, end_logits) + outputs[2:]
1166
+ return ((total_loss,) + output) if total_loss is not None else output
1167
+
1168
+ return QuestionAnsweringModelOutput(
1169
+ loss=total_loss,
1170
+ start_logits=start_logits,
1171
+ end_logits=end_logits,
1172
+ hidden_states=outputs.hidden_states,
1173
+ attentions=outputs.attentions,
1174
+ )
1175
+
1176
+
1177
+ def create_position_ids_from_input_ids(input_ids, padding_idx, past_key_values_length=0):
1178
+ """
1179
+ Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols
1180
+ are ignored. This is modified from fairseq's *utils.make_positions*.
1181
+
1182
+ Args:
1183
+ input_ids (`torch.LongTensor`):
1184
+ Indices of input sequence tokens in the vocabulary.
1185
+
1186
+ Returns: torch.Tensor
1187
+ """
1188
+ # The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA.
1189
+ mask = input_ids.ne(padding_idx).int()
1190
+ incremental_indices = (torch.cumsum(mask, dim=1).type_as(mask) + past_key_values_length) * mask
1191
+ return incremental_indices.long() + padding_idx
1192
+
1193
+
1194
+ __all__ = [
1195
+ "IBertForMaskedLM",
1196
+ "IBertForMultipleChoice",
1197
+ "IBertForQuestionAnswering",
1198
+ "IBertForSequenceClassification",
1199
+ "IBertForTokenClassification",
1200
+ "IBertModel",
1201
+ "IBertPreTrainedModel",
1202
+ ]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/mobilevitv2/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_mobilevitv2 import *
22
+ from .modeling_mobilevitv2 import *
23
+ else:
24
+ import sys
25
+
26
+ _file = globals()["__file__"]
27
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/mobilevitv2/modeling_mobilevitv2.py ADDED
@@ -0,0 +1,942 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 Apple Inc. and The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # Original license: https://github.com/apple/ml-cvnets/blob/main/LICENSE
16
+ """PyTorch MobileViTV2 model."""
17
+
18
+ import torch
19
+ from torch import nn
20
+ from torch.nn import CrossEntropyLoss
21
+
22
+ from ... import initialization as init
23
+ from ...activations import ACT2FN
24
+ from ...modeling_layers import GradientCheckpointingLayer
25
+ from ...modeling_outputs import (
26
+ BaseModelOutputWithNoAttention,
27
+ BaseModelOutputWithPoolingAndNoAttention,
28
+ ImageClassifierOutputWithNoAttention,
29
+ SemanticSegmenterOutput,
30
+ )
31
+ from ...modeling_utils import PreTrainedModel
32
+ from ...utils import auto_docstring, logging
33
+ from .configuration_mobilevitv2 import MobileViTV2Config
34
+
35
+
36
+ logger = logging.get_logger(__name__)
37
+
38
+
39
+ # Copied from transformers.models.mobilevit.modeling_mobilevit.make_divisible
40
+ def make_divisible(value: int, divisor: int = 8, min_value: int | None = None) -> int:
41
+ """
42
+ Ensure that all layers have a channel count that is divisible by `divisor`.
43
+ """
44
+ if min_value is None:
45
+ min_value = divisor
46
+ new_value = max(min_value, int(value + divisor / 2) // divisor * divisor)
47
+ # Make sure that round down does not go down by more than 10%.
48
+ if new_value < 0.9 * value:
49
+ new_value += divisor
50
+ return int(new_value)
51
+
52
+
53
+ def clip(value: float, min_val: float = float("-inf"), max_val: float = float("inf")) -> float:
54
+ return max(min_val, min(max_val, value))
55
+
56
+
57
+ # Copied from transformers.models.mobilevit.modeling_mobilevit.MobileViTConvLayer with MobileViT->MobileViTV2
58
+ class MobileViTV2ConvLayer(nn.Module):
59
+ def __init__(
60
+ self,
61
+ config: MobileViTV2Config,
62
+ in_channels: int,
63
+ out_channels: int,
64
+ kernel_size: int,
65
+ stride: int = 1,
66
+ groups: int = 1,
67
+ bias: bool = False,
68
+ dilation: int = 1,
69
+ use_normalization: bool = True,
70
+ use_activation: bool | str = True,
71
+ ) -> None:
72
+ super().__init__()
73
+ padding = int((kernel_size - 1) / 2) * dilation
74
+
75
+ if in_channels % groups != 0:
76
+ raise ValueError(f"Input channels ({in_channels}) are not divisible by {groups} groups.")
77
+ if out_channels % groups != 0:
78
+ raise ValueError(f"Output channels ({out_channels}) are not divisible by {groups} groups.")
79
+
80
+ self.convolution = nn.Conv2d(
81
+ in_channels=in_channels,
82
+ out_channels=out_channels,
83
+ kernel_size=kernel_size,
84
+ stride=stride,
85
+ padding=padding,
86
+ dilation=dilation,
87
+ groups=groups,
88
+ bias=bias,
89
+ padding_mode="zeros",
90
+ )
91
+
92
+ if use_normalization:
93
+ self.normalization = nn.BatchNorm2d(
94
+ num_features=out_channels,
95
+ eps=1e-5,
96
+ momentum=0.1,
97
+ affine=True,
98
+ track_running_stats=True,
99
+ )
100
+ else:
101
+ self.normalization = None
102
+
103
+ if use_activation:
104
+ if isinstance(use_activation, str):
105
+ self.activation = ACT2FN[use_activation]
106
+ elif isinstance(config.hidden_act, str):
107
+ self.activation = ACT2FN[config.hidden_act]
108
+ else:
109
+ self.activation = config.hidden_act
110
+ else:
111
+ self.activation = None
112
+
113
+ def forward(self, features: torch.Tensor) -> torch.Tensor:
114
+ features = self.convolution(features)
115
+ if self.normalization is not None:
116
+ features = self.normalization(features)
117
+ if self.activation is not None:
118
+ features = self.activation(features)
119
+ return features
120
+
121
+
122
+ # Copied from transformers.models.mobilevit.modeling_mobilevit.MobileViTInvertedResidual with MobileViT->MobileViTV2
123
+ class MobileViTV2InvertedResidual(nn.Module):
124
+ """
125
+ Inverted residual block (MobileNetv2): https://huggingface.co/papers/1801.04381
126
+ """
127
+
128
+ def __init__(
129
+ self, config: MobileViTV2Config, in_channels: int, out_channels: int, stride: int, dilation: int = 1
130
+ ) -> None:
131
+ super().__init__()
132
+ expanded_channels = make_divisible(int(round(in_channels * config.expand_ratio)), 8)
133
+
134
+ if stride not in [1, 2]:
135
+ raise ValueError(f"Invalid stride {stride}.")
136
+
137
+ self.use_residual = (stride == 1) and (in_channels == out_channels)
138
+
139
+ self.expand_1x1 = MobileViTV2ConvLayer(
140
+ config, in_channels=in_channels, out_channels=expanded_channels, kernel_size=1
141
+ )
142
+
143
+ self.conv_3x3 = MobileViTV2ConvLayer(
144
+ config,
145
+ in_channels=expanded_channels,
146
+ out_channels=expanded_channels,
147
+ kernel_size=3,
148
+ stride=stride,
149
+ groups=expanded_channels,
150
+ dilation=dilation,
151
+ )
152
+
153
+ self.reduce_1x1 = MobileViTV2ConvLayer(
154
+ config,
155
+ in_channels=expanded_channels,
156
+ out_channels=out_channels,
157
+ kernel_size=1,
158
+ use_activation=False,
159
+ )
160
+
161
+ def forward(self, features: torch.Tensor) -> torch.Tensor:
162
+ residual = features
163
+
164
+ features = self.expand_1x1(features)
165
+ features = self.conv_3x3(features)
166
+ features = self.reduce_1x1(features)
167
+
168
+ return residual + features if self.use_residual else features
169
+
170
+
171
+ # Copied from transformers.models.mobilevit.modeling_mobilevit.MobileViTMobileNetLayer with MobileViT->MobileViTV2
172
+ class MobileViTV2MobileNetLayer(nn.Module):
173
+ def __init__(
174
+ self, config: MobileViTV2Config, in_channels: int, out_channels: int, stride: int = 1, num_stages: int = 1
175
+ ) -> None:
176
+ super().__init__()
177
+
178
+ self.layer = nn.ModuleList()
179
+ for i in range(num_stages):
180
+ layer = MobileViTV2InvertedResidual(
181
+ config,
182
+ in_channels=in_channels,
183
+ out_channels=out_channels,
184
+ stride=stride if i == 0 else 1,
185
+ )
186
+ self.layer.append(layer)
187
+ in_channels = out_channels
188
+
189
+ def forward(self, features: torch.Tensor) -> torch.Tensor:
190
+ for layer_module in self.layer:
191
+ features = layer_module(features)
192
+ return features
193
+
194
+
195
+ class MobileViTV2LinearSelfAttention(nn.Module):
196
+ """
197
+ This layer applies a self-attention with linear complexity, as described in MobileViTV2 paper:
198
+ https://huggingface.co/papers/2206.02680
199
+
200
+ Args:
201
+ config (`MobileVitv2Config`):
202
+ Model configuration object
203
+ embed_dim (`int`):
204
+ `input_channels` from an expected input of size :math:`(batch_size, input_channels, height, width)`
205
+ """
206
+
207
+ def __init__(self, config: MobileViTV2Config, embed_dim: int) -> None:
208
+ super().__init__()
209
+
210
+ self.qkv_proj = MobileViTV2ConvLayer(
211
+ config=config,
212
+ in_channels=embed_dim,
213
+ out_channels=1 + (2 * embed_dim),
214
+ bias=True,
215
+ kernel_size=1,
216
+ use_normalization=False,
217
+ use_activation=False,
218
+ )
219
+
220
+ self.attn_dropout = nn.Dropout(p=config.attn_dropout)
221
+ self.out_proj = MobileViTV2ConvLayer(
222
+ config=config,
223
+ in_channels=embed_dim,
224
+ out_channels=embed_dim,
225
+ bias=True,
226
+ kernel_size=1,
227
+ use_normalization=False,
228
+ use_activation=False,
229
+ )
230
+ self.embed_dim = embed_dim
231
+
232
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
233
+ # (batch_size, embed_dim, num_pixels_in_patch, num_patches) --> (batch_size, 1+2*embed_dim, num_pixels_in_patch, num_patches)
234
+ qkv = self.qkv_proj(hidden_states)
235
+
236
+ # Project hidden_states into query, key and value
237
+ # Query --> [batch_size, 1, num_pixels_in_patch, num_patches]
238
+ # value, key --> [batch_size, embed_dim, num_pixels_in_patch, num_patches]
239
+ query, key, value = torch.split(qkv, split_size_or_sections=[1, self.embed_dim, self.embed_dim], dim=1)
240
+
241
+ # apply softmax along num_patches dimension
242
+ context_scores = torch.nn.functional.softmax(query, dim=-1)
243
+ context_scores = self.attn_dropout(context_scores)
244
+
245
+ # Compute context vector
246
+ # [batch_size, embed_dim, num_pixels_in_patch, num_patches] x [batch_size, 1, num_pixels_in_patch, num_patches] -> [batch_size, embed_dim, num_pixels_in_patch, num_patches]
247
+ context_vector = key * context_scores
248
+ # [batch_size, embed_dim, num_pixels_in_patch, num_patches] --> [batch_size, embed_dim, num_pixels_in_patch, 1]
249
+ context_vector = torch.sum(context_vector, dim=-1, keepdim=True)
250
+
251
+ # combine context vector with values
252
+ # [batch_size, embed_dim, num_pixels_in_patch, num_patches] * [batch_size, embed_dim, num_pixels_in_patch, 1] --> [batch_size, embed_dim, num_pixels_in_patch, num_patches]
253
+ out = torch.nn.functional.relu(value) * context_vector.expand_as(value)
254
+ out = self.out_proj(out)
255
+ return out
256
+
257
+
258
+ class MobileViTV2FFN(nn.Module):
259
+ def __init__(
260
+ self,
261
+ config: MobileViTV2Config,
262
+ embed_dim: int,
263
+ ffn_latent_dim: int,
264
+ ffn_dropout: float = 0.0,
265
+ ) -> None:
266
+ super().__init__()
267
+ self.conv1 = MobileViTV2ConvLayer(
268
+ config=config,
269
+ in_channels=embed_dim,
270
+ out_channels=ffn_latent_dim,
271
+ kernel_size=1,
272
+ stride=1,
273
+ bias=True,
274
+ use_normalization=False,
275
+ use_activation=True,
276
+ )
277
+ self.dropout1 = nn.Dropout(ffn_dropout)
278
+
279
+ self.conv2 = MobileViTV2ConvLayer(
280
+ config=config,
281
+ in_channels=ffn_latent_dim,
282
+ out_channels=embed_dim,
283
+ kernel_size=1,
284
+ stride=1,
285
+ bias=True,
286
+ use_normalization=False,
287
+ use_activation=False,
288
+ )
289
+ self.dropout2 = nn.Dropout(ffn_dropout)
290
+
291
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
292
+ hidden_states = self.conv1(hidden_states)
293
+ hidden_states = self.dropout1(hidden_states)
294
+ hidden_states = self.conv2(hidden_states)
295
+ hidden_states = self.dropout2(hidden_states)
296
+ return hidden_states
297
+
298
+
299
+ class MobileViTV2TransformerLayer(nn.Module):
300
+ def __init__(
301
+ self,
302
+ config: MobileViTV2Config,
303
+ embed_dim: int,
304
+ ffn_latent_dim: int,
305
+ dropout: float = 0.0,
306
+ ) -> None:
307
+ super().__init__()
308
+ self.layernorm_before = nn.GroupNorm(num_groups=1, num_channels=embed_dim, eps=config.layer_norm_eps)
309
+ self.attention = MobileViTV2LinearSelfAttention(config, embed_dim)
310
+ self.dropout1 = nn.Dropout(p=dropout)
311
+ self.layernorm_after = nn.GroupNorm(num_groups=1, num_channels=embed_dim, eps=config.layer_norm_eps)
312
+ self.ffn = MobileViTV2FFN(config, embed_dim, ffn_latent_dim, config.ffn_dropout)
313
+
314
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
315
+ layernorm_1_out = self.layernorm_before(hidden_states)
316
+ attention_output = self.attention(layernorm_1_out)
317
+ hidden_states = attention_output + hidden_states
318
+
319
+ layer_output = self.layernorm_after(hidden_states)
320
+ layer_output = self.ffn(layer_output)
321
+
322
+ layer_output = layer_output + hidden_states
323
+ return layer_output
324
+
325
+
326
+ class MobileViTV2Transformer(nn.Module):
327
+ def __init__(self, config: MobileViTV2Config, n_layers: int, d_model: int) -> None:
328
+ super().__init__()
329
+
330
+ ffn_multiplier = config.ffn_multiplier
331
+
332
+ ffn_dims = [ffn_multiplier * d_model] * n_layers
333
+
334
+ # ensure that dims are multiple of 16
335
+ ffn_dims = [int((d // 16) * 16) for d in ffn_dims]
336
+
337
+ self.layer = nn.ModuleList()
338
+ for block_idx in range(n_layers):
339
+ transformer_layer = MobileViTV2TransformerLayer(
340
+ config, embed_dim=d_model, ffn_latent_dim=ffn_dims[block_idx]
341
+ )
342
+ self.layer.append(transformer_layer)
343
+
344
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
345
+ for layer_module in self.layer:
346
+ hidden_states = layer_module(hidden_states)
347
+ return hidden_states
348
+
349
+
350
+ class MobileViTV2Layer(GradientCheckpointingLayer):
351
+ """
352
+ MobileViTV2 layer: https://huggingface.co/papers/2206.02680
353
+ """
354
+
355
+ def __init__(
356
+ self,
357
+ config: MobileViTV2Config,
358
+ in_channels: int,
359
+ out_channels: int,
360
+ attn_unit_dim: int,
361
+ n_attn_blocks: int = 2,
362
+ dilation: int = 1,
363
+ stride: int = 2,
364
+ ) -> None:
365
+ super().__init__()
366
+ self.patch_width = config.patch_size
367
+ self.patch_height = config.patch_size
368
+
369
+ cnn_out_dim = attn_unit_dim
370
+
371
+ if stride == 2:
372
+ self.downsampling_layer = MobileViTV2InvertedResidual(
373
+ config,
374
+ in_channels=in_channels,
375
+ out_channels=out_channels,
376
+ stride=stride if dilation == 1 else 1,
377
+ dilation=dilation // 2 if dilation > 1 else 1,
378
+ )
379
+ in_channels = out_channels
380
+ else:
381
+ self.downsampling_layer = None
382
+
383
+ # Local representations
384
+ self.conv_kxk = MobileViTV2ConvLayer(
385
+ config,
386
+ in_channels=in_channels,
387
+ out_channels=in_channels,
388
+ kernel_size=config.conv_kernel_size,
389
+ groups=in_channels,
390
+ )
391
+ self.conv_1x1 = MobileViTV2ConvLayer(
392
+ config,
393
+ in_channels=in_channels,
394
+ out_channels=cnn_out_dim,
395
+ kernel_size=1,
396
+ use_normalization=False,
397
+ use_activation=False,
398
+ )
399
+
400
+ # Global representations
401
+ self.transformer = MobileViTV2Transformer(config, d_model=attn_unit_dim, n_layers=n_attn_blocks)
402
+
403
+ # self.layernorm = MobileViTV2LayerNorm2D(attn_unit_dim, eps=config.layer_norm_eps)
404
+ self.layernorm = nn.GroupNorm(num_groups=1, num_channels=attn_unit_dim, eps=config.layer_norm_eps)
405
+
406
+ # Fusion
407
+ self.conv_projection = MobileViTV2ConvLayer(
408
+ config,
409
+ in_channels=cnn_out_dim,
410
+ out_channels=in_channels,
411
+ kernel_size=1,
412
+ use_normalization=True,
413
+ use_activation=False,
414
+ )
415
+
416
+ def unfolding(self, feature_map: torch.Tensor) -> tuple[torch.Tensor, tuple[int, int]]:
417
+ batch_size, in_channels, img_height, img_width = feature_map.shape
418
+ patches = nn.functional.unfold(
419
+ feature_map,
420
+ kernel_size=(self.patch_height, self.patch_width),
421
+ stride=(self.patch_height, self.patch_width),
422
+ )
423
+ patches = patches.reshape(batch_size, in_channels, self.patch_height * self.patch_width, -1)
424
+
425
+ return patches, (img_height, img_width)
426
+
427
+ def folding(self, patches: torch.Tensor, output_size: tuple[int, int]) -> torch.Tensor:
428
+ batch_size, in_dim, patch_size, n_patches = patches.shape
429
+ patches = patches.reshape(batch_size, in_dim * patch_size, n_patches)
430
+
431
+ feature_map = nn.functional.fold(
432
+ patches,
433
+ output_size=output_size,
434
+ kernel_size=(self.patch_height, self.patch_width),
435
+ stride=(self.patch_height, self.patch_width),
436
+ )
437
+
438
+ return feature_map
439
+
440
+ def forward(self, features: torch.Tensor) -> torch.Tensor:
441
+ # reduce spatial dimensions if needed
442
+ if self.downsampling_layer:
443
+ features = self.downsampling_layer(features)
444
+
445
+ # local representation
446
+ features = self.conv_kxk(features)
447
+ features = self.conv_1x1(features)
448
+
449
+ # convert feature map to patches
450
+ patches, output_size = self.unfolding(features)
451
+
452
+ # learn global representations
453
+ patches = self.transformer(patches)
454
+ patches = self.layernorm(patches)
455
+
456
+ # convert patches back to feature maps
457
+ # [batch_size, patch_height, patch_width, input_dim] --> [batch_size, input_dim, patch_height, patch_width]
458
+ features = self.folding(patches, output_size)
459
+
460
+ features = self.conv_projection(features)
461
+ return features
462
+
463
+
464
+ class MobileViTV2Encoder(nn.Module):
465
+ def __init__(self, config: MobileViTV2Config) -> None:
466
+ super().__init__()
467
+ self.config = config
468
+
469
+ self.layer = nn.ModuleList()
470
+ self.gradient_checkpointing = False
471
+
472
+ # segmentation architectures like DeepLab and PSPNet modify the strides
473
+ # of the classification backbones
474
+ dilate_layer_4 = dilate_layer_5 = False
475
+ if config.output_stride == 8:
476
+ dilate_layer_4 = True
477
+ dilate_layer_5 = True
478
+ elif config.output_stride == 16:
479
+ dilate_layer_5 = True
480
+
481
+ dilation = 1
482
+
483
+ layer_0_dim = make_divisible(
484
+ clip(value=32 * config.width_multiplier, min_val=16, max_val=64), divisor=8, min_value=16
485
+ )
486
+
487
+ layer_1_dim = make_divisible(64 * config.width_multiplier, divisor=16)
488
+ layer_2_dim = make_divisible(128 * config.width_multiplier, divisor=8)
489
+ layer_3_dim = make_divisible(256 * config.width_multiplier, divisor=8)
490
+ layer_4_dim = make_divisible(384 * config.width_multiplier, divisor=8)
491
+ layer_5_dim = make_divisible(512 * config.width_multiplier, divisor=8)
492
+
493
+ layer_1 = MobileViTV2MobileNetLayer(
494
+ config,
495
+ in_channels=layer_0_dim,
496
+ out_channels=layer_1_dim,
497
+ stride=1,
498
+ num_stages=1,
499
+ )
500
+ self.layer.append(layer_1)
501
+
502
+ layer_2 = MobileViTV2MobileNetLayer(
503
+ config,
504
+ in_channels=layer_1_dim,
505
+ out_channels=layer_2_dim,
506
+ stride=2,
507
+ num_stages=2,
508
+ )
509
+ self.layer.append(layer_2)
510
+
511
+ layer_3 = MobileViTV2Layer(
512
+ config,
513
+ in_channels=layer_2_dim,
514
+ out_channels=layer_3_dim,
515
+ attn_unit_dim=make_divisible(config.base_attn_unit_dims[0] * config.width_multiplier, divisor=8),
516
+ n_attn_blocks=config.n_attn_blocks[0],
517
+ )
518
+ self.layer.append(layer_3)
519
+
520
+ if dilate_layer_4:
521
+ dilation *= 2
522
+
523
+ layer_4 = MobileViTV2Layer(
524
+ config,
525
+ in_channels=layer_3_dim,
526
+ out_channels=layer_4_dim,
527
+ attn_unit_dim=make_divisible(config.base_attn_unit_dims[1] * config.width_multiplier, divisor=8),
528
+ n_attn_blocks=config.n_attn_blocks[1],
529
+ dilation=dilation,
530
+ )
531
+ self.layer.append(layer_4)
532
+
533
+ if dilate_layer_5:
534
+ dilation *= 2
535
+
536
+ layer_5 = MobileViTV2Layer(
537
+ config,
538
+ in_channels=layer_4_dim,
539
+ out_channels=layer_5_dim,
540
+ attn_unit_dim=make_divisible(config.base_attn_unit_dims[2] * config.width_multiplier, divisor=8),
541
+ n_attn_blocks=config.n_attn_blocks[2],
542
+ dilation=dilation,
543
+ )
544
+ self.layer.append(layer_5)
545
+
546
+ def forward(
547
+ self,
548
+ hidden_states: torch.Tensor,
549
+ output_hidden_states: bool = False,
550
+ return_dict: bool = True,
551
+ ) -> tuple | BaseModelOutputWithNoAttention:
552
+ all_hidden_states = () if output_hidden_states else None
553
+
554
+ for i, layer_module in enumerate(self.layer):
555
+ hidden_states = layer_module(hidden_states)
556
+
557
+ if output_hidden_states:
558
+ all_hidden_states = all_hidden_states + (hidden_states,)
559
+
560
+ if not return_dict:
561
+ return tuple(v for v in [hidden_states, all_hidden_states] if v is not None)
562
+
563
+ return BaseModelOutputWithNoAttention(last_hidden_state=hidden_states, hidden_states=all_hidden_states)
564
+
565
+
566
+ @auto_docstring
567
+ class MobileViTV2PreTrainedModel(PreTrainedModel):
568
+ config: MobileViTV2Config
569
+ base_model_prefix = "mobilevitv2"
570
+ main_input_name = "pixel_values"
571
+ input_modalities = ("image",)
572
+ supports_gradient_checkpointing = True
573
+ _no_split_modules = ["MobileViTV2Layer"]
574
+
575
+ @torch.no_grad()
576
+ def _init_weights(self, module: nn.Module) -> None:
577
+ """Initialize the weights"""
578
+ if isinstance(module, (nn.Linear, nn.Conv2d, nn.BatchNorm2d)):
579
+ init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
580
+ if module.bias is not None:
581
+ init.zeros_(module.bias)
582
+ if getattr(module, "running_mean", None) is not None:
583
+ init.zeros_(module.running_mean)
584
+ init.ones_(module.running_var)
585
+ init.zeros_(module.num_batches_tracked)
586
+ elif isinstance(module, nn.GroupNorm):
587
+ init.zeros_(module.bias)
588
+ init.ones_(module.weight)
589
+
590
+
591
+ @auto_docstring
592
+ class MobileViTV2Model(MobileViTV2PreTrainedModel):
593
+ def __init__(self, config: MobileViTV2Config, expand_output: bool = True):
594
+ r"""
595
+ expand_output (`bool`, *optional*, defaults to `True`):
596
+ Whether to expand the output of the model. If `True`, the model will output pooled features in addition to
597
+ hidden states. If `False`, only the hidden states will be returned.
598
+ """
599
+ super().__init__(config)
600
+ self.config = config
601
+ self.expand_output = expand_output
602
+
603
+ layer_0_dim = make_divisible(
604
+ clip(value=32 * config.width_multiplier, min_val=16, max_val=64), divisor=8, min_value=16
605
+ )
606
+
607
+ self.conv_stem = MobileViTV2ConvLayer(
608
+ config,
609
+ in_channels=config.num_channels,
610
+ out_channels=layer_0_dim,
611
+ kernel_size=3,
612
+ stride=2,
613
+ use_normalization=True,
614
+ use_activation=True,
615
+ )
616
+ self.encoder = MobileViTV2Encoder(config)
617
+
618
+ # Initialize weights and apply final processing
619
+ self.post_init()
620
+
621
+ @auto_docstring
622
+ def forward(
623
+ self,
624
+ pixel_values: torch.Tensor | None = None,
625
+ output_hidden_states: bool | None = None,
626
+ return_dict: bool | None = None,
627
+ **kwargs,
628
+ ) -> tuple | BaseModelOutputWithPoolingAndNoAttention:
629
+ output_hidden_states = (
630
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
631
+ )
632
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
633
+
634
+ if pixel_values is None:
635
+ raise ValueError("You have to specify pixel_values")
636
+
637
+ embedding_output = self.conv_stem(pixel_values)
638
+
639
+ encoder_outputs = self.encoder(
640
+ embedding_output,
641
+ output_hidden_states=output_hidden_states,
642
+ return_dict=return_dict,
643
+ )
644
+
645
+ if self.expand_output:
646
+ last_hidden_state = encoder_outputs[0]
647
+
648
+ # global average pooling: (batch_size, channels, height, width) -> (batch_size, channels)
649
+ pooled_output = torch.mean(last_hidden_state, dim=[-2, -1], keepdim=False)
650
+ else:
651
+ last_hidden_state = encoder_outputs[0]
652
+ pooled_output = None
653
+
654
+ if not return_dict:
655
+ output = (last_hidden_state, pooled_output) if pooled_output is not None else (last_hidden_state,)
656
+ return output + encoder_outputs[1:]
657
+
658
+ return BaseModelOutputWithPoolingAndNoAttention(
659
+ last_hidden_state=last_hidden_state,
660
+ pooler_output=pooled_output,
661
+ hidden_states=encoder_outputs.hidden_states,
662
+ )
663
+
664
+
665
+ @auto_docstring(
666
+ custom_intro="""
667
+ MobileViTV2 model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
668
+ ImageNet.
669
+ """
670
+ )
671
+ class MobileViTV2ForImageClassification(MobileViTV2PreTrainedModel):
672
+ def __init__(self, config: MobileViTV2Config) -> None:
673
+ super().__init__(config)
674
+
675
+ self.num_labels = config.num_labels
676
+ self.mobilevitv2 = MobileViTV2Model(config)
677
+
678
+ out_channels = make_divisible(512 * config.width_multiplier, divisor=8) # layer 5 output dimension
679
+ # Classifier head
680
+ self.classifier = (
681
+ nn.Linear(in_features=out_channels, out_features=config.num_labels)
682
+ if config.num_labels > 0
683
+ else nn.Identity()
684
+ )
685
+
686
+ # Initialize weights and apply final processing
687
+ self.post_init()
688
+
689
+ @auto_docstring
690
+ def forward(
691
+ self,
692
+ pixel_values: torch.Tensor | None = None,
693
+ output_hidden_states: bool | None = None,
694
+ labels: torch.Tensor | None = None,
695
+ return_dict: bool | None = None,
696
+ **kwargs,
697
+ ) -> tuple | ImageClassifierOutputWithNoAttention:
698
+ r"""
699
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
700
+ Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
701
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss). If
702
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
703
+ """
704
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
705
+
706
+ outputs = self.mobilevitv2(pixel_values, output_hidden_states=output_hidden_states, return_dict=return_dict)
707
+
708
+ pooled_output = outputs.pooler_output if return_dict else outputs[1]
709
+
710
+ logits = self.classifier(pooled_output)
711
+
712
+ loss = None
713
+ if labels is not None:
714
+ loss = self.loss_function(labels, logits, self.config)
715
+
716
+ if not return_dict:
717
+ output = (logits,) + outputs[2:]
718
+ return ((loss,) + output) if loss is not None else output
719
+
720
+ return ImageClassifierOutputWithNoAttention(
721
+ loss=loss,
722
+ logits=logits,
723
+ hidden_states=outputs.hidden_states,
724
+ )
725
+
726
+
727
+ # Copied from transformers.models.mobilevit.modeling_mobilevit.MobileViTASPPPooling with MobileViT->MobileViTV2
728
+ class MobileViTV2ASPPPooling(nn.Module):
729
+ def __init__(self, config: MobileViTV2Config, in_channels: int, out_channels: int) -> None:
730
+ super().__init__()
731
+
732
+ self.global_pool = nn.AdaptiveAvgPool2d(output_size=1)
733
+
734
+ self.conv_1x1 = MobileViTV2ConvLayer(
735
+ config,
736
+ in_channels=in_channels,
737
+ out_channels=out_channels,
738
+ kernel_size=1,
739
+ stride=1,
740
+ use_normalization=True,
741
+ use_activation="relu",
742
+ )
743
+
744
+ def forward(self, features: torch.Tensor) -> torch.Tensor:
745
+ spatial_size = features.shape[-2:]
746
+ features = self.global_pool(features)
747
+ features = self.conv_1x1(features)
748
+ features = nn.functional.interpolate(features, size=spatial_size, mode="bilinear", align_corners=False)
749
+ return features
750
+
751
+
752
+ class MobileViTV2ASPP(nn.Module):
753
+ """
754
+ ASPP module defined in DeepLab papers: https://huggingface.co/papers/1606.00915, https://huggingface.co/papers/1706.05587
755
+ """
756
+
757
+ def __init__(self, config: MobileViTV2Config) -> None:
758
+ super().__init__()
759
+
760
+ encoder_out_channels = make_divisible(512 * config.width_multiplier, divisor=8) # layer 5 output dimension
761
+ in_channels = encoder_out_channels
762
+ out_channels = config.aspp_out_channels
763
+
764
+ if len(config.atrous_rates) != 3:
765
+ raise ValueError("Expected 3 values for atrous_rates")
766
+
767
+ self.convs = nn.ModuleList()
768
+
769
+ in_projection = MobileViTV2ConvLayer(
770
+ config,
771
+ in_channels=in_channels,
772
+ out_channels=out_channels,
773
+ kernel_size=1,
774
+ use_activation="relu",
775
+ )
776
+ self.convs.append(in_projection)
777
+
778
+ self.convs.extend(
779
+ [
780
+ MobileViTV2ConvLayer(
781
+ config,
782
+ in_channels=in_channels,
783
+ out_channels=out_channels,
784
+ kernel_size=3,
785
+ dilation=rate,
786
+ use_activation="relu",
787
+ )
788
+ for rate in config.atrous_rates
789
+ ]
790
+ )
791
+
792
+ pool_layer = MobileViTV2ASPPPooling(config, in_channels, out_channels)
793
+ self.convs.append(pool_layer)
794
+
795
+ self.project = MobileViTV2ConvLayer(
796
+ config, in_channels=5 * out_channels, out_channels=out_channels, kernel_size=1, use_activation="relu"
797
+ )
798
+
799
+ self.dropout = nn.Dropout(p=config.aspp_dropout_prob)
800
+
801
+ def forward(self, features: torch.Tensor) -> torch.Tensor:
802
+ pyramid = []
803
+ for conv in self.convs:
804
+ pyramid.append(conv(features))
805
+ pyramid = torch.cat(pyramid, dim=1)
806
+
807
+ pooled_features = self.project(pyramid)
808
+ pooled_features = self.dropout(pooled_features)
809
+ return pooled_features
810
+
811
+
812
+ # Copied from transformers.models.mobilevit.modeling_mobilevit.MobileViTDeepLabV3 with MobileViT->MobileViTV2
813
+ class MobileViTV2DeepLabV3(nn.Module):
814
+ """
815
+ DeepLabv3 architecture: https://huggingface.co/papers/1706.05587
816
+ """
817
+
818
+ def __init__(self, config: MobileViTV2Config) -> None:
819
+ super().__init__()
820
+ self.aspp = MobileViTV2ASPP(config)
821
+
822
+ self.dropout = nn.Dropout2d(config.classifier_dropout_prob)
823
+
824
+ self.classifier = MobileViTV2ConvLayer(
825
+ config,
826
+ in_channels=config.aspp_out_channels,
827
+ out_channels=config.num_labels,
828
+ kernel_size=1,
829
+ use_normalization=False,
830
+ use_activation=False,
831
+ bias=True,
832
+ )
833
+
834
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
835
+ features = self.aspp(hidden_states[-1])
836
+ features = self.dropout(features)
837
+ features = self.classifier(features)
838
+ return features
839
+
840
+
841
+ @auto_docstring(
842
+ custom_intro="""
843
+ MobileViTV2 model with a semantic segmentation head on top, e.g. for Pascal VOC.
844
+ """
845
+ )
846
+ class MobileViTV2ForSemanticSegmentation(MobileViTV2PreTrainedModel):
847
+ def __init__(self, config: MobileViTV2Config) -> None:
848
+ super().__init__(config)
849
+
850
+ self.num_labels = config.num_labels
851
+ self.mobilevitv2 = MobileViTV2Model(config, expand_output=False)
852
+ self.segmentation_head = MobileViTV2DeepLabV3(config)
853
+
854
+ # Initialize weights and apply final processing
855
+ self.post_init()
856
+
857
+ @auto_docstring
858
+ def forward(
859
+ self,
860
+ pixel_values: torch.Tensor | None = None,
861
+ labels: torch.Tensor | None = None,
862
+ output_hidden_states: bool | None = None,
863
+ return_dict: bool | None = None,
864
+ **kwargs,
865
+ ) -> tuple | SemanticSegmenterOutput:
866
+ r"""
867
+ labels (`torch.LongTensor` of shape `(batch_size, height, width)`, *optional*):
868
+ Ground truth semantic segmentation maps for computing the loss. Indices should be in `[0, ...,
869
+ config.num_labels - 1]`. If `config.num_labels > 1`, a classification loss is computed (Cross-Entropy).
870
+
871
+ Examples:
872
+
873
+ ```python
874
+ >>> import httpx
875
+ >>> from io import BytesIO
876
+ >>> import torch
877
+ >>> from PIL import Image
878
+ >>> from transformers import AutoImageProcessor, MobileViTV2ForSemanticSegmentation
879
+
880
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
881
+ >>> with httpx.stream("GET", url) as response:
882
+ ... image = Image.open(BytesIO(response.read()))
883
+
884
+ >>> image_processor = AutoImageProcessor.from_pretrained("apple/mobilevitv2-1.0-imagenet1k-256")
885
+ >>> model = MobileViTV2ForSemanticSegmentation.from_pretrained("apple/mobilevitv2-1.0-imagenet1k-256")
886
+
887
+ >>> inputs = image_processor(images=image, return_tensors="pt")
888
+
889
+ >>> with torch.no_grad():
890
+ ... outputs = model(**inputs)
891
+
892
+ >>> # logits are of shape (batch_size, num_labels, height, width)
893
+ >>> logits = outputs.logits
894
+ ```"""
895
+ output_hidden_states = (
896
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
897
+ )
898
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
899
+
900
+ if labels is not None and self.config.num_labels == 1:
901
+ raise ValueError("The number of labels should be greater than one")
902
+
903
+ outputs = self.mobilevitv2(
904
+ pixel_values,
905
+ output_hidden_states=True, # we need the intermediate hidden states
906
+ return_dict=return_dict,
907
+ )
908
+
909
+ encoder_hidden_states = outputs.hidden_states if return_dict else outputs[1]
910
+
911
+ logits = self.segmentation_head(encoder_hidden_states)
912
+
913
+ loss = None
914
+ if labels is not None:
915
+ # upsample logits to the images' original size
916
+ upsampled_logits = nn.functional.interpolate(
917
+ logits, size=labels.shape[-2:], mode="bilinear", align_corners=False
918
+ )
919
+ loss_fct = CrossEntropyLoss(ignore_index=self.config.semantic_loss_ignore_index)
920
+ loss = loss_fct(upsampled_logits, labels)
921
+
922
+ if not return_dict:
923
+ if output_hidden_states:
924
+ output = (logits,) + outputs[1:]
925
+ else:
926
+ output = (logits,) + outputs[2:]
927
+ return ((loss,) + output) if loss is not None else output
928
+
929
+ return SemanticSegmenterOutput(
930
+ loss=loss,
931
+ logits=logits,
932
+ hidden_states=outputs.hidden_states if output_hidden_states else None,
933
+ attentions=None,
934
+ )
935
+
936
+
937
+ __all__ = [
938
+ "MobileViTV2ForImageClassification",
939
+ "MobileViTV2ForSemanticSegmentation",
940
+ "MobileViTV2Model",
941
+ "MobileViTV2PreTrainedModel",
942
+ ]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/musicgen_melody/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_musicgen_melody import *
22
+ from .modeling_musicgen_melody import *
23
+ else:
24
+ import sys
25
+
26
+ _file = globals()["__file__"]
27
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/musicgen_melody/feature_extraction_musicgen_melody.py ADDED
@@ -0,0 +1,334 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Meta AI and The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """
15
+ Feature extractor class for Musicgen Melody
16
+ """
17
+
18
+ import copy
19
+ from typing import Any
20
+
21
+ import numpy as np
22
+
23
+ from ...audio_utils import chroma_filter_bank
24
+ from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
25
+ from ...feature_extraction_utils import BatchFeature
26
+ from ...utils import TensorType, is_torch_available, is_torchaudio_available, logging
27
+ from ...utils.import_utils import requires
28
+
29
+
30
+ if is_torch_available():
31
+ import torch
32
+
33
+ if is_torchaudio_available():
34
+ import torchaudio
35
+
36
+ logger = logging.get_logger(__name__)
37
+
38
+
39
+ @requires(backends=("torchaudio",))
40
+ class MusicgenMelodyFeatureExtractor(SequenceFeatureExtractor):
41
+ r"""
42
+ Constructs a MusicgenMelody feature extractor.
43
+
44
+ This feature extractor inherits from [`~feature_extraction_sequence_utils.SequenceFeatureExtractor`] which contains
45
+ most of the main methods. Users should refer to this superclass for more information regarding those methods.
46
+
47
+ This class extracts chroma features from audio processed by [Demucs](https://github.com/adefossez/demucs/tree/main) or
48
+ directly from raw audio waveform.
49
+
50
+ Args:
51
+ feature_size (`int`, *optional*, defaults to 12):
52
+ The feature dimension of the extracted features.
53
+ sampling_rate (`int`, *optional*, defaults to 32000):
54
+ The sampling rate at which the audio files should be digitalized expressed in hertz (Hz).
55
+ hop_length (`int`, *optional*, defaults to 4096):
56
+ Length of the overlapping windows for the STFT used to obtain the Mel Frequency coefficients.
57
+ chunk_length (`int`, *optional*, defaults to 30):
58
+ The maximum number of chunks of `sampling_rate` samples used to trim and pad longer or shorter audio
59
+ sequences.
60
+ n_fft (`int`, *optional*, defaults to 16384):
61
+ Size of the Fourier transform.
62
+ num_chroma (`int`, *optional*, defaults to 12):
63
+ Number of chroma bins to use.
64
+ padding_value (`float`, *optional*, defaults to 0.0):
65
+ Padding value used to pad the audio.
66
+ return_attention_mask (`bool`, *optional*, defaults to `False`):
67
+ Whether to return the attention mask. Can be overwritten when calling the feature extractor.
68
+
69
+ [What are attention masks?](../glossary#attention-mask)
70
+
71
+ <Tip>
72
+
73
+ For Whisper models, `attention_mask` should always be passed for batched inference, to avoid subtle
74
+ bugs.
75
+
76
+ </Tip>
77
+ stem_indices (`list[int]`, *optional*, defaults to `[3, 2]`):
78
+ Stem channels to extract if demucs outputs are passed.
79
+ """
80
+
81
+ model_input_names = ["input_features"]
82
+
83
+ def __init__(
84
+ self,
85
+ feature_size=12,
86
+ sampling_rate=32000,
87
+ hop_length=4096,
88
+ chunk_length=30,
89
+ n_fft=16384,
90
+ num_chroma=12,
91
+ padding_value=0.0,
92
+ return_attention_mask=False, # pad inputs to max length with silence token (zero) and no attention mask
93
+ stem_indices=[3, 2],
94
+ **kwargs,
95
+ ):
96
+ super().__init__(
97
+ feature_size=feature_size,
98
+ sampling_rate=sampling_rate,
99
+ padding_value=padding_value,
100
+ return_attention_mask=return_attention_mask,
101
+ **kwargs,
102
+ )
103
+ self.n_fft = n_fft
104
+ self.hop_length = hop_length
105
+ self.chunk_length = chunk_length
106
+ self.n_samples = chunk_length * sampling_rate
107
+ self.sampling_rate = sampling_rate
108
+ self.chroma_filters = torch.from_numpy(
109
+ chroma_filter_bank(sampling_rate=sampling_rate, num_frequency_bins=n_fft, tuning=0, num_chroma=num_chroma)
110
+ ).float()
111
+ self.spectrogram = torchaudio.transforms.Spectrogram(
112
+ n_fft=n_fft, win_length=n_fft, hop_length=hop_length, power=2, center=True, pad=0, normalized=True
113
+ )
114
+ self.stem_indices = stem_indices
115
+
116
+ def _torch_extract_fbank_features(self, waveform: torch.Tensor) -> torch.Tensor:
117
+ """
118
+ Compute the chroma spectrogram of the provided audio using the torchaudio spectrogram implementation and the librosa chroma features.
119
+ """
120
+
121
+ # if wav length is not long enough, pad it
122
+ wav_length = waveform.shape[-1]
123
+ if wav_length < self.n_fft:
124
+ pad = self.n_fft - wav_length
125
+ rest = 0 if pad % 2 == 0 else 1
126
+ waveform = torch.nn.functional.pad(waveform, (pad // 2, pad // 2 + rest), "constant", 0)
127
+
128
+ # squeeze alongside channel dimension
129
+ spec = self.spectrogram(waveform).squeeze(1)
130
+
131
+ # sum along the frequency dimension
132
+ raw_chroma = torch.einsum("cf, ...ft->...ct", self.chroma_filters, spec)
133
+
134
+ # normalise with max value
135
+ norm_chroma = torch.nn.functional.normalize(raw_chroma, p=float("inf"), dim=-2, eps=1e-6)
136
+
137
+ # transpose time and chroma dimension -> (batch, time, chroma)
138
+ norm_chroma = norm_chroma.transpose(1, 2)
139
+
140
+ # replace max value alongside chroma dimension with 1 and replace the rest with 0
141
+ idx = norm_chroma.argmax(-1, keepdim=True)
142
+ norm_chroma[:] = 0
143
+ norm_chroma.scatter_(dim=-1, index=idx, value=1)
144
+
145
+ return norm_chroma
146
+
147
+ def _extract_stem_indices(self, audio, sampling_rate=None):
148
+ """
149
+ Extracts stems from the output of the [Demucs](https://github.com/adefossez/demucs/tree/main) audio separation model,
150
+ then converts to mono-channel and resample to the feature extractor sampling rate.
151
+
152
+ Args:
153
+ audio (`torch.Tensor` of shape `(batch_size, num_stems, channel_size, audio_length)`):
154
+ The output of the Demucs model to be processed.
155
+ sampling_rate (`int`, *optional*):
156
+ Demucs sampling rate. If not specified, defaults to `44000`.
157
+ """
158
+ sampling_rate = 44000 if sampling_rate is None else sampling_rate
159
+
160
+ # extract "vocals" and "others" sources from audio encoder (demucs) output
161
+ # [batch_size, num_stems, channel_size, audio_length]
162
+ wav = audio[:, torch.tensor(self.stem_indices)]
163
+
164
+ # merge extracted stems to single waveform
165
+ wav = wav.sum(1)
166
+
167
+ # convert to mono-channel waveform
168
+ wav = wav.mean(dim=1, keepdim=True)
169
+
170
+ # resample to model sampling rate
171
+ # not equivalent to julius.resample
172
+ if sampling_rate != self.sampling_rate:
173
+ wav = torchaudio.functional.resample(
174
+ wav, sampling_rate, self.sampling_rate, rolloff=0.945, lowpass_filter_width=24
175
+ )
176
+
177
+ # [batch_size, 1, audio_length] -> [batch_size, audio_length]
178
+ wav = wav.squeeze(1)
179
+
180
+ return wav
181
+
182
+ def __call__(
183
+ self,
184
+ audio: np.ndarray | list[float] | list[np.ndarray] | list[list[float]],
185
+ truncation: bool = True,
186
+ pad_to_multiple_of: int | None = None,
187
+ return_tensors: str | TensorType | None = None,
188
+ return_attention_mask: bool | None = None,
189
+ padding: str | None = True,
190
+ max_length: int | None = None,
191
+ sampling_rate: int | None = None,
192
+ **kwargs,
193
+ ) -> BatchFeature:
194
+ """
195
+ Main method to featurize and prepare for the model one or several sequence(s).
196
+
197
+ Args:
198
+ audio (`torch.Tensor`, `np.ndarray`, `list[float]`, `list[np.ndarray]`, `list[torch.Tensor]`, `list[list[float]]`):
199
+ The sequence or batch of sequences to be padded. Each sequence can be a torch tensor, a numpy array, a list of float
200
+ values, a list of numpy arrays, a list of torch tensors, or a list of list of float values.
201
+ If `audio` is the output of Demucs, it has to be a torch tensor of shape `(batch_size, num_stems, channel_size, audio_length)`.
202
+ Otherwise, it must be mono or stereo channel audio.
203
+ truncation (`bool`, *optional*, default to `True`):
204
+ Activates truncation to cut input sequences longer than *max_length* to *max_length*.
205
+ pad_to_multiple_of (`int`, *optional*, defaults to None):
206
+ If set will pad the sequence to a multiple of the provided value.
207
+
208
+ This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability
209
+ `>= 7.5` (Volta), or on TPUs which benefit from having sequence lengths be a multiple of 128.
210
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
211
+ If set, will return tensors instead of list of python integers. Acceptable values are:
212
+
213
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
214
+ - `'np'`: Return Numpy `np.ndarray` objects.
215
+ return_attention_mask (`bool`, *optional*):
216
+ Whether to return the attention mask. If left to the default, will return the attention mask according
217
+ to the specific feature_extractor's default.
218
+
219
+ [What are attention masks?](../glossary#attention-mask)
220
+
221
+ <Tip>
222
+ For Musicgen Melody models, audio `attention_mask` is not necessary.
223
+ </Tip>
224
+
225
+ padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `True`):
226
+ Select a strategy to pad the returned sequences (according to the model's padding side and padding
227
+ index) among:
228
+
229
+ - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
230
+ sequence if provided).
231
+ - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
232
+ acceptable input length for the model if that argument is not provided.
233
+ - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
234
+ lengths).
235
+ max_length (`int`, *optional*):
236
+ Maximum length of the returned list and optionally padding length (see above).
237
+ sampling_rate (`int`, *optional*):
238
+ The sampling rate at which the `audio` input was sampled. It is strongly recommended to pass
239
+ `sampling_rate` at the forward call to prevent silent errors.
240
+ Note that if `audio` is the output of Demucs, `sampling_rate` must be the sampling rate at which Demucs operates.
241
+ """
242
+
243
+ if sampling_rate is None:
244
+ logger.warning_once(
245
+ f"It is strongly recommended to pass the `sampling_rate` argument to `{self.__class__.__name__}()`. "
246
+ "Failing to do so can result in silent errors that might be hard to debug."
247
+ )
248
+
249
+ if isinstance(audio, torch.Tensor) and len(audio.shape) == 4:
250
+ logger.warning_once(
251
+ "`audio` is a 4-dimensional torch tensor and has thus been recognized as the output of `Demucs`. "
252
+ "If this is not the case, make sure to read Musicgen Melody docstrings and "
253
+ "to correct `audio` to get the right behaviour."
254
+ "Link to the docstrings: https://huggingface.co/docs/transformers/main/en/model_doc/musicgen_melody"
255
+ )
256
+ audio = self._extract_stem_indices(audio, sampling_rate=sampling_rate)
257
+ elif sampling_rate is not None and sampling_rate != self.sampling_rate:
258
+ audio = torchaudio.functional.resample(
259
+ audio, sampling_rate, self.sampling_rate, rolloff=0.945, lowpass_filter_width=24
260
+ )
261
+
262
+ is_batched = isinstance(audio, (np.ndarray, torch.Tensor)) and len(audio.shape) > 1
263
+ is_batched = is_batched or (
264
+ isinstance(audio, (list, tuple)) and (isinstance(audio[0], (torch.Tensor, np.ndarray, tuple, list)))
265
+ )
266
+
267
+ if is_batched and not isinstance(audio[0], torch.Tensor):
268
+ audio = [torch.tensor(speech, dtype=torch.float32).unsqueeze(-1) for speech in audio]
269
+ elif is_batched:
270
+ audio = [speech.unsqueeze(-1) for speech in audio]
271
+ elif not is_batched and not isinstance(audio, torch.Tensor):
272
+ audio = torch.tensor(audio, dtype=torch.float32).unsqueeze(-1)
273
+
274
+ if isinstance(audio[0], torch.Tensor) and audio[0].dtype is torch.float64:
275
+ audio = [speech.to(torch.float32) for speech in audio]
276
+
277
+ # always return batch
278
+ if not is_batched:
279
+ audio = [audio]
280
+
281
+ if len(audio[0].shape) == 3:
282
+ logger.warning_once(
283
+ "`audio` has been detected as a batch of stereo signals. Will be convert to mono signals. "
284
+ "If this is an undesired behaviour, make sure to read Musicgen Melody docstrings and "
285
+ "to correct `audio` to get the right behaviour."
286
+ "Link to the docstrings: https://huggingface.co/docs/transformers/main/en/model_doc/musicgen_melody"
287
+ )
288
+ # convert to mono-channel waveform
289
+ audio = [stereo.mean(dim=0) for stereo in audio]
290
+
291
+ batched_speech = BatchFeature({"input_features": audio})
292
+
293
+ padded_inputs = self.pad(
294
+ batched_speech,
295
+ padding=padding,
296
+ max_length=max_length if max_length else self.n_samples,
297
+ truncation=truncation,
298
+ pad_to_multiple_of=pad_to_multiple_of,
299
+ return_attention_mask=return_attention_mask,
300
+ return_tensors="pt",
301
+ )
302
+
303
+ input_features = self._torch_extract_fbank_features(padded_inputs["input_features"].squeeze(-1))
304
+
305
+ padded_inputs["input_features"] = input_features
306
+
307
+ if return_attention_mask:
308
+ # rescale from raw audio length to spectrogram length
309
+ padded_inputs["attention_mask"] = padded_inputs["attention_mask"][:, :: self.hop_length]
310
+
311
+ if return_tensors is not None:
312
+ padded_inputs = padded_inputs.convert_to_tensors(return_tensors)
313
+
314
+ return padded_inputs
315
+
316
+ def to_dict(self) -> dict[str, Any]:
317
+ """
318
+ Serializes this instance to a Python dictionary. Returns:
319
+ `dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance.
320
+ """
321
+ output = copy.deepcopy(self.__dict__)
322
+ output["feature_extractor_type"] = self.__class__.__name__
323
+ if "mel_filters" in output:
324
+ del output["mel_filters"]
325
+ if "window" in output:
326
+ del output["window"]
327
+ if "chroma_filters" in output:
328
+ del output["chroma_filters"]
329
+ if "spectrogram" in output:
330
+ del output["spectrogram"]
331
+ return output
332
+
333
+
334
+ __all__ = ["MusicgenMelodyFeatureExtractor"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/musicgen_melody/modeling_musicgen_melody.py ADDED
The diff for this file is too large to render. See raw diff
 
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/wav2vec2_phoneme/__init__.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .tokenization_wav2vec2_phoneme import *
22
+ else:
23
+ import sys
24
+
25
+ _file = globals()["__file__"]
26
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/wav2vec2_phoneme/tokenization_wav2vec2_phoneme.py ADDED
@@ -0,0 +1,581 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 The Facebook Inc. and The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Tokenization class for Wav2Vec2Phoneme."""
15
+
16
+ import json
17
+ import os
18
+ from dataclasses import dataclass
19
+ from itertools import groupby
20
+ from typing import TYPE_CHECKING, Any, Union
21
+
22
+ import numpy as np
23
+
24
+ from ...tokenization_python import PreTrainedTokenizer
25
+ from ...tokenization_utils_base import AddedToken
26
+ from ...utils import (
27
+ ModelOutput,
28
+ logging,
29
+ requires_backends,
30
+ to_py_obj,
31
+ )
32
+
33
+
34
+ logger = logging.get_logger(__name__)
35
+
36
+
37
+ if TYPE_CHECKING:
38
+ import torch
39
+
40
+
41
+ VOCAB_FILES_NAMES = {
42
+ "vocab_file": "vocab.json",
43
+ "tokenizer_config_file": "tokenizer_config.json",
44
+ }
45
+
46
+
47
+ # Wav2Vec2Phoneme has no max input length
48
+
49
+
50
+ ListOfDict = list[dict[str, int | str]]
51
+
52
+
53
+ @dataclass
54
+ class Wav2Vec2PhonemeCTCTokenizerOutput(ModelOutput):
55
+ """
56
+ Output type of [` Wav2Vec2PhonemeCTCTokenizer`], with transcription.
57
+
58
+ Args:
59
+ text (list of `str` or `str`):
60
+ Decoded logits in text from. Usually the speech transcription.
61
+ char_offsets (list of `list[dict[str, Union[int, str]]]` or `list[dict[str, Union[int, str]]]`):
62
+ Offsets of the decoded characters. In combination with sampling rate and model downsampling rate char
63
+ offsets can be used to compute time stamps for each character. Total logit score of the beam associated with
64
+ produced text.
65
+ """
66
+
67
+ text: list[str] | str
68
+ char_offsets: list[ListOfDict] | ListOfDict = None
69
+
70
+
71
+ class Wav2Vec2PhonemeCTCTokenizer(PreTrainedTokenizer):
72
+ """
73
+ Constructs a Wav2Vec2PhonemeCTC tokenizer.
74
+
75
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains some of the main methods. Users should refer to
76
+ the superclass for more information regarding such methods.
77
+
78
+ Args:
79
+ vocab_file (`str`):
80
+ File containing the vocabulary.
81
+ bos_token (`str`, *optional*, defaults to `"<s>"`):
82
+ The beginning of sentence token.
83
+ eos_token (`str`, *optional*, defaults to `"</s>"`):
84
+ The end of sentence token.
85
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
86
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
87
+ token instead.
88
+ pad_token (`str`, *optional*, defaults to `"<pad>"`):
89
+ The token used for padding, for example when batching sequences of different lengths.
90
+ do_phonemize (`bool`, *optional*, defaults to `True`):
91
+ Whether the tokenizer should phonetize the input or not. Only if a sequence of phonemes is passed to the
92
+ tokenizer, `do_phonemize` should be set to `False`.
93
+ phonemizer_lang (`str`, *optional*, defaults to `"en-us"`):
94
+ The language of the phoneme set to which the tokenizer should phonetize the input text to.
95
+ phonemizer_backend (`str`, *optional*. defaults to `"espeak"`):
96
+ The backend phonetization library that shall be used by the phonemizer library. Defaults to `espeak-ng`.
97
+ See the [phonemizer package](https://github.com/bootphon/phonemizer#readme). for more information.
98
+
99
+ **kwargs
100
+ Additional keyword arguments passed along to [`PreTrainedTokenizer`]
101
+ """
102
+
103
+ vocab_files_names = VOCAB_FILES_NAMES
104
+ model_input_names = ["input_ids", "attention_mask"]
105
+
106
+ def __init__(
107
+ self,
108
+ vocab_file,
109
+ bos_token="<s>",
110
+ eos_token="</s>",
111
+ unk_token="<unk>",
112
+ pad_token="<pad>",
113
+ phone_delimiter_token=" ",
114
+ word_delimiter_token=None,
115
+ do_phonemize=True,
116
+ phonemizer_lang="en-us",
117
+ phonemizer_backend="espeak",
118
+ **kwargs,
119
+ ):
120
+ # Recover delimiters from V5 `*_token` auto-promotion; they aren't vocab tokens.
121
+ model_specific = kwargs.get("model_specific_special_tokens") or {}
122
+ if "word_delimiter_token" in model_specific:
123
+ word_delimiter_token = model_specific.pop("word_delimiter_token")
124
+ if "phone_delimiter_token" in model_specific:
125
+ phone_delimiter_token = model_specific.pop("phone_delimiter_token")
126
+ if not model_specific:
127
+ kwargs.pop("model_specific_special_tokens", None)
128
+
129
+ self._word_delimiter_token = word_delimiter_token
130
+ self._phone_delimiter_token = phone_delimiter_token
131
+ self.do_phonemize = do_phonemize
132
+ self.phonemizer_lang = phonemizer_lang
133
+ self.phonemizer_backend = phonemizer_backend
134
+
135
+ if do_phonemize:
136
+ self.init_backend(self.phonemizer_lang)
137
+
138
+ with open(vocab_file, encoding="utf-8") as vocab_handle:
139
+ self.encoder = json.load(vocab_handle)
140
+ self.decoder = {v: k for k, v in self.encoder.items()}
141
+
142
+ super().__init__(
143
+ unk_token=unk_token,
144
+ bos_token=bos_token,
145
+ eos_token=eos_token,
146
+ pad_token=pad_token,
147
+ do_phonemize=do_phonemize,
148
+ phonemizer_lang=phonemizer_lang,
149
+ phonemizer_backend=phonemizer_backend,
150
+ **kwargs,
151
+ )
152
+ self.init_kwargs["word_delimiter_token"] = word_delimiter_token
153
+ self.init_kwargs["phone_delimiter_token"] = phone_delimiter_token
154
+
155
+ @property
156
+ def vocab_size(self) -> int:
157
+ return len(self.decoder)
158
+
159
+ def get_vocab(self) -> dict:
160
+ vocab = dict(self.encoder.copy())
161
+ vocab.update(self.added_tokens_encoder)
162
+ return vocab
163
+
164
+ def _add_tokens(self, new_tokens: list[str] | list[AddedToken], special_tokens: bool = False) -> int:
165
+ # Overwritten to never strip!
166
+ to_add = []
167
+ for token in new_tokens:
168
+ if isinstance(token, str):
169
+ to_add.append(AddedToken(token, rstrip=False, lstrip=False, normalized=True, special=special_tokens))
170
+ else:
171
+ to_add.append(token)
172
+
173
+ return super()._add_tokens(to_add, special_tokens)
174
+
175
+ def init_backend(self, phonemizer_lang: str):
176
+ """
177
+ Initializes the backend.
178
+
179
+ Args:
180
+ phonemizer_lang (`str`): The language to be used.
181
+ """
182
+ requires_backends(self, "phonemizer")
183
+ from phonemizer.backend import BACKENDS
184
+
185
+ self._phonemizer_backend = BACKENDS[self.phonemizer_backend](phonemizer_lang, language_switch="remove-flags")
186
+
187
+ def prepare_for_tokenization(
188
+ self,
189
+ text: str,
190
+ is_split_into_words: bool = False,
191
+ phonemizer_lang: str | None = None,
192
+ do_phonemize: bool | None = None,
193
+ **kwargs,
194
+ ) -> tuple[str, dict[str, Any]]:
195
+ """
196
+ Performs any necessary transformations before tokenization.
197
+
198
+ This method should pop the arguments from kwargs and return the remaining `kwargs` as well. We test the
199
+ `kwargs` at the end of the encoding process to be sure all the arguments have been used.
200
+
201
+ Args:
202
+ text (`str`):
203
+ The text to prepare.
204
+ is_split_into_words (`bool`, *optional*, defaults to `False`):
205
+ Whether or not the input is already pre-tokenized (e.g., split into words). If set to `True`, the
206
+ tokenizer assumes the input is already split into words (for instance, by splitting it on whitespace)
207
+ which it will tokenize. This is useful for NER or token classification.
208
+ phonemizer_lang (`str`, *optional*):
209
+ The language of the phoneme set to which the tokenizer should phonetize the input text to.
210
+ do_phonemize (`bool`, *optional*):
211
+ Whether the tokenizer should phonetize the input text or not. Only if a sequence of phonemes is passed
212
+ to the tokenizer, `do_phonemize` should be set to `False`.
213
+
214
+
215
+ Returns:
216
+ `tuple[str, dict[str, Any]]`: The prepared text and the unused kwargs.
217
+ """
218
+ if is_split_into_words:
219
+ text = " " + text
220
+
221
+ # set whether tokenizer should phonemize or not
222
+ if do_phonemize is not None:
223
+ self.do_phonemize = do_phonemize
224
+
225
+ # set the correct phonemizer language
226
+ if phonemizer_lang is not None:
227
+ self.phonemizer_lang = phonemizer_lang
228
+ self.init_backend(phonemizer_lang)
229
+
230
+ return (text, {})
231
+
232
+ def _tokenize(self, text, **kwargs):
233
+ """
234
+ Converts a string into a sequence of tokens (string), using the tokenizer.
235
+ """
236
+
237
+ # make sure whitespace is stripped to prevent <unk>
238
+ text = text.strip()
239
+
240
+ # phonemize
241
+ if self.do_phonemize:
242
+ text = text.lower()
243
+
244
+ # create list of phonemes
245
+ text = self.phonemize(text, self.phonemizer_lang)
246
+
247
+ # make sure ' ' is between phonemes
248
+ tokens = text.split(" ")
249
+
250
+ tokens = list(filter(lambda p: p.strip() != "", tokens))
251
+ return tokens
252
+
253
+ def phonemize(self, text: str, phonemizer_lang: str | None = None) -> str:
254
+ from phonemizer.separator import Separator
255
+
256
+ word_delimiter = self.word_delimiter_token + " " if self.word_delimiter_token is not None else ""
257
+ if phonemizer_lang is not None and phonemizer_lang != self.phonemizer_lang:
258
+ self.init_backend(phonemizer_lang)
259
+ else:
260
+ phonemizer_lang = self.phonemizer_lang
261
+
262
+ separator = Separator(phone=self.phone_delimiter_token, word=word_delimiter, syllable="")
263
+ phonemes = self._phonemizer_backend.phonemize(
264
+ [text],
265
+ separator=separator,
266
+ )
267
+ phonemes = phonemes[0].strip()
268
+
269
+ return phonemes
270
+
271
+ @property
272
+ def word_delimiter_token(self) -> str:
273
+ """
274
+ `str`: Word delimiter token. Log an error if used while not having been set.
275
+ """
276
+ if self._word_delimiter_token is None:
277
+ if self.verbose:
278
+ logger.error("Using word_delimiter_token, but it is not set yet.")
279
+ return None
280
+ return str(self._word_delimiter_token)
281
+
282
+ @property
283
+ def word_delimiter_token_id(self) -> int | None:
284
+ """
285
+ `Optional[int]`: Id of the word_delimiter_token in the vocabulary. Returns `None` if the token has not been
286
+ set.
287
+ """
288
+ if self._word_delimiter_token is None:
289
+ return None
290
+ return self.convert_tokens_to_ids(self.word_delimiter_token)
291
+
292
+ @word_delimiter_token.setter
293
+ def word_delimiter_token(self, value):
294
+ self._word_delimiter_token = value
295
+
296
+ @word_delimiter_token_id.setter
297
+ def word_delimiter_token_id(self, value):
298
+ self._word_delimiter_token = self.convert_tokens_to_ids(value)
299
+
300
+ @property
301
+ def phone_delimiter_token(self) -> str:
302
+ """
303
+ `str`: Word delimiter token. Log an error if used while not having been set.
304
+ """
305
+ if self._phone_delimiter_token is None:
306
+ if self.verbose:
307
+ logger.error("Using phone_delimiter_token, but it is not set yet.")
308
+ return None
309
+ return str(self._phone_delimiter_token)
310
+
311
+ @property
312
+ def phone_delimiter_token_id(self) -> int | None:
313
+ """
314
+ `Optional[int]`: Id of the phone_delimiter_token in the vocabulary. Returns `None` if the token has not been
315
+ set.
316
+ """
317
+ if self._phone_delimiter_token is None:
318
+ return None
319
+ return self.convert_tokens_to_ids(self.phone_delimiter_token)
320
+
321
+ @phone_delimiter_token.setter
322
+ def phone_delimiter_token(self, value):
323
+ self._phone_delimiter_token = value
324
+
325
+ @phone_delimiter_token_id.setter
326
+ def phone_delimiter_token_id(self, value):
327
+ self._phone_delimiter_token = self.convert_tokens_to_ids(value)
328
+
329
+ def _convert_token_to_id(self, token: str) -> int:
330
+ """Converts a token (str) in an index (integer) using the vocab."""
331
+ return self.encoder.get(token, self.encoder.get(self.unk_token))
332
+
333
+ def _convert_id_to_token(self, index: int) -> str:
334
+ """Converts an index (integer) in a token (str) using the vocab."""
335
+ result = self.decoder.get(index, self.unk_token)
336
+ return result
337
+
338
+ def convert_tokens_to_string(
339
+ self,
340
+ tokens: list[str],
341
+ group_tokens: bool = True,
342
+ spaces_between_special_tokens: bool = False,
343
+ filter_word_delimiter_token: bool = True,
344
+ output_char_offsets: bool = False,
345
+ ) -> str:
346
+ """
347
+ Converts a connectionist-temporal-classification (CTC) output tokens into a single string.
348
+ """
349
+ # group same tokens into non-repeating tokens in CTC style decoding
350
+ if group_tokens:
351
+ chars, char_repetitions = zip(*((token, len(list(group_iter))) for token, group_iter in groupby(tokens)))
352
+ else:
353
+ chars = tokens
354
+ char_repetitions = len(tokens) * [1]
355
+
356
+ # filter self.pad_token which is used as CTC-blank token
357
+ processed_chars = list(filter(lambda char: char != self.pad_token, chars))
358
+
359
+ # also filter self.word_delimiter_token if not not
360
+ if filter_word_delimiter_token and self.word_delimiter_token is not None:
361
+ processed_chars = list(filter(lambda token: token != self.word_delimiter_token, processed_chars))
362
+
363
+ # retrieve offsets
364
+ char_offsets = None
365
+ if output_char_offsets:
366
+ word_delimiter_token_for_offsets = (
367
+ self.word_delimiter_token if filter_word_delimiter_token is True else None
368
+ )
369
+ char_offsets = self._compute_offsets(
370
+ char_repetitions, chars, self.pad_token, word_delimiter_token=word_delimiter_token_for_offsets
371
+ )
372
+
373
+ if len(char_offsets) != len(processed_chars):
374
+ raise ValueError(
375
+ f"`char_offsets`: {char_offsets} and `processed_tokens`: {processed_chars}"
376
+ " have to be of the same length, but are: `len(offsets)`: "
377
+ f"{len(char_offsets)} and `len(processed_tokens)`: {len(processed_chars)}"
378
+ )
379
+
380
+ # set tokens to correct processed token
381
+ for i, char in enumerate(processed_chars):
382
+ char_offsets[i]["char"] = char
383
+
384
+ string = " ".join(processed_chars).strip()
385
+
386
+ return {"text": string, "char_offsets": char_offsets}
387
+
388
+ @staticmethod
389
+ def _compute_offsets(
390
+ char_repetitions: list[int], chars: list[str], ctc_token: int, word_delimiter_token: int | None = None
391
+ ) -> list[dict[str, str | int]]:
392
+ end_indices = np.asarray(char_repetitions).cumsum()
393
+ start_indices = np.concatenate(([0], end_indices[:-1]))
394
+
395
+ offsets = [
396
+ {"char": t, "start_offset": s, "end_offset": e} for t, s, e in zip(chars, start_indices, end_indices)
397
+ ]
398
+
399
+ # filter out CTC token
400
+ offsets = list(filter(lambda offsets: offsets["char"] != ctc_token, offsets))
401
+
402
+ # filter out word delimiter token if necessary
403
+ if word_delimiter_token is not None:
404
+ offsets = list(filter(lambda offsets: offsets["char"] != word_delimiter_token, offsets))
405
+
406
+ return offsets
407
+
408
+ def _decode(
409
+ self,
410
+ token_ids: list[int],
411
+ skip_special_tokens: bool = False,
412
+ clean_up_tokenization_spaces: bool | None = None,
413
+ group_tokens: bool = True,
414
+ filter_word_delimiter_token: bool = True,
415
+ spaces_between_special_tokens: bool = False,
416
+ output_char_offsets: bool = False,
417
+ ) -> str:
418
+ """
419
+ special _decode function is needed for Wav2Vec2PhonemeTokenizer because added tokens should be treated exactly
420
+ the same as tokens of the base vocabulary and therefore the function `convert_tokens_to_string` has to be
421
+ called on the whole token list and not individually on added tokens
422
+ """
423
+ filtered_tokens = self.convert_ids_to_tokens(token_ids, skip_special_tokens=skip_special_tokens)
424
+
425
+ result = []
426
+ for token in filtered_tokens:
427
+ if skip_special_tokens and token in self.all_special_ids:
428
+ continue
429
+ result.append(token)
430
+
431
+ string_output = self.convert_tokens_to_string(
432
+ result,
433
+ group_tokens=group_tokens,
434
+ spaces_between_special_tokens=spaces_between_special_tokens,
435
+ filter_word_delimiter_token=filter_word_delimiter_token,
436
+ output_char_offsets=output_char_offsets,
437
+ )
438
+
439
+ text = string_output["text"]
440
+
441
+ clean_up_tokenization_spaces = (
442
+ clean_up_tokenization_spaces
443
+ if clean_up_tokenization_spaces is not None
444
+ else self.clean_up_tokenization_spaces
445
+ )
446
+ if clean_up_tokenization_spaces:
447
+ text = self.clean_up_tokenization(text)
448
+
449
+ if output_char_offsets:
450
+ return Wav2Vec2PhonemeCTCTokenizerOutput(text=text, char_offsets=string_output["char_offsets"])
451
+ else:
452
+ return text
453
+
454
+ # overwritten from `tokenization_utils_base.py` because we need docs for `output_char_offsets` here
455
+ def decode(
456
+ self,
457
+ token_ids: Union[int, list[int], np.ndarray, "torch.Tensor"],
458
+ skip_special_tokens: bool = False,
459
+ clean_up_tokenization_spaces: bool | None = None,
460
+ output_char_offsets: bool = False,
461
+ **kwargs,
462
+ ) -> str:
463
+ """
464
+ Converts a sequence of ids in a string, using the tokenizer and vocabulary with options to remove special
465
+ tokens and clean up tokenization spaces.
466
+
467
+ Similar to doing `self.convert_tokens_to_string(self.convert_ids_to_tokens(token_ids))`.
468
+
469
+ Args:
470
+ token_ids (`Union[int, list[int], np.ndarray, torch.Tensor]`):
471
+ List of tokenized input ids. Can be obtained using the `__call__` method.
472
+ skip_special_tokens (`bool`, *optional*, defaults to `False`):
473
+ Whether or not to remove special tokens in the decoding.
474
+ clean_up_tokenization_spaces (`bool`, *optional*):
475
+ Whether or not to clean up the tokenization spaces.
476
+ output_char_offsets (`bool`, *optional*, defaults to `False`):
477
+ Whether or not to output character offsets. Character offsets can be used in combination with the
478
+ sampling rate and model downsampling rate to compute the time-stamps of transcribed characters.
479
+
480
+ <Tip>
481
+
482
+ Please take a look at the Example of [`~models.wav2vec2.tokenization_wav2vec2.decode`] to better
483
+ understand how to make use of `output_word_offsets`.
484
+ [`~model.wav2vec2_phoneme.tokenization_wav2vec2_phoneme.batch_decode`] works the same way with
485
+ phonemes.
486
+
487
+ </Tip>
488
+
489
+ kwargs (additional keyword arguments, *optional*):
490
+ Will be passed to the underlying model specific decode method.
491
+
492
+ Returns:
493
+ `str` or [`~models.wav2vec2.tokenization_wav2vec2_phoneme.Wav2Vec2PhonemeCTCTokenizerOutput`]: The decoded
494
+ sentence. Will be a [`~models.wav2vec2.tokenization_wav2vec2_phoneme.Wav2Vec2PhonemeCTCTokenizerOutput`]
495
+ when `output_char_offsets == True`.
496
+ """
497
+ # Convert inputs to python lists
498
+ token_ids = to_py_obj(token_ids)
499
+
500
+ return self._decode(
501
+ token_ids=token_ids,
502
+ skip_special_tokens=skip_special_tokens,
503
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
504
+ output_char_offsets=output_char_offsets,
505
+ **kwargs,
506
+ )
507
+
508
+ # overwritten from `tokenization_utils_base.py` because tokenizer can output
509
+ # `ModelOutput` which should not be a list for batched output and because
510
+ # we need docs for `output_char_offsets` here
511
+ def batch_decode(
512
+ self,
513
+ sequences: Union[list[int], list[list[int]], np.ndarray, "torch.Tensor"],
514
+ skip_special_tokens: bool = False,
515
+ clean_up_tokenization_spaces: bool | None = None,
516
+ output_char_offsets: bool = False,
517
+ **kwargs,
518
+ ) -> list[str]:
519
+ """
520
+ Convert a list of lists of token ids into a list of strings by calling decode.
521
+
522
+ Args:
523
+ sequences (`Union[list[int], list[list[int]], np.ndarray, torch.Tensor]`):
524
+ List of tokenized input ids. Can be obtained using the `__call__` method.
525
+ skip_special_tokens (`bool`, *optional*, defaults to `False`):
526
+ Whether or not to remove special tokens in the decoding.
527
+ clean_up_tokenization_spaces (`bool`, *optional*):
528
+ Whether or not to clean up the tokenization spaces.
529
+ output_char_offsets (`bool`, *optional*, defaults to `False`):
530
+ Whether or not to output character offsets. Character offsets can be used in combination with the
531
+ sampling rate and model downsampling rate to compute the time-stamps of transcribed characters.
532
+
533
+ <Tip>
534
+
535
+ Please take a look at the Example of [`~models.wav2vec2.tokenization_wav2vec2.decode`] to better
536
+ understand how to make use of `output_word_offsets`.
537
+ [`~model.wav2vec2_phoneme.tokenization_wav2vec2_phoneme.batch_decode`] works analogous with phonemes
538
+ and batched output.
539
+
540
+ </Tip>
541
+
542
+ kwargs (additional keyword arguments, *optional*):
543
+ Will be passed to the underlying model specific decode method.
544
+
545
+ Returns:
546
+ `list[str]` or [`~models.wav2vec2.tokenization_wav2vec2_phoneme.Wav2Vec2PhonemeCTCTokenizerOutput`]: The
547
+ decoded sentence. Will be a
548
+ [`~models.wav2vec2.tokenization_wav2vec2_phoneme.Wav2Vec2PhonemeCTCTokenizerOutput`] when
549
+ `output_char_offsets == True`.
550
+ """
551
+ batch_decoded = [
552
+ self.decode(
553
+ seq,
554
+ skip_special_tokens=skip_special_tokens,
555
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
556
+ output_char_offsets=output_char_offsets,
557
+ **kwargs,
558
+ )
559
+ for seq in sequences
560
+ ]
561
+ if output_char_offsets:
562
+ # transform list of dicts to dict of lists
563
+ return Wav2Vec2PhonemeCTCTokenizerOutput({k: [d[k] for d in batch_decoded] for k in batch_decoded[0]})
564
+
565
+ return batch_decoded
566
+
567
+ def save_vocabulary(self, save_directory: str, filename_prefix: str | None = None) -> tuple[str]:
568
+ if not os.path.isdir(save_directory):
569
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
570
+ return
571
+ vocab_file = os.path.join(
572
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
573
+ )
574
+
575
+ with open(vocab_file, "w", encoding="utf-8") as f:
576
+ f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
577
+
578
+ return (vocab_file,)
579
+
580
+
581
+ __all__ = ["Wav2Vec2PhonemeCTCTokenizer"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/logs/debug_articlefull_elfopt_shared_wheel.log ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Muon: 54 2D params; Nesterov-AdamW: 76 other params
2
+ {
3
+ "data_mode": "cache",
4
+ "cache_path": "cache/owt_t5_llmclean_qwen36_35b_articlefull_pack1023_10k_appendeos1.pt",
5
+ "data_path": "/e2e-data/evad-tech-vla/wanghan58/data/small_benchmarks/langflow_2604_11748/openwebtext",
6
+ "tokenizer_path": "/e2e-data/evad-tech-vla/wanghan58/models/hf/t5-small/tokenizer.json",
7
+ "text_column": "text",
8
+ "pack_len": 1023,
9
+ "append_eos": 1,
10
+ "num_workers": 0,
11
+ "shuffle_buffer": 8192,
12
+ "reject_txt": "cache/online_rejected.txt",
13
+ "out_dir": "runs/debug_articlefull_elfopt_shared_wheel",
14
+ "subset_size": 10000,
15
+ "resume": "",
16
+ "steps": 1,
17
+ "batch_size": 2,
18
+ "grad_accum": 1,
19
+ "lr": 7.8125e-06,
20
+ "blr": 0.001,
21
+ "min_lr": 0.0,
22
+ "lr_schedule": "constant",
23
+ "warmup_steps": 2500,
24
+ "warmup_epochs": 0.5,
25
+ "optimizer": "muon",
26
+ "weight_decay": 0.0,
27
+ "adam_beta1": 0.9,
28
+ "adam_beta2": 0.95,
29
+ "adam_eps": 1e-08,
30
+ "grad_clip": 1.0,
31
+ "log_every": 1,
32
+ "save_every": 999999,
33
+ "dim": 768,
34
+ "layers": 12,
35
+ "heads": 12,
36
+ "mlp_dim": 3072,
37
+ "time_tokens": 4,
38
+ "c_min": 1.0,
39
+ "c_max": 1024.0,
40
+ "c_schedule": "sqrt",
41
+ "seed": 1234,
42
+ "loader_batches_per_rank": 5000,
43
+ "optimizer_steps_per_epoch": 5000,
44
+ "steps_per_epoch": 5000,
45
+ "effective_batch_size": 2
46
+ }
47
+ [data] mode=cache rows=10000 length=1024 vocab=32100 seen=24862 dropped=2100 bos=1:</s> eos=1:</s>
48
+ [optim] optimizer=muon lr=7.812500e-06 blr=1.000000e-03 effective_batch=2 warmup_steps=2500 lr_schedule=constant wd=0.0 loader_batches_per_rank=5000 optimizer_steps_per_epoch=5000
49
+ step=1 lr=3.125000e-09 loss=10.5609 {'pos0_bos_p': 2.3223959942697547e-05, 'pos0_bos_top1': 0, 'last_eos_p': 2.623751242936123e-05, 'last_eos_top1': 0}
LTA_openwebtext_dualt/mini_owt_logdirichlet/logs/infer_owt_lr3e3_bottleneck16_step552k_decode64_ema_20260615_084145.log ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [2026-06-15T08:41:45+00:00] start bottleneck16 latest step552k infer
2
+ -rw-r--r-- 1 root root 856M Jun 15 08:03 runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr3e3_ema0p9999_elfopt_not5_bottleneck16_unfixed_norm_stateprobadd_selfcond_ce_fast_20260612_030202/step_548000.pt
3
+ -rw-r--r-- 1 root root 856M Jun 15 08:12 runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr3e3_ema0p9999_elfopt_not5_bottleneck16_unfixed_norm_stateprobadd_selfcond_ce_fast_20260612_030202/step_549000.pt
4
+ -rw-r--r-- 1 root root 856M Jun 15 08:20 runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr3e3_ema0p9999_elfopt_not5_bottleneck16_unfixed_norm_stateprobadd_selfcond_ce_fast_20260612_030202/step_550000.pt
5
+ -rw-r--r-- 1 root root 856M Jun 15 08:29 runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr3e3_ema0p9999_elfopt_not5_bottleneck16_unfixed_norm_stateprobadd_selfcond_ce_fast_20260612_030202/step_551000.pt
6
+ -rw-r--r-- 1 root root 856M Jun 15 08:37 runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr3e3_ema0p9999_elfopt_not5_bottleneck16_unfixed_norm_stateprobadd_selfcond_ce_fast_20260612_030202/step_552000.pt
7
+ checkpoint=runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr3e3_ema0p9999_elfopt_not5_bottleneck16_unfixed_norm_stateprobadd_selfcond_ce_fast_20260612_030202/step_552000.pt
8
+ use_ema=1
9
+ step=552000
10
+ decode_steps=64
11
+ n=64 chunk_n=8 gpu=0
12
+ out_base=/e2e-data/evad-tech-vla/wanghan58/workspace/LTA_openwebtext_dualt/docs/lta_samples/metrics_20260615
13
+ [2026-06-15T08:41:45+00:00] infer step=552000 decode=64 -> /e2e-data/evad-tech-vla/wanghan58/workspace/LTA_openwebtext_dualt/docs/lta_samples/metrics_20260615/owt_lr3e3_not5_bottleneck16_latest_step552000_ema_sc1p0_decode64_n64
14
+ [2026-06-15T08:41:45+00:00] run decode=64 chunk=0 n=8 seed=123
15
+ [2026-06-15T08:42:02+00:00] done decode=64 chunk=0
16
+ [2026-06-15T08:42:02+00:00] run decode=64 chunk=1 n=8 seed=124
17
+ [2026-06-15T08:42:19+00:00] done decode=64 chunk=1
18
+ [2026-06-15T08:42:19+00:00] run decode=64 chunk=2 n=8 seed=125
19
+ [2026-06-15T08:42:35+00:00] done decode=64 chunk=2
20
+ [2026-06-15T08:42:35+00:00] run decode=64 chunk=3 n=8 seed=126
21
+ [2026-06-15T08:42:52+00:00] done decode=64 chunk=3
22
+ [2026-06-15T08:42:52+00:00] run decode=64 chunk=4 n=8 seed=127
23
+ [2026-06-15T08:43:09+00:00] done decode=64 chunk=4
24
+ [2026-06-15T08:43:09+00:00] run decode=64 chunk=5 n=8 seed=128
25
+ [2026-06-15T08:43:26+00:00] done decode=64 chunk=5
26
+ [2026-06-15T08:43:26+00:00] run decode=64 chunk=6 n=8 seed=129
27
+ [2026-06-15T08:43:42+00:00] done decode=64 chunk=6
28
+ [2026-06-15T08:43:42+00:00] run decode=64 chunk=7 n=8 seed=130
29
+ [2026-06-15T08:43:59+00:00] done decode=64 chunk=7
30
+ merged 64 samples -> /e2e-data/evad-tech-vla/wanghan58/workspace/LTA_openwebtext_dualt/docs/lta_samples/metrics_20260615/owt_lr3e3_not5_bottleneck16_latest_step552000_ema_sc1p0_decode64_n64/sc1p0/samples64.txt
31
+ loading scorer /e2e-data/evad-tech-vla/wanghan58/models/flowtext_scorers/gpt2-large-standard dtype=fp32 device=cuda
32
+ run kind ppl mean_entropy distinct_1 distinct_2 top_token_mass eos_rows eos_total ppl_tokens t5_tokens path
33
+ sc1p0 raw_full 32.18946562436723 4.794616828572085 0.06929465724556837 0.3957697373518246 0.04843808107103012 61 61 61390 64536 /e2e-data/evad-tech-vla/wanghan58/workspace/LTA_openwebtext_dualt/docs/lta_samples/metrics_20260615/owt_lr3e3_not5_bottleneck16_latest_step552000_ema_sc1p0_decode64_n64/sc1p0
34
+ sc1p0 pre_eos 37.00546922148033 4.809895122812238 0.07104502271788517 0.40573516562078005 0.0496616147173768 0 0 58182 62946 /e2e-data/evad-tech-vla/wanghan58/workspace/LTA_openwebtext_dualt/docs/lta_samples/metrics_20260615/owt_lr3e3_not5_bottleneck16_latest_step552000_ema_sc1p0_decode64_n64/sc1p0
35
+ [2026-06-15T08:44:23+00:00] done
36
+ [2026-06-15T08:44:23+00:00] all done
LTA_openwebtext_dualt/mini_owt_logdirichlet/logs/owt_llmclean_qwen36_35b_articlefull_full_rev8_4gpu_resume_20260531_013159.outer.log ADDED
The diff for this file is too large to render. See raw diff
 
LTA_openwebtext_dualt/mini_owt_logdirichlet/logs/vllm_qwen36_35b_a3b_gpu6_port8014.log ADDED
The diff for this file is too large to render. See raw diff