JinghuiLuAstronaut commited on
Commit
9d2cae1
·
verified ·
1 Parent(s): af3e74f

Add files using upload-large-folder tool

Browse files
Files changed (20) hide show
  1. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35/lib/python3.12/site-packages/pip/_vendor/chardet/codingstatemachinedict.py +19 -0
  2. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35/lib/python3.12/site-packages/pip/_vendor/chardet/resultdict.py +16 -0
  3. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35/lib/python3.12/site-packages/pip/_vendor/chardet/sbcharsetprober.py +162 -0
  4. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/bert_japanese/__init__.py +26 -0
  5. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/bert_japanese/tokenization_bert_japanese.py +901 -0
  6. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/cpm/__init__.py +26 -0
  7. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/cpm/tokenization_cpm.py +336 -0
  8. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/cpm/tokenization_cpm_fast.py +232 -0
  9. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/glmasr/modeling_glmasr.py +531 -0
  10. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/glmasr/modular_glmasr.py +445 -0
  11. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/hrm_text/__init__.py +27 -0
  12. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/hrm_text/modeling_hrm_text.py +644 -0
  13. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/led/__init__.py +28 -0
  14. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/led/configuration_led.py +86 -0
  15. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/led/modeling_led.py +0 -0
  16. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/mistral/modular_mistral.py +188 -0
  17. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/vit_msn/__init__.py +27 -0
  18. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/vit_msn/configuration_vit_msn.py +58 -0
  19. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/vit_msn/modeling_vit_msn.py +457 -0
  20. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/vit_msn/modular_vit_msn.py +217 -0
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35/lib/python3.12/site-packages/pip/_vendor/chardet/codingstatemachinedict.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import TYPE_CHECKING, Tuple
2
+
3
+ if TYPE_CHECKING:
4
+ # TypedDict was introduced in Python 3.8.
5
+ #
6
+ # TODO: Remove the else block and TYPE_CHECKING check when dropping support
7
+ # for Python 3.7.
8
+ from typing import TypedDict
9
+
10
+ class CodingStateMachineDict(TypedDict, total=False):
11
+ class_table: Tuple[int, ...]
12
+ class_factor: int
13
+ state_table: Tuple[int, ...]
14
+ char_len_table: Tuple[int, ...]
15
+ name: str
16
+ language: str # Optional key
17
+
18
+ else:
19
+ CodingStateMachineDict = dict
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35/lib/python3.12/site-packages/pip/_vendor/chardet/resultdict.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import TYPE_CHECKING, Optional
2
+
3
+ if TYPE_CHECKING:
4
+ # TypedDict was introduced in Python 3.8.
5
+ #
6
+ # TODO: Remove the else block and TYPE_CHECKING check when dropping support
7
+ # for Python 3.7.
8
+ from typing import TypedDict
9
+
10
+ class ResultDict(TypedDict):
11
+ encoding: Optional[str]
12
+ confidence: float
13
+ language: Optional[str]
14
+
15
+ else:
16
+ ResultDict = dict
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35/lib/python3.12/site-packages/pip/_vendor/chardet/sbcharsetprober.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ######################## BEGIN LICENSE BLOCK ########################
2
+ # The Original Code is Mozilla Universal charset detector code.
3
+ #
4
+ # The Initial Developer of the Original Code is
5
+ # Netscape Communications Corporation.
6
+ # Portions created by the Initial Developer are Copyright (C) 2001
7
+ # the Initial Developer. All Rights Reserved.
8
+ #
9
+ # Contributor(s):
10
+ # Mark Pilgrim - port to Python
11
+ # Shy Shalom - original C code
12
+ #
13
+ # This library is free software; you can redistribute it and/or
14
+ # modify it under the terms of the GNU Lesser General Public
15
+ # License as published by the Free Software Foundation; either
16
+ # version 2.1 of the License, or (at your option) any later version.
17
+ #
18
+ # This library is distributed in the hope that it will be useful,
19
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
20
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21
+ # Lesser General Public License for more details.
22
+ #
23
+ # You should have received a copy of the GNU Lesser General Public
24
+ # License along with this library; if not, write to the Free Software
25
+ # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
26
+ # 02110-1301 USA
27
+ ######################### END LICENSE BLOCK #########################
28
+
29
+ from typing import Dict, List, NamedTuple, Optional, Union
30
+
31
+ from .charsetprober import CharSetProber
32
+ from .enums import CharacterCategory, ProbingState, SequenceLikelihood
33
+
34
+
35
+ class SingleByteCharSetModel(NamedTuple):
36
+ charset_name: str
37
+ language: str
38
+ char_to_order_map: Dict[int, int]
39
+ language_model: Dict[int, Dict[int, int]]
40
+ typical_positive_ratio: float
41
+ keep_ascii_letters: bool
42
+ alphabet: str
43
+
44
+
45
+ class SingleByteCharSetProber(CharSetProber):
46
+ SAMPLE_SIZE = 64
47
+ SB_ENOUGH_REL_THRESHOLD = 1024 # 0.25 * SAMPLE_SIZE^2
48
+ POSITIVE_SHORTCUT_THRESHOLD = 0.95
49
+ NEGATIVE_SHORTCUT_THRESHOLD = 0.05
50
+
51
+ def __init__(
52
+ self,
53
+ model: SingleByteCharSetModel,
54
+ is_reversed: bool = False,
55
+ name_prober: Optional[CharSetProber] = None,
56
+ ) -> None:
57
+ super().__init__()
58
+ self._model = model
59
+ # TRUE if we need to reverse every pair in the model lookup
60
+ self._reversed = is_reversed
61
+ # Optional auxiliary prober for name decision
62
+ self._name_prober = name_prober
63
+ self._last_order = 255
64
+ self._seq_counters: List[int] = []
65
+ self._total_seqs = 0
66
+ self._total_char = 0
67
+ self._control_char = 0
68
+ self._freq_char = 0
69
+ self.reset()
70
+
71
+ def reset(self) -> None:
72
+ super().reset()
73
+ # char order of last character
74
+ self._last_order = 255
75
+ self._seq_counters = [0] * SequenceLikelihood.get_num_categories()
76
+ self._total_seqs = 0
77
+ self._total_char = 0
78
+ self._control_char = 0
79
+ # characters that fall in our sampling range
80
+ self._freq_char = 0
81
+
82
+ @property
83
+ def charset_name(self) -> Optional[str]:
84
+ if self._name_prober:
85
+ return self._name_prober.charset_name
86
+ return self._model.charset_name
87
+
88
+ @property
89
+ def language(self) -> Optional[str]:
90
+ if self._name_prober:
91
+ return self._name_prober.language
92
+ return self._model.language
93
+
94
+ def feed(self, byte_str: Union[bytes, bytearray]) -> ProbingState:
95
+ # TODO: Make filter_international_words keep things in self.alphabet
96
+ if not self._model.keep_ascii_letters:
97
+ byte_str = self.filter_international_words(byte_str)
98
+ else:
99
+ byte_str = self.remove_xml_tags(byte_str)
100
+ if not byte_str:
101
+ return self.state
102
+ char_to_order_map = self._model.char_to_order_map
103
+ language_model = self._model.language_model
104
+ for char in byte_str:
105
+ order = char_to_order_map.get(char, CharacterCategory.UNDEFINED)
106
+ # XXX: This was SYMBOL_CAT_ORDER before, with a value of 250, but
107
+ # CharacterCategory.SYMBOL is actually 253, so we use CONTROL
108
+ # to make it closer to the original intent. The only difference
109
+ # is whether or not we count digits and control characters for
110
+ # _total_char purposes.
111
+ if order < CharacterCategory.CONTROL:
112
+ self._total_char += 1
113
+ if order < self.SAMPLE_SIZE:
114
+ self._freq_char += 1
115
+ if self._last_order < self.SAMPLE_SIZE:
116
+ self._total_seqs += 1
117
+ if not self._reversed:
118
+ lm_cat = language_model[self._last_order][order]
119
+ else:
120
+ lm_cat = language_model[order][self._last_order]
121
+ self._seq_counters[lm_cat] += 1
122
+ self._last_order = order
123
+
124
+ charset_name = self._model.charset_name
125
+ if self.state == ProbingState.DETECTING:
126
+ if self._total_seqs > self.SB_ENOUGH_REL_THRESHOLD:
127
+ confidence = self.get_confidence()
128
+ if confidence > self.POSITIVE_SHORTCUT_THRESHOLD:
129
+ self.logger.debug(
130
+ "%s confidence = %s, we have a winner", charset_name, confidence
131
+ )
132
+ self._state = ProbingState.FOUND_IT
133
+ elif confidence < self.NEGATIVE_SHORTCUT_THRESHOLD:
134
+ self.logger.debug(
135
+ "%s confidence = %s, below negative shortcut threshold %s",
136
+ charset_name,
137
+ confidence,
138
+ self.NEGATIVE_SHORTCUT_THRESHOLD,
139
+ )
140
+ self._state = ProbingState.NOT_ME
141
+
142
+ return self.state
143
+
144
+ def get_confidence(self) -> float:
145
+ r = 0.01
146
+ if self._total_seqs > 0:
147
+ r = (
148
+ (
149
+ self._seq_counters[SequenceLikelihood.POSITIVE]
150
+ + 0.25 * self._seq_counters[SequenceLikelihood.LIKELY]
151
+ )
152
+ / self._total_seqs
153
+ / self._model.typical_positive_ratio
154
+ )
155
+ # The more control characters (proportionnaly to the size
156
+ # of the text), the less confident we become in the current
157
+ # charset.
158
+ r = r * (self._total_char - self._control_char) / self._total_char
159
+ r = r * self._freq_char / self._total_char
160
+ if r >= 1.0:
161
+ r = 0.99
162
+ return r
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/bert_japanese/__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_bert_japanese 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/bert_japanese/tokenization_bert_japanese.py ADDED
@@ -0,0 +1,901 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Tokenization classes."""
15
+
16
+ import collections
17
+ import copy
18
+ import os
19
+ import unicodedata
20
+ from typing import Any
21
+
22
+ from ...tokenization_python import PreTrainedTokenizer, _is_control, _is_punctuation, _is_whitespace
23
+ from ...utils import is_sentencepiece_available, is_sudachi_projection_available, logging
24
+
25
+
26
+ if is_sentencepiece_available():
27
+ import sentencepiece as spm
28
+ else:
29
+ spm = None
30
+
31
+ logger = logging.get_logger(__name__)
32
+
33
+ VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt", "spm_file": "spiece.model"}
34
+
35
+ SPIECE_UNDERLINE = "▁"
36
+
37
+
38
+ def load_vocab(vocab_file):
39
+ """Loads a vocabulary file into a dictionary."""
40
+ vocab = collections.OrderedDict()
41
+ with open(vocab_file, "r", encoding="utf-8") as reader:
42
+ tokens = reader.readlines()
43
+ for index, token in enumerate(tokens):
44
+ token = token.rstrip("\n")
45
+ vocab[token] = index
46
+ return vocab
47
+
48
+
49
+ def whitespace_tokenize(text):
50
+ """Runs basic whitespace cleaning and splitting on a piece of text."""
51
+ text = text.strip()
52
+ if not text:
53
+ return []
54
+ tokens = text.split()
55
+ return tokens
56
+
57
+
58
+ class BertJapaneseTokenizer(PreTrainedTokenizer):
59
+ r"""
60
+ Construct a BERT tokenizer for Japanese text.
61
+
62
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer
63
+ to: this superclass for more information regarding those methods.
64
+
65
+ Args:
66
+ vocab_file (`str`):
67
+ Path to a one-wordpiece-per-line vocabulary file.
68
+ spm_file (`str`, *optional*):
69
+ Path to [SentencePiece](https://github.com/google/sentencepiece) file (generally has a .spm or .model
70
+ extension) that contains the vocabulary.
71
+ do_lower_case (`bool`, *optional*, defaults to `True`):
72
+ Whether to lower case the input. Only has an effect when do_basic_tokenize=True.
73
+ do_word_tokenize (`bool`, *optional*, defaults to `True`):
74
+ Whether to do word tokenization.
75
+ do_subword_tokenize (`bool`, *optional*, defaults to `True`):
76
+ Whether to do subword tokenization.
77
+ word_tokenizer_type (`str`, *optional*, defaults to `"basic"`):
78
+ Type of word tokenizer. Choose from ["basic", "mecab", "sudachi", "jumanpp"].
79
+ subword_tokenizer_type (`str`, *optional*, defaults to `"wordpiece"`):
80
+ Type of subword tokenizer. Choose from ["wordpiece", "character", "sentencepiece",].
81
+ mecab_kwargs (`dict`, *optional*):
82
+ Dictionary passed to the `MecabTokenizer` constructor.
83
+ sudachi_kwargs (`dict`, *optional*):
84
+ Dictionary passed to the `SudachiTokenizer` constructor.
85
+ jumanpp_kwargs (`dict`, *optional*):
86
+ Dictionary passed to the `JumanppTokenizer` constructor.
87
+ """
88
+
89
+ vocab_files_names = VOCAB_FILES_NAMES
90
+
91
+ def __init__(
92
+ self,
93
+ vocab_file,
94
+ spm_file=None,
95
+ do_lower_case=False,
96
+ do_word_tokenize=True,
97
+ do_subword_tokenize=True,
98
+ word_tokenizer_type="basic",
99
+ subword_tokenizer_type="wordpiece",
100
+ never_split=None,
101
+ unk_token="[UNK]",
102
+ sep_token="[SEP]",
103
+ pad_token="[PAD]",
104
+ cls_token="[CLS]",
105
+ mask_token="[MASK]",
106
+ mecab_kwargs=None,
107
+ sudachi_kwargs=None,
108
+ jumanpp_kwargs=None,
109
+ **kwargs,
110
+ ):
111
+ if subword_tokenizer_type == "sentencepiece":
112
+ if not os.path.isfile(spm_file):
113
+ raise ValueError(
114
+ f"Can't find a vocabulary file at path '{spm_file}'. To load the vocabulary from a Google"
115
+ " pretrained model use `tokenizer = AutoTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`"
116
+ )
117
+ self.spm_file = spm_file
118
+ else:
119
+ if not os.path.isfile(vocab_file):
120
+ raise ValueError(
121
+ f"Can't find a vocabulary file at path '{vocab_file}'. To load the vocabulary from a Google"
122
+ " pretrained model use `tokenizer = AutoTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`"
123
+ )
124
+ self.vocab = load_vocab(vocab_file)
125
+ self.ids_to_tokens = collections.OrderedDict([(ids, tok) for tok, ids in self.vocab.items()])
126
+
127
+ self.do_word_tokenize = do_word_tokenize
128
+ self.word_tokenizer_type = word_tokenizer_type
129
+ self.lower_case = do_lower_case
130
+ self.never_split = never_split
131
+ self.mecab_kwargs = copy.deepcopy(mecab_kwargs)
132
+ self.sudachi_kwargs = copy.deepcopy(sudachi_kwargs)
133
+ self.jumanpp_kwargs = copy.deepcopy(jumanpp_kwargs)
134
+ if do_word_tokenize:
135
+ if word_tokenizer_type == "basic":
136
+ self.word_tokenizer = BasicTokenizer(
137
+ do_lower_case=do_lower_case, never_split=never_split, tokenize_chinese_chars=False
138
+ )
139
+ elif word_tokenizer_type == "mecab":
140
+ self.word_tokenizer = MecabTokenizer(
141
+ do_lower_case=do_lower_case, never_split=never_split, **(mecab_kwargs or {})
142
+ )
143
+ elif word_tokenizer_type == "sudachi":
144
+ self.word_tokenizer = SudachiTokenizer(
145
+ do_lower_case=do_lower_case, never_split=never_split, **(sudachi_kwargs or {})
146
+ )
147
+ elif word_tokenizer_type == "jumanpp":
148
+ self.word_tokenizer = JumanppTokenizer(
149
+ do_lower_case=do_lower_case, never_split=never_split, **(jumanpp_kwargs or {})
150
+ )
151
+ else:
152
+ raise ValueError(f"Invalid word_tokenizer_type '{word_tokenizer_type}' is specified.")
153
+
154
+ self.do_subword_tokenize = do_subword_tokenize
155
+ self.subword_tokenizer_type = subword_tokenizer_type
156
+ if do_subword_tokenize:
157
+ if subword_tokenizer_type == "wordpiece":
158
+ self.subword_tokenizer = WordpieceTokenizer(vocab=self.vocab, unk_token=str(unk_token))
159
+ elif subword_tokenizer_type == "character":
160
+ self.subword_tokenizer = CharacterTokenizer(vocab=self.vocab, unk_token=str(unk_token))
161
+ elif subword_tokenizer_type == "sentencepiece":
162
+ self.subword_tokenizer = SentencepieceTokenizer(vocab=self.spm_file, unk_token=str(unk_token))
163
+ else:
164
+ raise ValueError(f"Invalid subword_tokenizer_type '{subword_tokenizer_type}' is specified.")
165
+ super().__init__(
166
+ spm_file=spm_file,
167
+ unk_token=unk_token,
168
+ sep_token=sep_token,
169
+ pad_token=pad_token,
170
+ cls_token=cls_token,
171
+ mask_token=mask_token,
172
+ do_lower_case=do_lower_case,
173
+ do_word_tokenize=do_word_tokenize,
174
+ do_subword_tokenize=do_subword_tokenize,
175
+ word_tokenizer_type=word_tokenizer_type,
176
+ subword_tokenizer_type=subword_tokenizer_type,
177
+ never_split=never_split,
178
+ mecab_kwargs=mecab_kwargs,
179
+ sudachi_kwargs=sudachi_kwargs,
180
+ jumanpp_kwargs=jumanpp_kwargs,
181
+ token_type_ids_pattern="bert_style",
182
+ token_type_ids_include_special_tokens=True,
183
+ special_tokens_pattern="cls_sep",
184
+ **kwargs,
185
+ )
186
+
187
+ @property
188
+ def do_lower_case(self):
189
+ return self.lower_case
190
+
191
+ def __getstate__(self):
192
+ state = dict(self.__dict__)
193
+ if self.word_tokenizer_type in ["mecab", "sudachi", "jumanpp"]:
194
+ del state["word_tokenizer"]
195
+ return state
196
+
197
+ def __setstate__(self, state):
198
+ self.__dict__ = state
199
+ if self.word_tokenizer_type == "mecab":
200
+ self.word_tokenizer = MecabTokenizer(
201
+ do_lower_case=self.do_lower_case, never_split=self.never_split, **(self.mecab_kwargs or {})
202
+ )
203
+ elif self.word_tokenizer_type == "sudachi":
204
+ self.word_tokenizer = SudachiTokenizer(
205
+ do_lower_case=self.do_lower_case, never_split=self.never_split, **(self.sudachi_kwargs or {})
206
+ )
207
+ elif self.word_tokenizer_type == "jumanpp":
208
+ self.word_tokenizer = JumanppTokenizer(
209
+ do_lower_case=self.do_lower_case, never_split=self.never_split, **(self.jumanpp_kwargs or {})
210
+ )
211
+
212
+ def _tokenize(self, text):
213
+ if self.do_word_tokenize:
214
+ tokens = self.word_tokenizer.tokenize(text, never_split=self.all_special_tokens)
215
+ else:
216
+ tokens = [text]
217
+
218
+ if self.do_subword_tokenize:
219
+ split_tokens = [sub_token for token in tokens for sub_token in self.subword_tokenizer.tokenize(token)]
220
+ else:
221
+ split_tokens = tokens
222
+
223
+ return split_tokens
224
+
225
+ @property
226
+ def vocab_size(self):
227
+ if self.subword_tokenizer_type == "sentencepiece":
228
+ return len(self.subword_tokenizer.sp_model)
229
+ return len(self.vocab)
230
+
231
+ def get_vocab(self):
232
+ if self.subword_tokenizer_type == "sentencepiece":
233
+ vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
234
+ vocab.update(self.added_tokens_encoder)
235
+ return vocab
236
+ # base vocab
237
+ vocab = dict(self.vocab)
238
+ # + added_tokens_encoder (only for tokens not in base vocab)
239
+ for token, index in self.added_tokens_encoder.items():
240
+ if token not in self.vocab:
241
+ vocab[token] = index
242
+ return vocab
243
+
244
+ def _convert_token_to_id(self, token):
245
+ """Converts a token (str) in an id using the vocab."""
246
+ if self.subword_tokenizer_type == "sentencepiece":
247
+ return self.subword_tokenizer.sp_model.PieceToId(token)
248
+ return self.vocab.get(token, self.vocab.get(self.unk_token))
249
+
250
+ def _convert_id_to_token(self, index):
251
+ """Converts an index (integer) in a token (str) using the vocab."""
252
+ if self.subword_tokenizer_type == "sentencepiece":
253
+ return self.subword_tokenizer.sp_model.IdToPiece(index)
254
+ return self.ids_to_tokens.get(index, self.unk_token)
255
+
256
+ def convert_tokens_to_string(self, tokens):
257
+ """Converts a sequence of tokens (string) in a single string."""
258
+ if self.subword_tokenizer_type == "sentencepiece":
259
+ return self.subword_tokenizer.sp_model.decode(tokens)
260
+ out_string = " ".join(tokens).replace(" ##", "").strip()
261
+ return out_string
262
+
263
+ def save_vocabulary(self, save_directory: str, filename_prefix: str | None = None) -> tuple[str]:
264
+ if os.path.isdir(save_directory):
265
+ if self.subword_tokenizer_type == "sentencepiece":
266
+ vocab_file = os.path.join(
267
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["spm_file"]
268
+ )
269
+ else:
270
+ vocab_file = os.path.join(
271
+ save_directory,
272
+ (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"],
273
+ )
274
+ else:
275
+ vocab_file = (filename_prefix + "-" if filename_prefix else "") + save_directory
276
+
277
+ if self.subword_tokenizer_type == "sentencepiece":
278
+ with open(vocab_file, "wb") as writer:
279
+ content_spiece_model = self.subword_tokenizer.sp_model.serialized_model_proto()
280
+ writer.write(content_spiece_model)
281
+ else:
282
+ with open(vocab_file, "w", encoding="utf-8") as writer:
283
+ index = 0
284
+ for token, token_index in sorted(self.vocab.items(), key=lambda kv: kv[1]):
285
+ if index != token_index:
286
+ logger.warning(
287
+ f"Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive."
288
+ " Please check that the vocabulary is not corrupted!"
289
+ )
290
+ index = token_index
291
+ writer.write(token + "\n")
292
+ index += 1
293
+ return (vocab_file,)
294
+
295
+
296
+ class MecabTokenizer:
297
+ """Runs basic tokenization with MeCab morphological parser."""
298
+
299
+ def __init__(
300
+ self,
301
+ do_lower_case=False,
302
+ never_split=None,
303
+ normalize_text=True,
304
+ mecab_dic: str | None = "unidic_lite",
305
+ mecab_option: str | None = None,
306
+ ):
307
+ """
308
+ Constructs a MecabTokenizer.
309
+
310
+ Args:
311
+ **do_lower_case**: (*optional*) boolean (default True)
312
+ Whether to lowercase the input.
313
+ **never_split**: (*optional*) list of str
314
+ Kept for backward compatibility purposes. Now implemented directly at the base class level (see
315
+ [`PreTrainedTokenizer.tokenize`]) List of tokens not to split.
316
+ **normalize_text**: (*optional*) boolean (default True)
317
+ Whether to apply unicode normalization to text before tokenization.
318
+ **mecab_dic**: (*optional*) string (default "ipadic")
319
+ Name of dictionary to be used for MeCab initialization. If you are using a system-installed dictionary,
320
+ set this option to `None` and modify *mecab_option*.
321
+ **mecab_option**: (*optional*) string
322
+ String passed to MeCab constructor.
323
+ """
324
+ self.do_lower_case = do_lower_case
325
+ self.never_split = never_split if never_split is not None else []
326
+ self.normalize_text = normalize_text
327
+
328
+ try:
329
+ import fugashi
330
+ except ModuleNotFoundError as error:
331
+ raise error.__class__(
332
+ "You need to install fugashi to use MecabTokenizer. "
333
+ "See https://pypi.org/project/fugashi/ for installation."
334
+ )
335
+
336
+ mecab_option = mecab_option or ""
337
+
338
+ if mecab_dic is not None:
339
+ if mecab_dic == "ipadic":
340
+ try:
341
+ import ipadic
342
+ except ModuleNotFoundError as error:
343
+ raise error.__class__(
344
+ "The ipadic dictionary is not installed. "
345
+ "See https://github.com/polm/ipadic-py for installation."
346
+ )
347
+
348
+ dic_dir = ipadic.DICDIR
349
+
350
+ elif mecab_dic == "unidic_lite":
351
+ try:
352
+ import unidic_lite
353
+ except ModuleNotFoundError as error:
354
+ raise error.__class__(
355
+ "The unidic_lite dictionary is not installed. "
356
+ "See https://github.com/polm/unidic-lite for installation."
357
+ )
358
+
359
+ dic_dir = unidic_lite.DICDIR
360
+
361
+ elif mecab_dic == "unidic":
362
+ try:
363
+ import unidic
364
+ except ModuleNotFoundError as error:
365
+ raise error.__class__(
366
+ "The unidic dictionary is not installed. "
367
+ "See https://github.com/polm/unidic-py for installation."
368
+ )
369
+
370
+ dic_dir = unidic.DICDIR
371
+ if not os.path.isdir(dic_dir):
372
+ raise RuntimeError(
373
+ "The unidic dictionary itself is not found. "
374
+ "See https://github.com/polm/unidic-py for installation."
375
+ )
376
+
377
+ else:
378
+ raise ValueError("Invalid mecab_dic is specified.")
379
+
380
+ mecabrc = os.path.join(dic_dir, "mecabrc")
381
+ mecab_option = f'-d "{dic_dir}" -r "{mecabrc}" ' + mecab_option
382
+
383
+ self.mecab = fugashi.GenericTagger(mecab_option)
384
+
385
+ def tokenize(self, text, never_split=None, **kwargs):
386
+ """Tokenizes a piece of text."""
387
+ if self.normalize_text:
388
+ text = unicodedata.normalize("NFKC", text)
389
+
390
+ never_split = self.never_split + (never_split if never_split is not None else [])
391
+ tokens = []
392
+
393
+ for word in self.mecab(text):
394
+ token = word.surface
395
+
396
+ if self.do_lower_case and token not in never_split:
397
+ token = token.lower()
398
+
399
+ tokens.append(token)
400
+
401
+ return tokens
402
+
403
+
404
+ class SudachiTokenizer:
405
+ """Runs basic tokenization with Sudachi morphological parser."""
406
+
407
+ def __init__(
408
+ self,
409
+ do_lower_case=False,
410
+ never_split=None,
411
+ normalize_text=True,
412
+ trim_whitespace=False,
413
+ sudachi_split_mode="A",
414
+ sudachi_config_path=None,
415
+ sudachi_resource_dir=None,
416
+ sudachi_dict_type="core",
417
+ sudachi_projection=None,
418
+ ):
419
+ """
420
+ Constructs a SudachiTokenizer.
421
+
422
+ Args:
423
+ **do_lower_case**: (*optional*) boolean (default True)
424
+ Whether to lowercase the input.
425
+ **never_split**: (*optional*) list of str
426
+ Kept for backward compatibility purposes. Now implemented directly at the base class level (see
427
+ [`PreTrainedTokenizer.tokenize`]) List of tokens not to split.
428
+ **normalize_text**: (*optional*) boolean (default True)
429
+ Whether to apply unicode normalization to text before tokenization.
430
+ **trim_whitespace**: (*optional*) boolean (default False)
431
+ Whether to trim all whitespace, tab, newline from tokens.
432
+ **sudachi_split_mode**: (*optional*) string
433
+ Split mode of sudachi, choose from `["A", "B", "C"]`.
434
+ **sudachi_config_path**: (*optional*) string
435
+ **sudachi_resource_dir**: (*optional*) string
436
+ **sudachi_dict_type**: (*optional*) string
437
+ dict type of sudachi, choose from `["small", "core", "full"]`.
438
+ **sudachi_projection**: (*optional*) string
439
+ Word projection mode of sudachi, choose from `["surface", "normalized", "reading", "dictionary", "dictionary_and_surface", "normalized_and_surface", "normalized_nouns"]`.
440
+ """
441
+
442
+ self.do_lower_case = do_lower_case
443
+ self.never_split = never_split if never_split is not None else []
444
+ self.normalize_text = normalize_text
445
+ self.trim_whitespace = trim_whitespace
446
+
447
+ try:
448
+ from sudachipy import dictionary, tokenizer
449
+ except ImportError:
450
+ raise ImportError(
451
+ "You need to install sudachipy to use SudachiTokenizer. "
452
+ "See https://github.com/WorksApplications/SudachiPy for installation."
453
+ )
454
+
455
+ if sudachi_split_mode == "A":
456
+ self.split_mode = tokenizer.Tokenizer.SplitMode.A
457
+ elif sudachi_split_mode == "B":
458
+ self.split_mode = tokenizer.Tokenizer.SplitMode.B
459
+ elif sudachi_split_mode == "C":
460
+ self.split_mode = tokenizer.Tokenizer.SplitMode.C
461
+ else:
462
+ raise ValueError("Invalid sudachi_split_mode is specified.")
463
+
464
+ self.projection = sudachi_projection
465
+
466
+ sudachi_dictionary = dictionary.Dictionary(
467
+ config_path=sudachi_config_path, resource_dir=sudachi_resource_dir, dict=sudachi_dict_type
468
+ )
469
+ if is_sudachi_projection_available():
470
+ self.sudachi = sudachi_dictionary.create(self.split_mode, projection=self.projection)
471
+ elif self.projection is not None:
472
+ raise ImportError("You need to install sudachipy>=0.6.8 to specify `projection` field in sudachi_kwargs.")
473
+ else:
474
+ self.sudachi = sudachi_dictionary.create(self.split_mode)
475
+
476
+ def tokenize(self, text, never_split=None, **kwargs):
477
+ """Tokenizes a piece of text."""
478
+ if self.normalize_text:
479
+ text = unicodedata.normalize("NFKC", text)
480
+
481
+ never_split = self.never_split + (never_split if never_split is not None else [])
482
+ tokens = []
483
+
484
+ for word in self.sudachi.tokenize(text):
485
+ token = word.surface()
486
+
487
+ if self.do_lower_case and token not in never_split:
488
+ token = token.lower()
489
+
490
+ if self.trim_whitespace:
491
+ if token.strip() == "":
492
+ continue
493
+ else:
494
+ token = token.strip()
495
+
496
+ tokens.append(token)
497
+
498
+ return tokens
499
+
500
+
501
+ class JumanppTokenizer:
502
+ """Runs basic tokenization with jumanpp morphological parser."""
503
+
504
+ def __init__(
505
+ self,
506
+ do_lower_case=False,
507
+ never_split=None,
508
+ normalize_text=True,
509
+ trim_whitespace=False,
510
+ ):
511
+ """
512
+ Constructs a JumanppTokenizer.
513
+
514
+ Args:
515
+ **do_lower_case**: (*optional*) boolean (default True)
516
+ Whether to lowercase the input.
517
+ **never_split**: (*optional*) list of str
518
+ Kept for backward compatibility purposes. Now implemented directly at the base class level (see
519
+ [`PreTrainedTokenizer.tokenize`]) List of tokens not to split.
520
+ **normalize_text**: (*optional*) boolean (default True)
521
+ Whether to apply unicode normalization to text before tokenization.
522
+ **trim_whitespace**: (*optional*) boolean (default False)
523
+ Whether to trim all whitespace, tab, newline from tokens.
524
+ """
525
+
526
+ self.do_lower_case = do_lower_case
527
+ self.never_split = never_split if never_split is not None else []
528
+ self.normalize_text = normalize_text
529
+ self.trim_whitespace = trim_whitespace
530
+
531
+ try:
532
+ import rhoknp
533
+ except ImportError:
534
+ raise ImportError(
535
+ "You need to install rhoknp to use JumanppTokenizer. "
536
+ "See https://github.com/ku-nlp/rhoknp for installation."
537
+ )
538
+
539
+ self.juman = rhoknp.Jumanpp()
540
+
541
+ def tokenize(self, text, never_split=None, **kwargs):
542
+ """Tokenizes a piece of text."""
543
+ if self.normalize_text:
544
+ text = unicodedata.normalize("NFKC", text)
545
+
546
+ text = text.strip()
547
+
548
+ never_split = self.never_split + (never_split if never_split is not None else [])
549
+ tokens = []
550
+
551
+ for mrph in self.juman.apply_to_sentence(text).morphemes:
552
+ token = mrph.text
553
+
554
+ if self.do_lower_case and token not in never_split:
555
+ token = token.lower()
556
+
557
+ if self.trim_whitespace:
558
+ if token.strip() == "":
559
+ continue
560
+ else:
561
+ token = token.strip()
562
+
563
+ tokens.append(token)
564
+
565
+ return tokens
566
+
567
+
568
+ class CharacterTokenizer:
569
+ """Runs Character tokenization."""
570
+
571
+ def __init__(self, vocab, unk_token, normalize_text=True):
572
+ """
573
+ Constructs a CharacterTokenizer.
574
+
575
+ Args:
576
+ **vocab**:
577
+ Vocabulary object.
578
+ **unk_token**: str
579
+ A special symbol for out-of-vocabulary token.
580
+ **normalize_text**: (`optional`) boolean (default True)
581
+ Whether to apply unicode normalization to text before tokenization.
582
+ """
583
+ self.vocab = vocab
584
+ self.unk_token = unk_token
585
+ self.normalize_text = normalize_text
586
+
587
+ def tokenize(self, text):
588
+ """
589
+ Tokenizes a piece of text into characters.
590
+
591
+ For example, `input = "apple""` will return as output `["a", "p", "p", "l", "e"]`.
592
+
593
+ Args:
594
+ text: A single token or whitespace separated tokens.
595
+ This should have already been passed through *BasicTokenizer*.
596
+
597
+ Returns:
598
+ A list of characters.
599
+ """
600
+ if self.normalize_text:
601
+ text = unicodedata.normalize("NFKC", text)
602
+
603
+ output_tokens = []
604
+ for char in text:
605
+ if char not in self.vocab:
606
+ output_tokens.append(self.unk_token)
607
+ continue
608
+
609
+ output_tokens.append(char)
610
+
611
+ return output_tokens
612
+
613
+
614
+ class BasicTokenizer:
615
+ """
616
+ Constructs a BasicTokenizer that will run basic tokenization (punctuation splitting, lower casing, etc.).
617
+
618
+ Args:
619
+ do_lower_case (`bool`, *optional*, defaults to `True`):
620
+ Whether or not to lowercase the input when tokenizing.
621
+ never_split (`Iterable`, *optional*):
622
+ Collection of tokens which will never be split during tokenization. Only has an effect when
623
+ `do_basic_tokenize=True`
624
+ tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
625
+ Whether or not to tokenize Chinese characters.
626
+
627
+ This should likely be deactivated for Japanese (see this
628
+ [issue](https://github.com/huggingface/transformers/issues/328)).
629
+ strip_accents (`bool`, *optional*):
630
+ Whether or not to strip all accents. If this option is not specified, then it will be determined by the
631
+ value for `lowercase` (as in the original BERT).
632
+ do_split_on_punc (`bool`, *optional*, defaults to `True`):
633
+ In some instances we want to skip the basic punctuation splitting so that later tokenization can capture
634
+ the full context of the words, such as contractions.
635
+ """
636
+
637
+ def __init__(
638
+ self,
639
+ do_lower_case=True,
640
+ never_split=None,
641
+ tokenize_chinese_chars=True,
642
+ strip_accents=None,
643
+ do_split_on_punc=True,
644
+ ):
645
+ if never_split is None:
646
+ never_split = []
647
+ self.do_lower_case = do_lower_case
648
+ self.never_split = set(never_split)
649
+ self.tokenize_chinese_chars = tokenize_chinese_chars
650
+ self.strip_accents = strip_accents
651
+ self.do_split_on_punc = do_split_on_punc
652
+
653
+ def tokenize(self, text, never_split=None):
654
+ """
655
+ Basic Tokenization of a piece of text. For sub-word tokenization, see WordPieceTokenizer.
656
+
657
+ Args:
658
+ never_split (`List[str]`, *optional*)
659
+ Kept for backward compatibility purposes. Now implemented directly at the base class level (see
660
+ [`PreTrainedTokenizer.tokenize`]) List of token not to split.
661
+ """
662
+ # union() returns a new set by concatenating the two sets.
663
+ never_split = self.never_split.union(set(never_split)) if never_split else self.never_split
664
+ text = self._clean_text(text)
665
+
666
+ # This was added on November 1st, 2018 for the multilingual and Chinese
667
+ # models. This is also applied to the English models now, but it doesn't
668
+ # matter since the English models were not trained on any Chinese data
669
+ # and generally don't have any Chinese data in them (there are Chinese
670
+ # characters in the vocabulary because Wikipedia does have some Chinese
671
+ # words in the English Wikipedia.).
672
+ if self.tokenize_chinese_chars:
673
+ text = self._tokenize_chinese_chars(text)
674
+ # prevents treating the same character with different unicode codepoints as different characters
675
+ unicode_normalized_text = unicodedata.normalize("NFC", text)
676
+ orig_tokens = whitespace_tokenize(unicode_normalized_text)
677
+ split_tokens = []
678
+ for token in orig_tokens:
679
+ if token not in never_split:
680
+ if self.do_lower_case:
681
+ token = token.lower()
682
+ if self.strip_accents is not False:
683
+ token = self._run_strip_accents(token)
684
+ elif self.strip_accents:
685
+ token = self._run_strip_accents(token)
686
+ split_tokens.extend(self._run_split_on_punc(token, never_split))
687
+
688
+ output_tokens = whitespace_tokenize(" ".join(split_tokens))
689
+ return output_tokens
690
+
691
+ def _run_strip_accents(self, text):
692
+ """Strips accents from a piece of text."""
693
+ text = unicodedata.normalize("NFD", text)
694
+ output = []
695
+ for char in text:
696
+ cat = unicodedata.category(char)
697
+ if cat == "Mn":
698
+ continue
699
+ output.append(char)
700
+ return "".join(output)
701
+
702
+ def _run_split_on_punc(self, text, never_split=None):
703
+ """Splits punctuation on a piece of text."""
704
+ if not self.do_split_on_punc or (never_split is not None and text in never_split):
705
+ return [text]
706
+ chars = list(text)
707
+ i = 0
708
+ start_new_word = True
709
+ output = []
710
+ while i < len(chars):
711
+ char = chars[i]
712
+ if _is_punctuation(char):
713
+ output.append([char])
714
+ start_new_word = True
715
+ else:
716
+ if start_new_word:
717
+ output.append([])
718
+ start_new_word = False
719
+ output[-1].append(char)
720
+ i += 1
721
+
722
+ return ["".join(x) for x in output]
723
+
724
+ def _tokenize_chinese_chars(self, text):
725
+ """Adds whitespace around any CJK character."""
726
+ output = []
727
+ for char in text:
728
+ cp = ord(char)
729
+ if self._is_chinese_char(cp):
730
+ output.append(" ")
731
+ output.append(char)
732
+ output.append(" ")
733
+ else:
734
+ output.append(char)
735
+ return "".join(output)
736
+
737
+ def _is_chinese_char(self, cp):
738
+ """Checks whether CP is the codepoint of a CJK character."""
739
+ # This defines a "chinese character" as anything in the CJK Unicode block:
740
+ # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
741
+ #
742
+ # Note that the CJK Unicode block is NOT all Japanese and Korean characters,
743
+ # despite its name. The modern Korean Hangul alphabet is a different block,
744
+ # as is Japanese Hiragana and Katakana. Those alphabets are used to write
745
+ # space-separated words, so they are not treated specially and handled
746
+ # like the all of the other languages.
747
+ if (
748
+ (cp >= 0x4E00 and cp <= 0x9FFF)
749
+ or (cp >= 0x3400 and cp <= 0x4DBF)
750
+ or (cp >= 0x20000 and cp <= 0x2A6DF)
751
+ or (cp >= 0x2A700 and cp <= 0x2B73F)
752
+ or (cp >= 0x2B740 and cp <= 0x2B81F)
753
+ or (cp >= 0x2B820 and cp <= 0x2CEAF)
754
+ or (cp >= 0xF900 and cp <= 0xFAFF)
755
+ or (cp >= 0x2F800 and cp <= 0x2FA1F)
756
+ ):
757
+ return True
758
+
759
+ return False
760
+
761
+ def _clean_text(self, text):
762
+ """Performs invalid character removal and whitespace cleanup on text."""
763
+ output = []
764
+ for char in text:
765
+ cp = ord(char)
766
+ if cp == 0 or cp == 0xFFFD or _is_control(char):
767
+ continue
768
+ if _is_whitespace(char):
769
+ output.append(" ")
770
+ else:
771
+ output.append(char)
772
+ return "".join(output)
773
+
774
+
775
+ class WordpieceTokenizer:
776
+ """Runs WordPiece tokenization."""
777
+
778
+ def __init__(self, vocab, unk_token, max_input_chars_per_word=100):
779
+ self.vocab = vocab
780
+ self.unk_token = unk_token
781
+ self.max_input_chars_per_word = max_input_chars_per_word
782
+
783
+ def tokenize(self, text):
784
+ """
785
+ Tokenizes a piece of text into its word pieces. This uses a greedy longest-match-first algorithm to perform
786
+ tokenization using the given vocabulary.
787
+
788
+ For example, `input = "unaffable"` will return as output `["un", "##aff", "##able"]`.
789
+
790
+ Args:
791
+ text: A single token or whitespace separated tokens. This should have
792
+ already been passed through *BasicTokenizer*.
793
+
794
+ Returns:
795
+ A list of wordpiece tokens.
796
+ """
797
+
798
+ output_tokens = []
799
+ for token in whitespace_tokenize(text):
800
+ chars = list(token)
801
+ if len(chars) > self.max_input_chars_per_word:
802
+ output_tokens.append(self.unk_token)
803
+ continue
804
+
805
+ is_bad = False
806
+ start = 0
807
+ sub_tokens = []
808
+ while start < len(chars):
809
+ end = len(chars)
810
+ cur_substr = None
811
+ while start < end:
812
+ substr = "".join(chars[start:end])
813
+ if start > 0:
814
+ substr = "##" + substr
815
+ if substr in self.vocab:
816
+ cur_substr = substr
817
+ break
818
+ end -= 1
819
+ if cur_substr is None:
820
+ is_bad = True
821
+ break
822
+ sub_tokens.append(cur_substr)
823
+ start = end
824
+
825
+ if is_bad:
826
+ output_tokens.append(self.unk_token)
827
+ else:
828
+ output_tokens.extend(sub_tokens)
829
+ return output_tokens
830
+
831
+
832
+ class SentencepieceTokenizer:
833
+ """
834
+ Runs sentencepiece tokenization. Based on transformers.models.albert.tokenization_albert.AlbertTokenizer.
835
+ """
836
+
837
+ def __init__(
838
+ self,
839
+ vocab,
840
+ unk_token,
841
+ do_lower_case=False,
842
+ remove_space=True,
843
+ keep_accents=True,
844
+ sp_model_kwargs: dict[str, Any] | None = None,
845
+ ):
846
+ self.vocab = vocab
847
+ self.unk_token = unk_token
848
+ self.do_lower_case = do_lower_case
849
+ self.remove_space = remove_space
850
+ self.keep_accents = keep_accents
851
+
852
+ self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
853
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
854
+ self.sp_model.Load(self.vocab)
855
+
856
+ def preprocess_text(self, inputs):
857
+ if self.remove_space:
858
+ outputs = " ".join(inputs.strip().split())
859
+ else:
860
+ outputs = inputs
861
+ outputs = outputs.replace("``", '"').replace("''", '"')
862
+
863
+ if not self.keep_accents:
864
+ outputs = unicodedata.normalize("NFKD", outputs)
865
+ outputs = "".join([c for c in outputs if not unicodedata.combining(c)])
866
+ if self.do_lower_case:
867
+ outputs = outputs.lower()
868
+
869
+ return outputs
870
+
871
+ def tokenize(self, text):
872
+ """
873
+ Tokenizes text by sentencepiece. Based on [SentencePiece](https://github.com/google/sentencepiece).
874
+ Tokenization needs the given vocabulary.
875
+
876
+ Args:
877
+ text: A string needs to be tokenized.
878
+
879
+ Returns:
880
+ A list of sentencepiece tokens.
881
+ """
882
+ text = self.preprocess_text(text)
883
+ pieces = self.sp_model.encode(text, out_type=str)
884
+ new_pieces = []
885
+ for piece in pieces:
886
+ if len(piece) > 1 and piece[-1] == "," and piece[-2].isdigit():
887
+ cur_pieces = self.sp_model.EncodeAsPieces(piece[:-1].replace(SPIECE_UNDERLINE, ""))
888
+ if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE:
889
+ if len(cur_pieces[0]) == 1:
890
+ cur_pieces = cur_pieces[1:]
891
+ else:
892
+ cur_pieces[0] = cur_pieces[0][1:]
893
+ cur_pieces.append(piece[-1])
894
+ new_pieces.extend(cur_pieces)
895
+ else:
896
+ new_pieces.append(piece)
897
+
898
+ return new_pieces
899
+
900
+
901
+ __all__ = ["BertJapaneseTokenizer", "CharacterTokenizer", "MecabTokenizer"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/cpm/__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_cpm 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/cpm/tokenization_cpm.py ADDED
@@ -0,0 +1,336 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Tokenization classes."""
15
+
16
+ import os
17
+ import unicodedata
18
+ from shutil import copyfile
19
+ from typing import Any
20
+
21
+ import sentencepiece as spm
22
+
23
+ from ...tokenization_python import AddedToken, PreTrainedTokenizer
24
+ from ...utils import SPIECE_UNDERLINE, logging
25
+ from ...utils.import_utils import requires
26
+
27
+
28
+ logger = logging.get_logger(__name__)
29
+
30
+ VOCAB_FILES_NAMES = {"vocab_file": "spiece.model"}
31
+
32
+
33
+ @requires(backends=("sentencepiece",))
34
+ class CpmTokenizer(PreTrainedTokenizer):
35
+ """Runs pre-tokenization with Jieba-RS segmentation tool. It is used in CPM models."""
36
+
37
+ vocab_files_names = VOCAB_FILES_NAMES
38
+
39
+ def __init__(
40
+ self,
41
+ vocab_file,
42
+ do_lower_case=False,
43
+ remove_space=True,
44
+ keep_accents=False,
45
+ bos_token="<s>",
46
+ eos_token="</s>",
47
+ unk_token="<unk>",
48
+ sep_token="<sep>",
49
+ pad_token="<pad>",
50
+ cls_token="<cls>",
51
+ mask_token="<mask>",
52
+ additional_special_tokens=["<eop>", "<eod>"],
53
+ sp_model_kwargs: dict[str, Any] | None = None,
54
+ **kwargs,
55
+ ) -> None:
56
+ """
57
+ Construct a CPM tokenizer. Based on [Jieba-RS](https://pypi.org/project/rjieba/) and
58
+ [SentencePiece](https://github.com/google/sentencepiece).
59
+
60
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should
61
+ refer to this superclass for more information regarding those methods.
62
+
63
+ Args:
64
+ vocab_file (`str`):
65
+ [SentencePiece](https://github.com/google/sentencepiece) file (generally has a .spm extension) that
66
+ contains the vocabulary necessary to instantiate a tokenizer.
67
+ do_lower_case (`bool`, *optional*, defaults to `True`):
68
+ Whether to lowercase the input when tokenizing.
69
+ remove_space (`bool`, *optional*, defaults to `True`):
70
+ Whether to strip the text when tokenizing (removing excess spaces before and after the string).
71
+ keep_accents (`bool`, *optional*, defaults to `False`):
72
+ Whether to keep accents when tokenizing.
73
+ bos_token (`str`, *optional*, defaults to `"<s>"`):
74
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier
75
+ token.
76
+
77
+ <Tip>
78
+
79
+ When building a sequence using special tokens, this is not the token that is used for the beginning of
80
+ sequence. The token used is the `cls_token`.
81
+
82
+ </Tip>
83
+
84
+ eos_token (`str`, *optional*, defaults to `"</s>"`):
85
+ The end of sequence token.
86
+
87
+ <Tip>
88
+
89
+ When building a sequence using special tokens, this is not the token that is used for the end of
90
+ sequence. The token used is the `sep_token`.
91
+
92
+ </Tip>
93
+
94
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
95
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be
96
+ this token instead.
97
+ sep_token (`str`, *optional*, defaults to `"<sep>"`):
98
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences
99
+ for sequence classification or for a text and a question for question answering. It is also used as the
100
+ last token of a sequence built with special tokens.
101
+ pad_token (`str`, *optional*, defaults to `"<pad>"`):
102
+ The token used for padding, for example when batching sequences of different lengths.
103
+ cls_token (`str`, *optional*, defaults to `"<cls>"`):
104
+ The classifier token which is used when doing sequence classification (classification of the whole
105
+ sequence instead of per-token classification). It is the first token of the sequence when built with
106
+ special tokens.
107
+ mask_token (`str`, *optional*, defaults to `"<mask>"`):
108
+ The token used for masking values. This is the token used when training this model with masked language
109
+ modeling. This is the token which the model will try to predict.
110
+ additional_special_tokens (`list[str]`, *optional*, defaults to `["<eop>", "<eod>"]`):
111
+ Additional special tokens used by the tokenizer.
112
+
113
+ Attributes:
114
+ sp_model (`SentencePieceProcessor`):
115
+ The *SentencePiece* processor that is used for every conversion (string, tokens and IDs).
116
+ """
117
+ # Mask token behave like a normal word, i.e. include the space before it
118
+ mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token
119
+
120
+ self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
121
+
122
+ self.do_lower_case = do_lower_case
123
+ self.remove_space = remove_space
124
+ self.keep_accents = keep_accents
125
+ self.vocab_file = vocab_file
126
+
127
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
128
+ self.sp_model.Load(vocab_file)
129
+
130
+ try:
131
+ import rjieba
132
+ except ModuleNotFoundError as error:
133
+ raise error.__class__(
134
+ "You need to install rjieba to use CpmTokenizer or CpmTokenizerFast. "
135
+ "See https://pypi.org/project/rjieba/ for installation."
136
+ )
137
+ self.jieba = rjieba
138
+ self.translator = str.maketrans(" \n", "\u2582\u2583")
139
+
140
+ super().__init__(
141
+ do_lower_case=do_lower_case,
142
+ remove_space=remove_space,
143
+ keep_accents=keep_accents,
144
+ bos_token=bos_token,
145
+ eos_token=eos_token,
146
+ unk_token=unk_token,
147
+ sep_token=sep_token,
148
+ pad_token=pad_token,
149
+ cls_token=cls_token,
150
+ mask_token=mask_token,
151
+ additional_special_tokens=additional_special_tokens,
152
+ sp_model_kwargs=self.sp_model_kwargs,
153
+ **kwargs,
154
+ )
155
+
156
+ self._pad_token_type_id = 3
157
+
158
+ @property
159
+ def vocab_size(self):
160
+ return len(self.sp_model)
161
+
162
+ def get_vocab(self):
163
+ vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
164
+ vocab.update(self.added_tokens_encoder)
165
+ return vocab
166
+
167
+ def __getstate__(self):
168
+ state = self.__dict__.copy()
169
+ state["sp_model"] = None
170
+ return state
171
+
172
+ def __setstate__(self, d):
173
+ self.__dict__ = d
174
+
175
+ # for backward compatibility
176
+ if not hasattr(self, "sp_model_kwargs"):
177
+ self.sp_model_kwargs = {}
178
+
179
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
180
+ self.sp_model.Load(self.vocab_file)
181
+
182
+ def preprocess_text(self, inputs):
183
+ if self.remove_space:
184
+ outputs = " ".join(inputs.strip().split())
185
+ else:
186
+ outputs = inputs
187
+ outputs = outputs.replace("``", '"').replace("''", '"')
188
+
189
+ if not self.keep_accents:
190
+ outputs = unicodedata.normalize("NFKD", outputs)
191
+ outputs = "".join([c for c in outputs if not unicodedata.combining(c)])
192
+ if self.do_lower_case:
193
+ outputs = outputs.lower()
194
+
195
+ return outputs
196
+
197
+ def _tokenize(self, text: str) -> list[str]:
198
+ """Tokenize a string."""
199
+ text = self.preprocess_text(text)
200
+ pieces = self.sp_model.encode(text, out_type=str)
201
+ new_pieces = []
202
+ for piece in pieces:
203
+ if len(piece) > 1 and piece[-1] == "," and piece[-2].isdigit():
204
+ cur_pieces = self.sp_model.EncodeAsPieces(piece[:-1].replace(SPIECE_UNDERLINE, ""))
205
+ if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE:
206
+ if len(cur_pieces[0]) == 1:
207
+ cur_pieces = cur_pieces[1:]
208
+ else:
209
+ cur_pieces[0] = cur_pieces[0][1:]
210
+ cur_pieces.append(piece[-1])
211
+ new_pieces.extend(cur_pieces)
212
+ else:
213
+ new_pieces.append(piece)
214
+
215
+ return new_pieces
216
+
217
+ def _convert_token_to_id(self, token):
218
+ """Converts a token (str) in an id using the vocab."""
219
+ return self.sp_model.PieceToId(token)
220
+
221
+ def _convert_id_to_token(self, index):
222
+ """Converts an index (integer) in a token (str) using the vocab."""
223
+ return self.sp_model.IdToPiece(index)
224
+
225
+ def convert_tokens_to_string(self, tokens):
226
+ """Converts a sequence of tokens (strings for sub-words) in a single string."""
227
+ out_string = "".join(tokens).replace(SPIECE_UNDERLINE, " ").strip()
228
+ return out_string
229
+
230
+ def build_inputs_with_special_tokens(
231
+ self, token_ids_0: list[int], token_ids_1: list[int] | None = None
232
+ ) -> list[int]:
233
+ """
234
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
235
+ adding special tokens. An XLNet sequence has the following format:
236
+
237
+ - single sequence: `X <sep> <cls>`
238
+ - pair of sequences: `A <sep> B <sep> <cls>`
239
+
240
+ Args:
241
+ token_ids_0 (`list[int]`):
242
+ List of IDs to which the special tokens will be added.
243
+ token_ids_1 (`list[int]`, *optional*):
244
+ Optional second list of IDs for sequence pairs.
245
+
246
+ Returns:
247
+ `list[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
248
+ """
249
+ sep = [self.sep_token_id]
250
+ cls = [self.cls_token_id]
251
+ if token_ids_1 is None:
252
+ return token_ids_0 + sep + cls
253
+ return token_ids_0 + sep + token_ids_1 + sep + cls
254
+
255
+ def get_special_tokens_mask(
256
+ self, token_ids_0: list[int], token_ids_1: list[int] | None = None, already_has_special_tokens: bool = False
257
+ ) -> list[int]:
258
+ """
259
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
260
+ special tokens using the tokenizer `prepare_for_model` method.
261
+
262
+ Args:
263
+ token_ids_0 (`list[int]`):
264
+ List of IDs.
265
+ token_ids_1 (`list[int]`, *optional*):
266
+ Optional second list of IDs for sequence pairs.
267
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
268
+ Whether or not the token list is already formatted with special tokens for the model.
269
+
270
+ Returns:
271
+ `list[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
272
+ """
273
+
274
+ if already_has_special_tokens:
275
+ return super().get_special_tokens_mask(
276
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
277
+ )
278
+
279
+ if token_ids_1 is not None:
280
+ return ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1, 1]
281
+ return ([0] * len(token_ids_0)) + [1, 1]
282
+
283
+ def create_token_type_ids_from_sequences(
284
+ self, token_ids_0: list[int], token_ids_1: list[int] | None = None
285
+ ) -> list[int]:
286
+ """
287
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. An XLNet
288
+ sequence pair mask has the following format:
289
+
290
+ ```
291
+ 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
292
+ | first sequence | second sequence |
293
+ ```
294
+
295
+ If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
296
+
297
+ Args:
298
+ token_ids_0 (`list[int]`):
299
+ List of IDs.
300
+ token_ids_1 (`list[int]`, *optional*):
301
+ Optional second list of IDs for sequence pairs.
302
+
303
+ Returns:
304
+ `list[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
305
+ """
306
+ sep = [self.sep_token_id]
307
+ cls_segment_id = [2]
308
+
309
+ if token_ids_1 is None:
310
+ return len(token_ids_0 + sep) * [0] + cls_segment_id
311
+ return len(token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1] + cls_segment_id
312
+
313
+ def save_vocabulary(self, save_directory: str, filename_prefix: str | None = None) -> tuple[str]:
314
+ if not os.path.isdir(save_directory):
315
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
316
+ return
317
+ out_vocab_file = os.path.join(
318
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
319
+ )
320
+
321
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
322
+ copyfile(self.vocab_file, out_vocab_file)
323
+ elif not os.path.isfile(self.vocab_file):
324
+ with open(out_vocab_file, "wb") as fi:
325
+ content_spiece_model = self.sp_model.serialized_model_proto()
326
+ fi.write(content_spiece_model)
327
+
328
+ return (out_vocab_file,)
329
+
330
+ def _decode(self, *args, **kwargs):
331
+ text = super()._decode(*args, **kwargs)
332
+ text = text.replace(" ", "").replace("\u2582", " ").replace("\u2583", "\n")
333
+ return text
334
+
335
+
336
+ __all__ = ["CpmTokenizer"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/cpm/tokenization_cpm_fast.py ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Tokenization classes."""
15
+
16
+ import os
17
+ from shutil import copyfile
18
+
19
+ from ...tokenization_utils_tokenizers import AddedToken, PreTrainedTokenizerFast
20
+ from ...utils import logging
21
+
22
+
23
+ logger = logging.get_logger(__name__)
24
+
25
+ VOCAB_FILES_NAMES = {"vocab_file": "spiece.model", "tokenizer_file": "tokenizer.json"}
26
+
27
+
28
+ class CpmTokenizerFast(PreTrainedTokenizerFast):
29
+ """Runs pre-tokenization with Jieba-RS segmentation tool. It is used in CPM models."""
30
+
31
+ def __init__(
32
+ self,
33
+ vocab_file=None,
34
+ tokenizer_file=None,
35
+ do_lower_case=False,
36
+ remove_space=True,
37
+ keep_accents=False,
38
+ bos_token="<s>",
39
+ eos_token="</s>",
40
+ unk_token="<unk>",
41
+ sep_token="<sep>",
42
+ pad_token="<pad>",
43
+ cls_token="<cls>",
44
+ mask_token="<mask>",
45
+ additional_special_tokens=["<eop>", "<eod>"],
46
+ **kwargs,
47
+ ):
48
+ """
49
+ Construct a CPM tokenizer. Based on [Jieba-RS](https://pypi.org/project/rjieba/) and
50
+ [SentencePiece](https://github.com/google/sentencepiece).
51
+
52
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should
53
+ refer to this superclass for more information regarding those methods.
54
+
55
+ Args:
56
+ vocab_file (`str`):
57
+ [SentencePiece](https://github.com/google/sentencepiece) file (generally has a .spm extension) that
58
+ contains the vocabulary necessary to instantiate a tokenizer.
59
+ do_lower_case (`bool`, *optional*, defaults to `True`):
60
+ Whether to lowercase the input when tokenizing.
61
+ remove_space (`bool`, *optional*, defaults to `True`):
62
+ Whether to strip the text when tokenizing (removing excess spaces before and after the string).
63
+ keep_accents (`bool`, *optional*, defaults to `False`):
64
+ Whether to keep accents when tokenizing.
65
+ bos_token (`str`, *optional*, defaults to `"<s>"`):
66
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier
67
+ token.
68
+
69
+ <Tip>
70
+
71
+ When building a sequence using special tokens, this is not the token that is used for the beginning of
72
+ sequence. The token used is the `cls_token`.
73
+
74
+ </Tip>
75
+
76
+ eos_token (`str`, *optional*, defaults to `"</s>"`):
77
+ The end of sequence token.
78
+
79
+ <Tip>
80
+
81
+ When building a sequence using special tokens, this is not the token that is used for the end of
82
+ sequence. The token used is the `sep_token`.
83
+
84
+ </Tip>
85
+
86
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
87
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be
88
+ this token instead.
89
+ sep_token (`str`, *optional*, defaults to `"<sep>"`):
90
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences
91
+ for sequence classification or for a text and a question for question answering. It is also used as the
92
+ last token of a sequence built with special tokens.
93
+ pad_token (`str`, *optional*, defaults to `"<pad>"`):
94
+ The token used for padding, for example when batching sequences of different lengths.
95
+ cls_token (`str`, *optional*, defaults to `"<cls>"`):
96
+ The classifier token which is used when doing sequence classification (classification of the whole
97
+ sequence instead of per-token classification). It is the first token of the sequence when built with
98
+ special tokens.
99
+ mask_token (`str`, *optional*, defaults to `"<mask>"`):
100
+ The token used for masking values. This is the token used when training this model with masked language
101
+ modeling. This is the token which the model will try to predict.
102
+ additional_special_tokens (`list[str]`, *optional*, defaults to `["<eop>", "<eod>"]`):
103
+ Additional special tokens used by the tokenizer.
104
+
105
+ Attributes:
106
+ sp_model (`SentencePieceProcessor`):
107
+ The *SentencePiece* processor that is used for every conversion (string, tokens and IDs).
108
+ """
109
+ # Mask token behave like a normal word, i.e. include the space before it
110
+ mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token
111
+
112
+ super().__init__(
113
+ vocab_file=vocab_file,
114
+ tokenizer_file=tokenizer_file,
115
+ do_lower_case=do_lower_case,
116
+ remove_space=remove_space,
117
+ keep_accents=keep_accents,
118
+ bos_token=bos_token,
119
+ eos_token=eos_token,
120
+ unk_token=unk_token,
121
+ sep_token=sep_token,
122
+ pad_token=pad_token,
123
+ cls_token=cls_token,
124
+ mask_token=mask_token,
125
+ additional_special_tokens=additional_special_tokens,
126
+ **kwargs,
127
+ )
128
+
129
+ self._pad_token_type_id = 3
130
+ self.do_lower_case = do_lower_case
131
+ self.remove_space = remove_space
132
+ self.keep_accents = keep_accents
133
+ self.vocab_file = vocab_file
134
+
135
+ try:
136
+ import rjieba
137
+ except ModuleNotFoundError as error:
138
+ raise error.__class__(
139
+ "You need to install rjieba to use CpmTokenizer or CpmTokenizerFast. "
140
+ "See https://pypi.org/project/rjieba/ for installation."
141
+ )
142
+ self.jieba = rjieba
143
+ self.translator = str.maketrans(" \n", "\u2582\u2583")
144
+
145
+ def build_inputs_with_special_tokens(
146
+ self, token_ids_0: list[int], token_ids_1: list[int] | None = None
147
+ ) -> list[int]:
148
+ """
149
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
150
+ adding special tokens. An XLNet sequence has the following format:
151
+
152
+ - single sequence: `X <sep> <cls>`
153
+ - pair of sequences: `A <sep> B <sep> <cls>`
154
+
155
+ Args:
156
+ token_ids_0 (`list[int]`):
157
+ List of IDs to which the special tokens will be added.
158
+ token_ids_1 (`list[int]`, *optional*):
159
+ Optional second list of IDs for sequence pairs.
160
+
161
+ Returns:
162
+ `list[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
163
+ """
164
+ sep = [self.sep_token_id]
165
+ cls = [self.cls_token_id]
166
+ if token_ids_1 is None:
167
+ return token_ids_0 + sep + cls
168
+ return token_ids_0 + sep + token_ids_1 + sep + cls
169
+
170
+ def create_token_type_ids_from_sequences(
171
+ self, token_ids_0: list[int], token_ids_1: list[int] | None = None
172
+ ) -> list[int]:
173
+ """
174
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. An XLNet
175
+ sequence pair mask has the following format:
176
+
177
+ ```
178
+ 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
179
+ | first sequence | second sequence |
180
+ ```
181
+
182
+ If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
183
+
184
+ Args:
185
+ token_ids_0 (`list[int]`):
186
+ List of IDs.
187
+ token_ids_1 (`list[int]`, *optional*):
188
+ Optional second list of IDs for sequence pairs.
189
+
190
+ Returns:
191
+ `list[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
192
+ """
193
+ sep = [self.sep_token_id]
194
+ cls_segment_id = [2]
195
+
196
+ if token_ids_1 is None:
197
+ return len(token_ids_0 + sep) * [0] + cls_segment_id
198
+ return len(token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1] + cls_segment_id
199
+
200
+ def save_vocabulary(self, save_directory: str, filename_prefix: str | None = None) -> tuple[str]:
201
+ if not self.can_save_slow_tokenizer:
202
+ raise ValueError(
203
+ "Your fast tokenizer does not have the necessary information to save the vocabulary for a slow "
204
+ "tokenizer."
205
+ )
206
+
207
+ if not os.path.isdir(save_directory):
208
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
209
+ return
210
+ out_vocab_file = os.path.join(
211
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
212
+ )
213
+
214
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file):
215
+ copyfile(self.vocab_file, out_vocab_file)
216
+
217
+ return (out_vocab_file,)
218
+
219
+ def _batch_encode_plus(self, batch_text_or_text_pairs, *args, **kwargs):
220
+ batch_text_or_text_pairs = [
221
+ " ".join([x.translate(self.translator) for x in self.jieba.cut(text, False)])
222
+ for text in batch_text_or_text_pairs
223
+ ]
224
+ return super()._batch_encode_plus(batch_text_or_text_pairs, *args, **kwargs)
225
+
226
+ def _decode(self, *args, **kwargs):
227
+ text = super()._decode(*args, **kwargs)
228
+ text = text.replace(" ", "").replace("\u2582", " ").replace("\u2583", "\n")
229
+ return text
230
+
231
+
232
+ __all__ = ["CpmTokenizerFast"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/glmasr/modeling_glmasr.py ADDED
@@ -0,0 +1,531 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/glmasr/modular_glmasr.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_glmasr.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # Copyright 2025 the HuggingFace Team. All rights reserved.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+
21
+ from collections.abc import Callable
22
+ from typing import Optional
23
+
24
+ from ...activations import ACT2FN
25
+ from ...cache_utils import Cache
26
+ from ...generation import GenerationMixin
27
+ from ...integrations import use_kernelized_func
28
+ from ...modeling_layers import GradientCheckpointingLayer
29
+ from ...modeling_outputs import BaseModelOutputWithPooling, CausalLMOutputWithPast
30
+ from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
31
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
32
+ from ...processing_utils import Unpack
33
+ from ...utils import TransformersKwargs, auto_docstring, is_torch_available, torch_compilable_check
34
+ from ...utils.generic import can_return_tuple, maybe_autocast, merge_with_config_defaults
35
+ from ...utils.output_capturing import capture_outputs
36
+ from ..auto import AutoModel, AutoModelForCausalLM
37
+ from .configuration_glmasr import GlmAsrConfig, GlmAsrEncoderConfig
38
+
39
+
40
+ if is_torch_available():
41
+ import torch
42
+ from torch import nn
43
+
44
+
45
+ class GlmAsrRotaryEmbedding(nn.Module):
46
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
47
+
48
+ def __init__(self, config: GlmAsrConfig, device=None):
49
+ super().__init__()
50
+ self.max_seq_len_cached = config.max_position_embeddings
51
+ self.original_max_seq_len = config.max_position_embeddings
52
+
53
+ self.config = config
54
+
55
+ self.rope_type = self.config.rope_parameters["rope_type"]
56
+ rope_init_fn: Callable = self.compute_default_rope_parameters
57
+ if self.rope_type != "default":
58
+ rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
59
+ inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
60
+
61
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
62
+ self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
63
+
64
+ @staticmethod
65
+ def compute_default_rope_parameters(
66
+ config: GlmAsrConfig | None = None,
67
+ device: Optional["torch.device"] = None,
68
+ seq_len: int | None = None,
69
+ ) -> tuple["torch.Tensor", float]:
70
+ """
71
+ Computes the inverse frequencies according to the original RoPE implementation
72
+ Args:
73
+ config ([`~transformers.PreTrainedConfig`]):
74
+ The model configuration.
75
+ device (`torch.device`):
76
+ The device to use for initialization of the inverse frequencies.
77
+ seq_len (`int`, *optional*):
78
+ The current sequence length. Unused for this type of RoPE.
79
+ Returns:
80
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
81
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
82
+ """
83
+ base = config.rope_parameters["rope_theta"]
84
+ partial_rotary_factor = config.rope_parameters.get("partial_rotary_factor", 1.0)
85
+ head_dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
86
+ dim = int(head_dim * partial_rotary_factor)
87
+
88
+ attention_factor = 1.0 # Unused in this type of RoPE
89
+
90
+ # Compute the inverse frequencies
91
+ inv_freq = 1.0 / (
92
+ base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
93
+ )
94
+ return inv_freq, attention_factor
95
+
96
+ @torch.no_grad()
97
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
98
+ def forward(self, x, position_ids):
99
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
100
+ position_ids_expanded = position_ids[:, None, :].float()
101
+
102
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
103
+ with maybe_autocast(device_type=device_type, enabled=False): # Force float32
104
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
105
+ emb = torch.cat((freqs, freqs), dim=-1)
106
+ cos = emb.cos() * self.attention_scaling
107
+ sin = emb.sin() * self.attention_scaling
108
+
109
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
110
+
111
+
112
+ def rotate_half(x):
113
+ """Rotates half the hidden dims of the input."""
114
+ x1 = x[..., : x.shape[-1] // 2]
115
+ x2 = x[..., x.shape[-1] // 2 :]
116
+ return torch.cat((-x2, x1), dim=-1)
117
+
118
+
119
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
120
+ """
121
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
122
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
123
+ """
124
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
125
+ if n_rep == 1:
126
+ return hidden_states
127
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
128
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
129
+
130
+
131
+ def eager_attention_forward(
132
+ module: nn.Module,
133
+ query: torch.Tensor,
134
+ key: torch.Tensor,
135
+ value: torch.Tensor,
136
+ attention_mask: torch.Tensor | None,
137
+ scaling: float,
138
+ dropout: float = 0.0,
139
+ **kwargs: Unpack[TransformersKwargs],
140
+ ):
141
+ key_states = repeat_kv(key, module.num_key_value_groups)
142
+ value_states = repeat_kv(value, module.num_key_value_groups)
143
+
144
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
145
+ if attention_mask is not None:
146
+ attn_weights = attn_weights + attention_mask
147
+
148
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
149
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
150
+ attn_output = torch.matmul(attn_weights, value_states)
151
+ attn_output = attn_output.transpose(1, 2).contiguous()
152
+
153
+ return attn_output, attn_weights
154
+
155
+
156
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
157
+ cos = cos.unsqueeze(unsqueeze_dim)
158
+ sin = sin.unsqueeze(unsqueeze_dim)
159
+
160
+ rotary_dim = cos.shape[-1]
161
+ q_rot, q_pass = q[..., :rotary_dim], q[..., rotary_dim:]
162
+ k_rot, k_pass = k[..., :rotary_dim], k[..., rotary_dim:]
163
+
164
+ # Apply rotary embeddings on the first half or full tensor
165
+ q_embed = (q_rot * cos) + (rotate_half(q_rot) * sin)
166
+ k_embed = (k_rot * cos) + (rotate_half(k_rot) * sin)
167
+
168
+ # Concatenate back to full shape
169
+ q_embed = torch.cat([q_embed, q_pass], dim=-1)
170
+ k_embed = torch.cat([k_embed, k_pass], dim=-1)
171
+ return q_embed, k_embed
172
+
173
+
174
+ @use_kernelized_func(apply_rotary_pos_emb)
175
+ class GlmAsrAttention(nn.Module):
176
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
177
+
178
+ def __init__(self, config: GlmAsrConfig, layer_idx: int):
179
+ super().__init__()
180
+ self.config = config
181
+ self.layer_idx = layer_idx
182
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
183
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
184
+ self.scaling = self.head_dim**-0.5
185
+ self.attention_dropout = config.attention_dropout
186
+ self.is_causal = False
187
+ self.q_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=True)
188
+ self.k_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=False)
189
+ self.v_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=True)
190
+ self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=True)
191
+
192
+ def forward(
193
+ self,
194
+ hidden_states: torch.Tensor,
195
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
196
+ **kwargs: Unpack[TransformersKwargs],
197
+ ) -> tuple[torch.Tensor, torch.Tensor]:
198
+ input_shape = hidden_states.shape[:-1]
199
+ hidden_shape = (*input_shape, -1, self.head_dim)
200
+
201
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
202
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
203
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
204
+
205
+ cos, sin = position_embeddings
206
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
207
+
208
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
209
+ self.config._attn_implementation, eager_attention_forward
210
+ )
211
+
212
+ attn_output, attn_weights = attention_interface(
213
+ self,
214
+ query_states,
215
+ key_states,
216
+ value_states,
217
+ attention_mask=None,
218
+ dropout=0.0 if not self.training else self.attention_dropout,
219
+ scaling=self.scaling,
220
+ **kwargs,
221
+ )
222
+
223
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
224
+ attn_output = self.o_proj(attn_output)
225
+ return attn_output, attn_weights
226
+
227
+
228
+ class GlmAsrMLP(nn.Module):
229
+ def __init__(self, config):
230
+ super().__init__()
231
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
232
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
233
+ self.act_fn = ACT2FN[config.hidden_act]
234
+
235
+ def forward(self, hidden_states: torch.Tensor):
236
+ hidden_states = self.fc1(hidden_states)
237
+ hidden_states = self.act_fn(hidden_states)
238
+ hidden_states = self.fc2(hidden_states)
239
+ return hidden_states
240
+
241
+
242
+ class GlmAsrEncoderLayer(GradientCheckpointingLayer):
243
+ def __init__(self, config: GlmAsrConfig, layer_idx: int):
244
+ super().__init__()
245
+ self.hidden_size = config.hidden_size
246
+
247
+ self.self_attn = GlmAsrAttention(config=config, layer_idx=layer_idx)
248
+
249
+ self.mlp = GlmAsrMLP(config)
250
+ self.input_layernorm = nn.LayerNorm(config.hidden_size)
251
+ self.post_attention_layernorm = nn.LayerNorm(config.hidden_size)
252
+
253
+ def forward(
254
+ self,
255
+ hidden_states: torch.Tensor,
256
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
257
+ **kwargs: Unpack[TransformersKwargs],
258
+ ) -> torch.Tensor:
259
+ residual = hidden_states
260
+ hidden_states = self.input_layernorm(hidden_states)
261
+ # Self Attention
262
+ hidden_states, _ = self.self_attn(
263
+ hidden_states=hidden_states,
264
+ position_embeddings=position_embeddings,
265
+ **kwargs,
266
+ )
267
+ hidden_states = residual + hidden_states
268
+
269
+ # Fully Connected
270
+ residual = hidden_states
271
+ hidden_states = self.post_attention_layernorm(hidden_states)
272
+ hidden_states = self.mlp(hidden_states)
273
+ hidden_states = residual + hidden_states
274
+ return hidden_states
275
+
276
+
277
+ @auto_docstring
278
+ class GlmAsrPreTrainedModel(PreTrainedModel):
279
+ config: GlmAsrConfig
280
+ base_model_prefix = "model"
281
+ input_modalities = ("audio", "text")
282
+ supports_gradient_checkpointing = True
283
+ _no_split_modules = ["GlmAsrAttention"]
284
+ _skip_keys_device_placement = ["past_key_values"]
285
+ _supports_flash_attn = True
286
+ _supports_sdpa = True
287
+
288
+
289
+ # TODO: @eustlb, this is what WhisperEncoder should look like
290
+ class GlmAsrEncoder(GlmAsrPreTrainedModel):
291
+ config: GlmAsrEncoderConfig
292
+ main_input_name = "input_features"
293
+ input_modalities = "audio"
294
+ _no_split_modules = ["GlmAsrEncoderLayer"]
295
+ _can_record_outputs = {
296
+ "hidden_states": GlmAsrEncoderLayer,
297
+ "attentions": GlmAsrAttention,
298
+ }
299
+
300
+ def __init__(self, config: GlmAsrEncoderConfig):
301
+ super().__init__(config)
302
+ self.conv1 = nn.Conv1d(config.num_mel_bins, config.hidden_size, kernel_size=3, padding=1)
303
+ self.conv2 = nn.Conv1d(config.hidden_size, config.hidden_size, kernel_size=3, stride=2, padding=1)
304
+
305
+ self.layers = nn.ModuleList(
306
+ [GlmAsrEncoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
307
+ )
308
+ self.norm = nn.LayerNorm(config.hidden_size)
309
+ self.rotary_emb = GlmAsrRotaryEmbedding(config=config)
310
+ self.gradient_checkpointing = False
311
+ self.post_init()
312
+
313
+ @merge_with_config_defaults
314
+ @capture_outputs
315
+ @auto_docstring
316
+ def forward(self, input_features, **kwargs: Unpack[TransformersKwargs]):
317
+ inputs_embeds = nn.functional.gelu(self.conv1(input_features))
318
+ inputs_embeds = nn.functional.gelu(self.conv2(inputs_embeds))
319
+ inputs_embeds = inputs_embeds.transpose(1, 2)
320
+
321
+ hidden_states = inputs_embeds
322
+ position_embeddings = self.rotary_emb(
323
+ hidden_states, position_ids=torch.arange(hidden_states.shape[1], device=hidden_states.device)[None, :]
324
+ )
325
+
326
+ for encoder_layer in self.layers:
327
+ hidden_states = encoder_layer(hidden_states, position_embeddings=position_embeddings, **kwargs)
328
+
329
+ hidden_states = self.norm(hidden_states)
330
+ return BaseModelOutputWithPooling(last_hidden_state=hidden_states)
331
+
332
+
333
+ class GlmAsrMultiModalProjector(nn.Module):
334
+ """
335
+ Audio adaptor (small MLP) that projects GlmAsrEncoder features
336
+ to the LLM embedding space so they can replace `<sound>` tokens.
337
+ """
338
+
339
+ def __init__(self, config: GlmAsrConfig):
340
+ super().__init__()
341
+ self.linear_1 = nn.Linear(config.audio_config.intermediate_size, config.text_config.hidden_size * 2)
342
+ self.act = ACT2FN[config.projector_hidden_act]
343
+ self.linear_2 = nn.Linear(config.text_config.hidden_size * 2, config.text_config.hidden_size)
344
+
345
+ def forward(self, audio_features):
346
+ hidden_states = self.linear_1(audio_features)
347
+ hidden_states = self.act(hidden_states)
348
+ hidden_states = self.linear_2(hidden_states)
349
+ return hidden_states
350
+
351
+
352
+ @auto_docstring(
353
+ custom_intro="""
354
+ The GlmAsr model which consists of a fine-tuned Whisper encoder, a multi-modal projector and a Llama language model.
355
+ """
356
+ )
357
+ class GlmAsrForConditionalGeneration(GlmAsrPreTrainedModel, GenerationMixin):
358
+ _keep_in_fp32_modules_strict = None
359
+ _supports_attention_backend = True
360
+ _tp_plan = None
361
+ _pp_plan = None
362
+
363
+ def __init__(self, config):
364
+ super().__init__(config)
365
+ self.vocab_size = config.text_config.vocab_size
366
+ self.audio_tower = AutoModel.from_config(config.audio_config)
367
+ self.language_model = AutoModelForCausalLM.from_config(config.text_config)
368
+ self.multi_modal_projector = GlmAsrMultiModalProjector(config)
369
+
370
+ # Initialize weights and apply final processing
371
+ self.post_init()
372
+
373
+ def get_output_embeddings(self):
374
+ return self.language_model.get_output_embeddings()
375
+
376
+ def set_output_embeddings(self, new_embeddings):
377
+ self.language_model.set_output_embeddings(new_embeddings)
378
+
379
+ def set_decoder(self, decoder):
380
+ self.language_model.set_decoder(decoder)
381
+
382
+ def get_decoder(self):
383
+ return self.language_model.get_decoder()
384
+
385
+ @can_return_tuple
386
+ @auto_docstring(
387
+ custom_intro="Compute audio embeddings from log-mel input features using the audio encoder and multi-modal projector."
388
+ )
389
+ def get_audio_features(
390
+ self,
391
+ input_features: torch.FloatTensor,
392
+ input_features_mask: torch.Tensor,
393
+ **kwargs: Unpack[TransformersKwargs],
394
+ ) -> tuple | BaseModelOutputWithPooling:
395
+ r"""
396
+ input_features (`torch.FloatTensor`):
397
+ Float values of mel features extracted from the raw speech waveform. Raw speech waveform can be
398
+ obtained by loading a `.flac` or `.wav` audio file into an array of type `list[float]` or a
399
+ `numpy.ndarray`, *e.g.* via the soundfile library (`pip install soundfile`). To prepare the array into
400
+ `input_features`, the [`AutoFeatureExtractor`] should be used for extracting the mel features, padding
401
+ and conversion into a tensor of type `torch.FloatTensor`. See [`~WhisperFeatureExtractor.__call__`]
402
+ input_features_mask (`torch.Tensor` of shape `(batch_size, feature_sequence_length)`):
403
+ Mask to avoid performing attention on padded feature indices.
404
+ """
405
+ audio_outputs = self.audio_tower(input_features, return_dict=True, **kwargs)
406
+ audio_hidden_states = audio_outputs.last_hidden_state
407
+ audio_hidden_states = audio_hidden_states.reshape(
408
+ input_features.shape[0], -1, self.config.audio_config.intermediate_size
409
+ )
410
+ audio_embeds = self.multi_modal_projector(audio_hidden_states)
411
+
412
+ audio_lengths = input_features_mask.sum(-1)
413
+ for padding, kernel_size, stride in [(1, 3, 1), (1, 3, 2)]:
414
+ audio_lengths = (audio_lengths + 2 * padding - (kernel_size - 1) - 1) // stride + 1
415
+ merge_factor = 4
416
+ post_lengths = (audio_lengths - merge_factor) // merge_factor + 1
417
+
418
+ valid_mask = torch.arange(audio_embeds.shape[1], device=post_lengths.device)[None, :] < post_lengths[:, None]
419
+ audio_outputs.pooler_output = audio_embeds[valid_mask.to(audio_embeds.device)]
420
+
421
+ return audio_outputs
422
+
423
+ def get_placeholder_mask(
424
+ self, input_ids: torch.LongTensor, inputs_embeds: torch.FloatTensor, audio_features: torch.FloatTensor
425
+ ):
426
+ """
427
+ Obtains multimodal placeholder mask from `input_ids` or `inputs_embeds`, and checks that the placeholder token count is
428
+ equal to the length of multimodal features. If the lengths are different, an error is raised.
429
+ """
430
+ if input_ids is None:
431
+ special_audio_mask = inputs_embeds == self.get_input_embeddings()(
432
+ torch.tensor(self.config.audio_token_id, dtype=torch.long, device=inputs_embeds.device)
433
+ )
434
+ special_audio_mask = special_audio_mask.all(-1)
435
+ else:
436
+ special_audio_mask = input_ids == self.config.audio_token_id
437
+
438
+ n_audio_tokens = special_audio_mask.sum()
439
+ n_audio_features = audio_features.shape[0]
440
+ special_audio_mask = special_audio_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
441
+ torch_compilable_check(
442
+ inputs_embeds[special_audio_mask].numel() == audio_features.numel(),
443
+ f"Audio features and audio tokens do not match, tokens: {n_audio_tokens}, features: {n_audio_features}",
444
+ )
445
+ return special_audio_mask
446
+
447
+ @can_return_tuple
448
+ @auto_docstring
449
+ def forward(
450
+ self,
451
+ input_ids: torch.LongTensor | None = None,
452
+ input_features: torch.FloatTensor | None = None,
453
+ input_features_mask: torch.Tensor | None = None,
454
+ attention_mask: torch.Tensor | None = None,
455
+ position_ids: torch.LongTensor | None = None,
456
+ past_key_values: Cache | None = None,
457
+ inputs_embeds: torch.FloatTensor | None = None,
458
+ labels: torch.LongTensor | None = None,
459
+ use_cache: bool | None = None,
460
+ logits_to_keep: int | torch.Tensor = 0,
461
+ **kwargs: Unpack[TransformersKwargs],
462
+ ) -> CausalLMOutputWithPast:
463
+ r"""
464
+ input_features_mask (`torch.Tensor` of shape `(batch_size, feature_sequence_length)`):
465
+ Mask to avoid performing attention on padding feature indices. Mask values selected in `[0, 1]`:
466
+
467
+ - 1 for tokens that are **not masked**,
468
+ - 0 for tokens that are **masked**.
469
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
470
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
471
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
472
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
473
+
474
+ Example:
475
+
476
+ ```python
477
+ >>> from transformers import GlmAsrForConditionalGeneration, AutoProcessor
478
+
479
+ >>> model_id = "zai-org/GLM-ASR-Nano-2512"
480
+ >>> processor = AutoProcessor.from_pretrained(model_id)
481
+ >>> model = GlmAsrForConditionalGeneration.from_pretrained(model_id, dtype="auto", device_map="auto")
482
+ >>> inputs = processor.apply_transcription_request("https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/bcn_weather.mp3")
483
+
484
+ >>> inputs = inputs.to(model.device, dtype=model.dtype)
485
+
486
+ >>> outputs = model.generate(**inputs, do_sample=False, max_new_tokens=500)
487
+
488
+ >>> decoded_outputs = processor.batch_decode(outputs[:, inputs.input_ids.shape[1] :], skip_special_tokens=True)
489
+ >>> print(decoded_outputs)
490
+ ```"""
491
+
492
+ if inputs_embeds is None:
493
+ inputs_embeds = self.get_input_embeddings()(input_ids)
494
+
495
+ if input_features is not None and input_ids is not None:
496
+ audio_embeds = self.get_audio_features(input_features, input_features_mask, return_dict=True).pooler_output
497
+
498
+ # replace text-audio token placeholders with audio embeddings
499
+ special_audio_mask = self.get_placeholder_mask(
500
+ input_ids, inputs_embeds=inputs_embeds, audio_features=audio_embeds
501
+ )
502
+ inputs_embeds = inputs_embeds.masked_scatter(special_audio_mask, audio_embeds.to(inputs_embeds.device))
503
+
504
+ outputs: CausalLMOutputWithPast = self.language_model(
505
+ inputs_embeds=inputs_embeds,
506
+ attention_mask=attention_mask,
507
+ position_ids=position_ids,
508
+ past_key_values=past_key_values,
509
+ labels=labels,
510
+ use_cache=use_cache,
511
+ logits_to_keep=logits_to_keep,
512
+ **kwargs,
513
+ )
514
+ return outputs
515
+
516
+ def prepare_inputs_for_generation(self, *args, is_first_iteration: bool = False, **kwargs):
517
+ input_features = kwargs.pop("input_features", None)
518
+ input_features_mask = kwargs.pop("input_features_mask", None)
519
+
520
+ model_inputs = super().prepare_inputs_for_generation(*args, **kwargs)
521
+
522
+ if is_first_iteration or not model_inputs.get("use_cache", False):
523
+ if input_features is not None:
524
+ model_inputs["input_features"] = input_features
525
+ if input_features_mask is not None:
526
+ model_inputs["input_features_mask"] = input_features_mask
527
+
528
+ return model_inputs
529
+
530
+
531
+ __all__ = ["GlmAsrEncoder", "GlmAsrForConditionalGeneration", "GlmAsrPreTrainedModel"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/glmasr/modular_glmasr.py ADDED
@@ -0,0 +1,445 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 the HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from collections.abc import Callable
16
+
17
+ import numpy as np
18
+
19
+ from ...activations import ACT2FN
20
+ from ...audio_utils import AudioInput, make_list_of_audio
21
+ from ...cache_utils import Cache
22
+ from ...feature_extraction_utils import BatchFeature
23
+ from ...modeling_layers import GradientCheckpointingLayer
24
+ from ...modeling_outputs import BaseModelOutputWithPooling, CausalLMOutputWithPast
25
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS
26
+ from ...processing_utils import Unpack
27
+ from ...utils import TransformersKwargs, auto_docstring, is_torch_available, logging
28
+ from ...utils.generic import can_return_tuple, merge_with_config_defaults
29
+ from ...utils.output_capturing import capture_outputs
30
+ from ..audioflamingo3.modeling_audioflamingo3 import (
31
+ AudioFlamingo3ForConditionalGeneration,
32
+ AudioFlamingo3MultiModalProjector,
33
+ AudioFlamingo3PreTrainedModel,
34
+ )
35
+ from ..audioflamingo3.processing_audioflamingo3 import AudioFlamingo3Processor, AudioFlamingo3ProcessorKwargs
36
+ from ..glm.modeling_glm import GlmRotaryEmbedding
37
+ from ..llama.modeling_llama import LlamaAttention, eager_attention_forward, rotate_half
38
+ from .configuration_glmasr import GlmAsrConfig, GlmAsrEncoderConfig
39
+
40
+
41
+ if is_torch_available():
42
+ import torch
43
+ from torch import nn
44
+
45
+
46
+ logger = logging.get_logger(__name__)
47
+
48
+
49
+ class GlmAsrProcessorKwargs(AudioFlamingo3ProcessorKwargs): ...
50
+
51
+
52
+ class GlmAsrProcessor(AudioFlamingo3Processor):
53
+ r"""
54
+ Constructs an GlmAsr processor which wraps an GlmAsr feature extractor and an GlmAsr
55
+ tokenizer into a single processor.
56
+
57
+ [`GlmAsrProcessor`] offers all the functionalities of [`WhisperFeatureExtractor`] and
58
+ [`Qwen2TokenizerFast`]. See the [`~GlmAsrProcessor.__call__`] for more information.
59
+
60
+ Args:
61
+ feature_extractor ([`WhisperFeatureExtractor`]):
62
+ The feature extractor is a required input.
63
+ tokenizer ([`Qwen2TokenizerFast`]):
64
+ The tokenizer is a required input.
65
+ chat_template (`Optional[str]`, *optional*):
66
+ The Jinja template to use for formatting the conversation. If not provided, the tokenizer's default chat
67
+ template will be used.
68
+ audio_token (`Optional[str]`, *optional*, defaults to `"<|pad|>`"):
69
+ Special token used to represent audio inputs in the chat template.
70
+ default_transcription_prompt (`str`, *optional*, defaults to `"Please transcribe this audio into text"`):
71
+ Default prompt to use for transcription tasks when applying transcription requests.
72
+ max_audio_len (`int`, *optional*, defaults to 655):
73
+ Maximum length of audio sequences in seconds. Audio longer than this will be truncated.
74
+ 655 gives approximately 8192 tokens, corresponding to the maximum sequence length of the text model.
75
+ """
76
+
77
+ def __init__(
78
+ self,
79
+ feature_extractor,
80
+ tokenizer,
81
+ chat_template=None,
82
+ audio_token="<|pad|>",
83
+ default_transcription_prompt="Please transcribe this audio into text",
84
+ max_audio_len=655,
85
+ ):
86
+ super().__init__(
87
+ feature_extractor,
88
+ tokenizer,
89
+ chat_template=chat_template,
90
+ audio_token=audio_token,
91
+ default_transcription_prompt=default_transcription_prompt,
92
+ max_audio_len=max_audio_len,
93
+ )
94
+
95
+ def _get_audio_token_length(self, audio_lengths: "torch.Tensor") -> "torch.Tensor":
96
+ merge_factor = 4
97
+ for padding, kernel_size, stride in [(1, 3, 1), (1, 3, 2)]:
98
+ audio_lengths = (audio_lengths + 2 * padding - (kernel_size - 1) - 1) // stride + 1
99
+
100
+ num_tokens = (audio_lengths - merge_factor) // merge_factor + 1
101
+ return num_tokens
102
+
103
+ def apply_transcription_request(
104
+ self,
105
+ audio: str | list[str] | AudioInput,
106
+ prompt: str | list[str] | None = None,
107
+ **kwargs: Unpack[GlmAsrProcessorKwargs],
108
+ ) -> BatchFeature:
109
+ """
110
+ Prepare inputs for automatic speech recognition without manually writing the default transcription prompt.
111
+
112
+ Args:
113
+ audio (`str`, `list[str]`, `np.ndarray`, `torch.Tensor`, `list[np.ndarray]`, `list[torch.Tensor]`):
114
+ Audio to transcribe. Strings are interpreted as local paths or URLs and will be loaded automatically by
115
+ the chat template loader; NumPy arrays and PyTorch tensors are forwarded directly.
116
+ prompt (`str` or `list[str]`, *optional*):
117
+ Custom prompt(s) to include in the user turn. A list must be the same length as the batch. When `None`,
118
+ each sample uses `"Transcribe the input speech."`.
119
+ **kwargs:
120
+ Additional keyword arguments forwarded to [`~GlmAsrProcessor.apply_chat_template`] (for example
121
+ `text_kwargs`, `audio_kwargs`, ...).
122
+
123
+ Returns:
124
+ [`BatchFeature`]: Processor outputs ready to be passed to [`GlmAsrForConditionalGeneration.generate`].
125
+
126
+ """
127
+
128
+ if isinstance(audio, str):
129
+ audio_items: list[str | np.ndarray] = [audio]
130
+ elif isinstance(audio, (list, tuple)) and audio and all(isinstance(el, str) for el in audio):
131
+ audio_items = list(audio)
132
+ else:
133
+ audio_items = list(make_list_of_audio(audio))
134
+ if is_torch_available():
135
+ audio_items = [el.detach().cpu().numpy() if isinstance(el, torch.Tensor) else el for el in audio_items]
136
+
137
+ batch_size = len(audio_items)
138
+ if batch_size == 0:
139
+ raise ValueError("`audio` must contain at least one sample.")
140
+
141
+ if prompt is None:
142
+ prompts = [self.default_transcription_prompt] * batch_size
143
+ elif isinstance(prompt, str):
144
+ prompts = [prompt] * batch_size
145
+ elif isinstance(prompt, (list, tuple)):
146
+ if len(prompt) != batch_size:
147
+ raise ValueError(
148
+ f"Received {len(prompt)} prompt(s) for {batch_size} audio sample(s); counts must match."
149
+ )
150
+ prompts = []
151
+ for item in prompt:
152
+ if item is None:
153
+ prompts.append(self.default_transcription_prompt)
154
+ elif isinstance(item, str):
155
+ prompts.append(item)
156
+ else:
157
+ raise TypeError("Each prompt must be a string or `None`.")
158
+ else:
159
+ raise TypeError("`prompt` must be a string, a sequence of strings, or `None`.")
160
+
161
+ conversations = [
162
+ [
163
+ {
164
+ "role": "user",
165
+ "content": [
166
+ {"type": "audio", "path": audio_item}
167
+ if isinstance(audio_item, str)
168
+ else {"type": "audio", "audio": audio_item},
169
+ {"type": "text", "text": prompt_text},
170
+ ],
171
+ }
172
+ ]
173
+ for prompt_text, audio_item in zip(prompts, audio_items)
174
+ ]
175
+
176
+ return self.apply_chat_template(
177
+ conversations,
178
+ tokenize=True,
179
+ add_generation_prompt=True,
180
+ return_dict=True,
181
+ **kwargs,
182
+ )
183
+
184
+
185
+ class GlmAsrRotaryEmbedding(GlmRotaryEmbedding): ...
186
+
187
+
188
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
189
+ cos = cos.unsqueeze(unsqueeze_dim)
190
+ sin = sin.unsqueeze(unsqueeze_dim)
191
+
192
+ rotary_dim = cos.shape[-1]
193
+ q_rot, q_pass = q[..., :rotary_dim], q[..., rotary_dim:]
194
+ k_rot, k_pass = k[..., :rotary_dim], k[..., rotary_dim:]
195
+
196
+ # Apply rotary embeddings on the first half or full tensor
197
+ q_embed = (q_rot * cos) + (rotate_half(q_rot) * sin)
198
+ k_embed = (k_rot * cos) + (rotate_half(k_rot) * sin)
199
+
200
+ # Concatenate back to full shape
201
+ q_embed = torch.cat([q_embed, q_pass], dim=-1)
202
+ k_embed = torch.cat([k_embed, k_pass], dim=-1)
203
+ return q_embed, k_embed
204
+
205
+
206
+ class GlmAsrAttention(LlamaAttention):
207
+ def __init__(self, config: GlmAsrConfig, layer_idx: int):
208
+ super().__init__(config, layer_idx)
209
+ self.is_causal = False
210
+ self.q_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=True)
211
+ self.k_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=False)
212
+ self.v_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=True)
213
+ self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=True)
214
+
215
+ def forward(
216
+ self,
217
+ hidden_states: torch.Tensor,
218
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
219
+ **kwargs: Unpack[TransformersKwargs],
220
+ ) -> tuple[torch.Tensor, torch.Tensor]:
221
+ input_shape = hidden_states.shape[:-1]
222
+ hidden_shape = (*input_shape, -1, self.head_dim)
223
+
224
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
225
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
226
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
227
+
228
+ cos, sin = position_embeddings
229
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
230
+
231
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
232
+ self.config._attn_implementation, eager_attention_forward
233
+ )
234
+
235
+ attn_output, attn_weights = attention_interface(
236
+ self,
237
+ query_states,
238
+ key_states,
239
+ value_states,
240
+ attention_mask=None,
241
+ dropout=0.0 if not self.training else self.attention_dropout,
242
+ scaling=self.scaling,
243
+ **kwargs,
244
+ )
245
+
246
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
247
+ attn_output = self.o_proj(attn_output)
248
+ return attn_output, attn_weights
249
+
250
+
251
+ class GlmAsrMLP(nn.Module):
252
+ def __init__(self, config):
253
+ super().__init__()
254
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
255
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
256
+ self.act_fn = ACT2FN[config.hidden_act]
257
+
258
+ def forward(self, hidden_states: torch.Tensor):
259
+ hidden_states = self.fc1(hidden_states)
260
+ hidden_states = self.act_fn(hidden_states)
261
+ hidden_states = self.fc2(hidden_states)
262
+ return hidden_states
263
+
264
+
265
+ class GlmAsrEncoderLayer(GradientCheckpointingLayer):
266
+ def __init__(self, config: GlmAsrConfig, layer_idx: int):
267
+ super().__init__()
268
+ self.hidden_size = config.hidden_size
269
+
270
+ self.self_attn = GlmAsrAttention(config=config, layer_idx=layer_idx)
271
+
272
+ self.mlp = GlmAsrMLP(config)
273
+ self.input_layernorm = nn.LayerNorm(config.hidden_size)
274
+ self.post_attention_layernorm = nn.LayerNorm(config.hidden_size)
275
+
276
+ def forward(
277
+ self,
278
+ hidden_states: torch.Tensor,
279
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
280
+ **kwargs: Unpack[TransformersKwargs],
281
+ ) -> torch.Tensor:
282
+ residual = hidden_states
283
+ hidden_states = self.input_layernorm(hidden_states)
284
+ # Self Attention
285
+ hidden_states, _ = self.self_attn(
286
+ hidden_states=hidden_states,
287
+ position_embeddings=position_embeddings,
288
+ **kwargs,
289
+ )
290
+ hidden_states = residual + hidden_states
291
+
292
+ # Fully Connected
293
+ residual = hidden_states
294
+ hidden_states = self.post_attention_layernorm(hidden_states)
295
+ hidden_states = self.mlp(hidden_states)
296
+ hidden_states = residual + hidden_states
297
+ return hidden_states
298
+
299
+
300
+ class GlmAsrPreTrainedModel(AudioFlamingo3PreTrainedModel): ...
301
+
302
+
303
+ # TODO: @eustlb, this is what WhisperEncoder should look like
304
+ class GlmAsrEncoder(GlmAsrPreTrainedModel):
305
+ config: GlmAsrEncoderConfig
306
+ main_input_name = "input_features"
307
+ input_modalities = "audio"
308
+ _no_split_modules = ["GlmAsrEncoderLayer"]
309
+ _can_record_outputs = {
310
+ "hidden_states": GlmAsrEncoderLayer,
311
+ "attentions": GlmAsrAttention,
312
+ }
313
+
314
+ def __init__(self, config: GlmAsrEncoderConfig):
315
+ super().__init__(config)
316
+ self.conv1 = nn.Conv1d(config.num_mel_bins, config.hidden_size, kernel_size=3, padding=1)
317
+ self.conv2 = nn.Conv1d(config.hidden_size, config.hidden_size, kernel_size=3, stride=2, padding=1)
318
+
319
+ self.layers = nn.ModuleList(
320
+ [GlmAsrEncoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
321
+ )
322
+ self.norm = nn.LayerNorm(config.hidden_size)
323
+ self.rotary_emb = GlmAsrRotaryEmbedding(config=config)
324
+ self.gradient_checkpointing = False
325
+ self.post_init()
326
+
327
+ @merge_with_config_defaults
328
+ @capture_outputs
329
+ @auto_docstring
330
+ def forward(self, input_features, **kwargs: Unpack[TransformersKwargs]):
331
+ inputs_embeds = nn.functional.gelu(self.conv1(input_features))
332
+ inputs_embeds = nn.functional.gelu(self.conv2(inputs_embeds))
333
+ inputs_embeds = inputs_embeds.transpose(1, 2)
334
+
335
+ hidden_states = inputs_embeds
336
+ position_embeddings = self.rotary_emb(
337
+ hidden_states, position_ids=torch.arange(hidden_states.shape[1], device=hidden_states.device)[None, :]
338
+ )
339
+
340
+ for encoder_layer in self.layers:
341
+ hidden_states = encoder_layer(hidden_states, position_embeddings=position_embeddings, **kwargs)
342
+
343
+ hidden_states = self.norm(hidden_states)
344
+ return BaseModelOutputWithPooling(last_hidden_state=hidden_states)
345
+
346
+
347
+ class GlmAsrMultiModalProjector(AudioFlamingo3MultiModalProjector):
348
+ def __init__(self, config: GlmAsrConfig):
349
+ super().__init__()
350
+ self.linear_1 = nn.Linear(config.audio_config.intermediate_size, config.text_config.hidden_size * 2)
351
+ self.linear_2 = nn.Linear(config.text_config.hidden_size * 2, config.text_config.hidden_size)
352
+
353
+
354
+ @auto_docstring(
355
+ custom_intro="""
356
+ The GlmAsr model which consists of a fine-tuned Whisper encoder, a multi-modal projector and a Llama language model.
357
+ """
358
+ )
359
+ class GlmAsrForConditionalGeneration(AudioFlamingo3ForConditionalGeneration):
360
+ _supports_attention_backend = True
361
+
362
+ @can_return_tuple
363
+ @auto_docstring(
364
+ custom_intro="Compute audio embeddings from log-mel input features using the audio encoder and multi-modal projector."
365
+ )
366
+ def get_audio_features(
367
+ self,
368
+ input_features: torch.FloatTensor,
369
+ input_features_mask: torch.Tensor,
370
+ **kwargs: Unpack[TransformersKwargs],
371
+ ) -> tuple | BaseModelOutputWithPooling:
372
+ audio_outputs = self.audio_tower(input_features, return_dict=True, **kwargs)
373
+ audio_hidden_states = audio_outputs.last_hidden_state
374
+ audio_hidden_states = audio_hidden_states.reshape(
375
+ input_features.shape[0], -1, self.config.audio_config.intermediate_size
376
+ )
377
+ audio_embeds = self.multi_modal_projector(audio_hidden_states)
378
+
379
+ audio_lengths = input_features_mask.sum(-1)
380
+ for padding, kernel_size, stride in [(1, 3, 1), (1, 3, 2)]:
381
+ audio_lengths = (audio_lengths + 2 * padding - (kernel_size - 1) - 1) // stride + 1
382
+ merge_factor = 4
383
+ post_lengths = (audio_lengths - merge_factor) // merge_factor + 1
384
+
385
+ valid_mask = torch.arange(audio_embeds.shape[1], device=post_lengths.device)[None, :] < post_lengths[:, None]
386
+ audio_outputs.pooler_output = audio_embeds[valid_mask.to(audio_embeds.device)]
387
+
388
+ return audio_outputs
389
+
390
+ def forward(
391
+ self,
392
+ input_ids: torch.LongTensor | None = None,
393
+ input_features: torch.FloatTensor | None = None,
394
+ input_features_mask: torch.Tensor | None = None,
395
+ attention_mask: torch.Tensor | None = None,
396
+ position_ids: torch.LongTensor | None = None,
397
+ past_key_values: Cache | None = None,
398
+ inputs_embeds: torch.FloatTensor | None = None,
399
+ labels: torch.LongTensor | None = None,
400
+ use_cache: bool | None = None,
401
+ logits_to_keep: int | torch.Tensor = 0,
402
+ **kwargs: Unpack[TransformersKwargs],
403
+ ) -> CausalLMOutputWithPast:
404
+ r"""
405
+ input_features_mask (`torch.Tensor` of shape `(batch_size, feature_sequence_length)`):
406
+ Mask to avoid performing attention on padding feature indices. Mask values selected in `[0, 1]`:
407
+
408
+ - 1 for tokens that are **not masked**,
409
+ - 0 for tokens that are **masked**.
410
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
411
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
412
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
413
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
414
+
415
+ Example:
416
+
417
+ ```python
418
+ >>> from transformers import GlmAsrForConditionalGeneration, AutoProcessor
419
+
420
+ >>> model_id = "zai-org/GLM-ASR-Nano-2512"
421
+ >>> processor = AutoProcessor.from_pretrained(model_id)
422
+ >>> model = GlmAsrForConditionalGeneration.from_pretrained(model_id, dtype="auto", device_map="auto")
423
+ >>> inputs = processor.apply_transcription_request("https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/bcn_weather.mp3")
424
+
425
+ >>> inputs = inputs.to(model.device, dtype=model.dtype)
426
+
427
+ >>> outputs = model.generate(**inputs, do_sample=False, max_new_tokens=500)
428
+
429
+ >>> decoded_outputs = processor.batch_decode(outputs[:, inputs.input_ids.shape[1] :], skip_special_tokens=True)
430
+ >>> print(decoded_outputs)
431
+ ```"""
432
+ return super().forward(
433
+ input_ids=input_ids,
434
+ attention_mask=attention_mask,
435
+ position_ids=position_ids,
436
+ past_key_values=past_key_values,
437
+ inputs_embeds=inputs_embeds,
438
+ labels=labels,
439
+ use_cache=use_cache,
440
+ logits_to_keep=logits_to_keep,
441
+ **kwargs,
442
+ )
443
+
444
+
445
+ __all__ = ["GlmAsrEncoder", "GlmAsrForConditionalGeneration", "GlmAsrProcessor", "GlmAsrPreTrainedModel"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/hrm_text/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 The Sapient AI Authors 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_hrm_text import *
22
+ from .modeling_hrm_text 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/hrm_text/modeling_hrm_text.py ADDED
@@ -0,0 +1,644 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/hrm_text/modular_hrm_text.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_hrm_text.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # Copyright 2026 The Sapient AI Authors 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 contextlib import nullcontext
23
+ from typing import Optional
24
+
25
+ import torch
26
+ from torch import nn
27
+
28
+ from ... import initialization as init
29
+ from ...activations import ACT2FN
30
+ from ...cache_utils import Cache, DynamicCache
31
+ from ...configuration_utils import PreTrainedConfig
32
+ from ...generation import GenerationMixin
33
+ from ...integrations import use_kernel_func_from_hub, use_kernelized_func
34
+ from ...masking_utils import create_causal_mask, create_masks_for_generate
35
+ from ...modeling_layers import GradientCheckpointingLayer
36
+ from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
37
+ from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
38
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
39
+ from ...processing_utils import Unpack
40
+ from ...utils import auto_docstring, can_return_tuple, logging
41
+ from ...utils.generic import (
42
+ TransformersKwargs,
43
+ is_flash_attention_requested,
44
+ maybe_autocast,
45
+ merge_with_config_defaults,
46
+ split_attention_implementation,
47
+ )
48
+ from ...utils.output_capturing import capture_outputs
49
+ from .configuration_hrm_text import HrmTextConfig
50
+
51
+
52
+ logger = logging.get_logger(__name__)
53
+
54
+
55
+ class HrmTextRMSNorm(torch.nn.Module):
56
+ def __init__(self, eps: float = 1e-6):
57
+ super().__init__()
58
+ self.eps = eps
59
+
60
+ def _norm(self, x):
61
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
62
+
63
+ def forward(self, x):
64
+ return self._norm(x.float()).type_as(x)
65
+
66
+ def extra_repr(self):
67
+ return f"eps={self.eps}"
68
+
69
+
70
+ class HrmTextMLP(nn.Module):
71
+ def __init__(self, config):
72
+ super().__init__()
73
+ self.config = config
74
+ self.hidden_size = config.hidden_size
75
+ self.intermediate_size = config.intermediate_size
76
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
77
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
78
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
79
+ self.act_fn = ACT2FN[config.hidden_act]
80
+
81
+ def forward(self, x):
82
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
83
+ return down_proj
84
+
85
+
86
+ def rotate_half(x):
87
+ """Rotates half the hidden dims of the input."""
88
+ x1 = x[..., : x.shape[-1] // 2]
89
+ x2 = x[..., x.shape[-1] // 2 :]
90
+ return torch.cat((-x2, x1), dim=-1)
91
+
92
+
93
+ @use_kernel_func_from_hub("rotary_pos_emb")
94
+ def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
95
+ """Applies Rotary Position Embedding to the query and key tensors.
96
+
97
+ Args:
98
+ q (`torch.Tensor`): The query tensor.
99
+ k (`torch.Tensor`): The key tensor.
100
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
101
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
102
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
103
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
104
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
105
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
106
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
107
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
108
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
109
+ Returns:
110
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
111
+ """
112
+ cos = cos.unsqueeze(unsqueeze_dim)
113
+ sin = sin.unsqueeze(unsqueeze_dim)
114
+ q_embed = (q * cos) + (rotate_half(q) * sin)
115
+ k_embed = (k * cos) + (rotate_half(k) * sin)
116
+ return q_embed, k_embed
117
+
118
+
119
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
120
+ """
121
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
122
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
123
+ """
124
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
125
+ if n_rep == 1:
126
+ return hidden_states
127
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
128
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
129
+
130
+
131
+ def eager_attention_forward(
132
+ module: nn.Module,
133
+ query: torch.Tensor,
134
+ key: torch.Tensor,
135
+ value: torch.Tensor,
136
+ attention_mask: torch.Tensor | None,
137
+ scaling: float,
138
+ dropout: float = 0.0,
139
+ **kwargs: Unpack[TransformersKwargs],
140
+ ):
141
+ key_states = repeat_kv(key, module.num_key_value_groups)
142
+ value_states = repeat_kv(value, module.num_key_value_groups)
143
+
144
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
145
+ if attention_mask is not None:
146
+ attn_weights = attn_weights + attention_mask
147
+
148
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
149
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
150
+ attn_output = torch.matmul(attn_weights, value_states)
151
+ attn_output = attn_output.transpose(1, 2).contiguous()
152
+
153
+ return attn_output, attn_weights
154
+
155
+
156
+ @use_kernelized_func(apply_rotary_pos_emb)
157
+ class HrmTextAttention(nn.Module):
158
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
159
+
160
+ def __init__(self, config: HrmTextConfig, layer_idx: int):
161
+ super().__init__()
162
+ self.config = config
163
+ self.layer_idx = layer_idx
164
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
165
+ self.num_key_value_groups = 1 # Uses MHA instead of GQA
166
+ self.scaling = self.head_dim**-0.5
167
+ self.attention_dropout = config.attention_dropout
168
+ self.is_causal = True
169
+
170
+ self.q_proj = nn.Linear(
171
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
172
+ )
173
+ self.k_proj = nn.Linear(
174
+ config.hidden_size,
175
+ config.num_attention_heads * self.head_dim,
176
+ bias=config.attention_bias,
177
+ )
178
+ self.v_proj = nn.Linear(
179
+ config.hidden_size,
180
+ config.num_attention_heads * self.head_dim,
181
+ bias=config.attention_bias,
182
+ )
183
+ self.o_proj = nn.Linear(
184
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
185
+ )
186
+ # Additional sigmoid gate applied at the end
187
+ self.gate_proj = nn.Linear(
188
+ config.hidden_size,
189
+ config.num_attention_heads * self.head_dim,
190
+ bias=config.attention_bias,
191
+ )
192
+
193
+ def forward(
194
+ self,
195
+ hidden_states: torch.Tensor,
196
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
197
+ attention_mask: torch.Tensor | None = None,
198
+ past_key_values: Cache | None = None,
199
+ cycle_offset: int = 0,
200
+ **kwargs: Unpack[TransformersKwargs],
201
+ ) -> tuple[torch.Tensor, torch.Tensor]:
202
+ input_shape = hidden_states.shape[:-1]
203
+ hidden_shape = (*input_shape, -1, self.head_dim)
204
+
205
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
206
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
207
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
208
+ gate_states = self.gate_proj(hidden_states).view(hidden_shape)
209
+
210
+ cos, sin = position_embeddings
211
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
212
+
213
+ if past_key_values is not None:
214
+ # Adjust cache slot by `cycle_offset` which is determined by it's current recurrent step through the stacks
215
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx + cycle_offset)
216
+
217
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
218
+ self.config._attn_implementation, eager_attention_forward
219
+ )
220
+ attn_output, attn_weights = attention_interface(
221
+ self,
222
+ query_states,
223
+ key_states,
224
+ value_states,
225
+ attention_mask,
226
+ dropout=0.0 if not self.training else self.attention_dropout,
227
+ scaling=self.scaling,
228
+ **kwargs,
229
+ )
230
+
231
+ # Additional sigmoid gating (similar to Qwen3Next)
232
+ attn_output = torch.sigmoid(gate_states) * attn_output
233
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
234
+ attn_output = self.o_proj(attn_output)
235
+ return attn_output, attn_weights
236
+
237
+
238
+ class HrmTextDecoderLayer(GradientCheckpointingLayer):
239
+ def __init__(self, config: HrmTextConfig, layer_idx: int):
240
+ super().__init__()
241
+ self.hidden_size = config.hidden_size
242
+
243
+ self.self_attn = HrmTextAttention(config=config, layer_idx=layer_idx)
244
+
245
+ self.mlp = HrmTextMLP(config)
246
+ self.input_layernorm = HrmTextRMSNorm(eps=config.rms_norm_eps)
247
+ self.post_attention_layernorm = HrmTextRMSNorm(eps=config.rms_norm_eps)
248
+
249
+ def forward(
250
+ self,
251
+ hidden_states: torch.Tensor,
252
+ attention_mask: torch.Tensor | None = None,
253
+ position_ids: torch.LongTensor | None = None,
254
+ past_key_values: Cache | None = None,
255
+ use_cache: bool | None = False,
256
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
257
+ **kwargs: Unpack[TransformersKwargs],
258
+ ) -> torch.Tensor:
259
+ residual = hidden_states
260
+ hidden_states = self.input_layernorm(hidden_states)
261
+ # Self Attention
262
+ hidden_states, _ = self.self_attn(
263
+ hidden_states=hidden_states,
264
+ attention_mask=attention_mask,
265
+ position_ids=position_ids,
266
+ past_key_values=past_key_values,
267
+ use_cache=use_cache,
268
+ position_embeddings=position_embeddings,
269
+ **kwargs,
270
+ )
271
+ hidden_states = residual + hidden_states
272
+
273
+ # Fully Connected
274
+ residual = hidden_states
275
+ hidden_states = self.post_attention_layernorm(hidden_states)
276
+ hidden_states = self.mlp(hidden_states)
277
+ hidden_states = residual + hidden_states
278
+ return hidden_states
279
+
280
+
281
+ class HrmTextStack(nn.Module):
282
+ """A single transformer stack — used twice inside, once as H module and once as L module"""
283
+
284
+ def __init__(self, config: HrmTextConfig):
285
+ super().__init__()
286
+ self.layers = nn.ModuleList(
287
+ [HrmTextDecoderLayer(config, layer_idx) for layer_idx in range(config.num_layers_per_stack)]
288
+ )
289
+ self.final_norm = HrmTextRMSNorm(eps=config.rms_norm_eps)
290
+
291
+ def forward(
292
+ self,
293
+ hidden_states: torch.Tensor,
294
+ attention_mask: torch.Tensor | None = None,
295
+ past_key_values: Cache | None = None,
296
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
297
+ cycle_offset: int = 0,
298
+ **kwargs: Unpack[TransformersKwargs],
299
+ ) -> torch.Tensor:
300
+ for layer in self.layers:
301
+ hidden_states = layer(
302
+ hidden_states,
303
+ attention_mask=attention_mask,
304
+ past_key_values=past_key_values,
305
+ position_embeddings=position_embeddings,
306
+ cycle_offset=cycle_offset,
307
+ **kwargs,
308
+ )
309
+ return self.final_norm(hidden_states)
310
+
311
+
312
+ @auto_docstring
313
+ class HrmTextPreTrainedModel(PreTrainedModel):
314
+ config: HrmTextConfig
315
+ base_model_prefix = "model"
316
+ supports_gradient_checkpointing = True
317
+ _no_split_modules = ["HrmTextDecoderLayer"]
318
+ _skip_keys_device_placement = ["past_key_values"]
319
+ _supports_flash_attn = True
320
+ _supports_sdpa = True
321
+ _supports_flex_attn = True
322
+
323
+ _can_compile_fullgraph = True
324
+ _supports_attention_backend = True
325
+ _can_record_outputs = {
326
+ "hidden_states": HrmTextDecoderLayer,
327
+ "attentions": HrmTextAttention,
328
+ }
329
+
330
+ def _check_and_adjust_attn_implementation(
331
+ self, attn_implementation: str | None, is_init_check: bool = False, allow_all_kernels: bool = False
332
+ ) -> str:
333
+ if attn_implementation is not None and self.config.prefix_lm:
334
+ _, base_implementation = split_attention_implementation(attn_implementation)
335
+ if is_flash_attention_requested(requested_attention_implementation=base_implementation):
336
+ raise ValueError(
337
+ f"`attn_implementation={attn_implementation!r}` is not supported when "
338
+ "`config.prefix_lm=True`: FlashAttention cannot represent the PrefixLM 4-D mask "
339
+ "overlay. Use `'sdpa'` (default) or `'flex_attention'`, or set `config.prefix_lm=False`."
340
+ )
341
+ return super()._check_and_adjust_attn_implementation(attn_implementation, is_init_check, allow_all_kernels)
342
+
343
+ @torch.no_grad()
344
+ def _init_weights(self, module):
345
+ super()._init_weights(module)
346
+ if isinstance(module, HrmTextModel):
347
+ init.zeros_(module.z_L_init)
348
+ # `z_L_init` is the frozen low-cycle initial state and never trains.
349
+ module.z_L_init.requires_grad_(False) # trf-ignore: TRF012
350
+
351
+
352
+ class HrmTextRotaryEmbedding(nn.Module):
353
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
354
+
355
+ def __init__(self, config: HrmTextConfig, device=None):
356
+ super().__init__()
357
+ self.max_seq_len_cached = config.max_position_embeddings
358
+ self.original_max_seq_len = config.max_position_embeddings
359
+
360
+ self.config = config
361
+
362
+ self.rope_type = self.config.rope_parameters["rope_type"]
363
+ rope_init_fn: Callable = self.compute_default_rope_parameters
364
+ if self.rope_type != "default":
365
+ rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
366
+ inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
367
+
368
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
369
+ self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
370
+
371
+ @staticmethod
372
+ def compute_default_rope_parameters(
373
+ config: HrmTextConfig | None = None,
374
+ device: Optional["torch.device"] = None,
375
+ seq_len: int | None = None,
376
+ ) -> tuple["torch.Tensor", float]:
377
+ """
378
+ Computes the inverse frequencies according to the original RoPE implementation
379
+ Args:
380
+ config ([`~transformers.PreTrainedConfig`]):
381
+ The model configuration.
382
+ device (`torch.device`):
383
+ The device to use for initialization of the inverse frequencies.
384
+ seq_len (`int`, *optional*):
385
+ The current sequence length. Unused for this type of RoPE.
386
+ Returns:
387
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
388
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
389
+ """
390
+ base = config.rope_parameters["rope_theta"]
391
+ dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
392
+
393
+ attention_factor = 1.0 # Unused in this type of RoPE
394
+
395
+ # Compute the inverse frequencies
396
+ inv_freq = 1.0 / (
397
+ base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
398
+ )
399
+ return inv_freq, attention_factor
400
+
401
+ @torch.no_grad()
402
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
403
+ def forward(self, x, position_ids):
404
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
405
+ position_ids_expanded = position_ids[:, None, :].float()
406
+
407
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
408
+ with maybe_autocast(device_type=device_type, enabled=False): # Force float32
409
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
410
+ emb = torch.cat((freqs, freqs), dim=-1)
411
+ cos = emb.cos() * self.attention_scaling
412
+ sin = emb.sin() * self.attention_scaling
413
+
414
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
415
+
416
+
417
+ @auto_docstring
418
+ class HrmTextModel(HrmTextPreTrainedModel):
419
+ def __init__(self, config: HrmTextConfig):
420
+ super().__init__(config)
421
+ self.padding_idx = config.pad_token_id
422
+ self.vocab_size = config.vocab_size
423
+
424
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
425
+ self.rotary_emb = HrmTextRotaryEmbedding(config=config)
426
+ self.gradient_checkpointing = False
427
+
428
+ self.embedding_scale = config.embedding_scale
429
+
430
+ # Recursive module structures
431
+ self.L_module = HrmTextStack(config)
432
+ self.H_module = HrmTextStack(config)
433
+ # Initial state for the low cycle module
434
+ self.z_L_init = nn.Parameter(torch.zeros(config.hidden_size), requires_grad=False)
435
+
436
+ raw_bp = list(config.L_bp_cycles)
437
+ self.L_bp_cycles_padded = [1] * max(0, config.H_cycles - len(raw_bp)) + raw_bp
438
+
439
+ # Initialize weights and apply final processing
440
+ self.post_init()
441
+
442
+ @merge_with_config_defaults
443
+ @capture_outputs
444
+ @auto_docstring
445
+ def forward(
446
+ self,
447
+ input_ids: torch.LongTensor | None = None,
448
+ attention_mask: torch.Tensor | None = None,
449
+ position_ids: torch.LongTensor | None = None,
450
+ past_key_values: Cache | None = None,
451
+ token_type_ids: torch.LongTensor | None = None,
452
+ inputs_embeds: torch.FloatTensor | None = None,
453
+ use_cache: bool | None = None,
454
+ **kwargs: Unpack[TransformersKwargs],
455
+ ) -> BaseModelOutputWithPast:
456
+ r"""
457
+ token_type_ids (`torch.LongTensor` of shape `(batch, seq_len)`, *optional*):
458
+ Per-position bidirectional/causal indicator. Tokens with `token_type_ids == 1`
459
+ form a single bidirectional block; all other positions are causal.
460
+ """
461
+ if (input_ids is None) ^ (inputs_embeds is not None):
462
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
463
+
464
+ if inputs_embeds is None:
465
+ inputs_embeds = self.embed_tokens(input_ids)
466
+ # Additional scaling on the input embeds
467
+ inputs_embeds = inputs_embeds * self.embedding_scale
468
+
469
+ if use_cache and past_key_values is None:
470
+ past_key_values = DynamicCache(config=self.config)
471
+
472
+ if position_ids is None:
473
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
474
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
475
+ position_ids = position_ids.unsqueeze(0)
476
+
477
+ # Create mask with optional prefix-based bidirectionality
478
+ mask_kwargs = {
479
+ "config": self.config,
480
+ "inputs_embeds": inputs_embeds,
481
+ "attention_mask": attention_mask,
482
+ "past_key_values": past_key_values,
483
+ "position_ids": position_ids,
484
+ }
485
+ is_first_iteration = past_key_values is None or not past_key_values.is_initialized
486
+ if token_type_ids is not None and is_first_iteration:
487
+ if self.config.prefix_lm:
488
+ mask_kwargs["block_sequence_ids"] = torch.where(token_type_ids == 1, 0, -1)
489
+ else:
490
+ logger.warning_once("`token_type_ids` was provided but `config.prefix_lm=False`; ignoring it.")
491
+
492
+ attention_mask = create_causal_mask(**mask_kwargs)
493
+ position_embeddings = self.rotary_emb(inputs_embeds, position_ids)
494
+
495
+ # Hierarchical (H/L)-cycle recurrence
496
+ #
497
+ # `z_H` - slow / high-level state
498
+ hidden_states_high_cycle = inputs_embeds
499
+ # `z_L` - fast / low-level state
500
+ hidden_states_low_cycle = (
501
+ self.z_L_init.to(dtype=hidden_states_high_cycle.dtype, device=hidden_states_high_cycle.device)
502
+ .expand_as(hidden_states_high_cycle)
503
+ .contiguous()
504
+ )
505
+
506
+ # Cache-slot layout under the recurrent forward:
507
+ #
508
+ # slot(h, l, layer) = (h * (L_cycles + 1) + l) * num_layers_per_stack + layer
509
+ # ^— L-stack invocation at (h, l)
510
+ # slot(h, H, layer) = (h * (L_cycles + 1) + L_cycles) * num_layers_per_stack + layer
511
+ # ^— trailing H-stack invocation
512
+ #
513
+ # That totals `num_layers_per_stack * H_cycles * (L_cycles + 1)` slots, i.e. the `config.num_hidden_layers`.
514
+ num_layers_per_stack = self.config.num_layers_per_stack
515
+ for high_cycle_idx in range(self.config.H_cycles):
516
+ # `L_bp_cycles` k-step grad trick: only the trailing `num_grad_iterations` of the
517
+ # `L_cycles` inner iterations propagate gradients; earlier iterations run under
518
+ # `torch.no_grad()` to bound activation memory.
519
+ num_grad_iterations = (
520
+ self.L_bp_cycles_padded[high_cycle_idx] if high_cycle_idx < len(self.L_bp_cycles_padded) else 1
521
+ )
522
+ grad_threshold = self.config.L_cycles - num_grad_iterations
523
+ for low_cycle_idx in range(self.config.L_cycles):
524
+ cycle_offset = (high_cycle_idx * (self.config.L_cycles + 1) + low_cycle_idx) * num_layers_per_stack
525
+ ctx = nullcontext() if low_cycle_idx >= grad_threshold else torch.no_grad()
526
+ with ctx:
527
+ hidden_states_low_cycle = self.L_module(
528
+ hidden_states_low_cycle.to(hidden_states_high_cycle.device) + hidden_states_high_cycle,
529
+ attention_mask=attention_mask,
530
+ past_key_values=past_key_values,
531
+ position_embeddings=position_embeddings,
532
+ position_ids=position_ids,
533
+ cycle_offset=cycle_offset,
534
+ **kwargs,
535
+ )
536
+
537
+ cycle_offset = (high_cycle_idx * (self.config.L_cycles + 1) + self.config.L_cycles) * num_layers_per_stack
538
+
539
+ hidden_states_high_cycle = self.H_module(
540
+ hidden_states_high_cycle + hidden_states_low_cycle.to(hidden_states_high_cycle.device),
541
+ attention_mask=attention_mask,
542
+ past_key_values=past_key_values,
543
+ position_embeddings=position_embeddings,
544
+ position_ids=position_ids,
545
+ cycle_offset=cycle_offset,
546
+ **kwargs,
547
+ )
548
+
549
+ return BaseModelOutputWithPast(
550
+ last_hidden_state=hidden_states_high_cycle,
551
+ past_key_values=past_key_values,
552
+ )
553
+
554
+
555
+ @auto_docstring
556
+ class HrmTextForCausalLM(HrmTextPreTrainedModel, GenerationMixin):
557
+ _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
558
+ _tp_plan = {"lm_head": "colwise_gather_output"}
559
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
560
+
561
+ def __init__(self, config):
562
+ super().__init__(config)
563
+ self.model = HrmTextModel(config)
564
+ self.vocab_size = config.vocab_size
565
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
566
+
567
+ # Initialize weights and apply final processing
568
+ self.post_init()
569
+
570
+ @can_return_tuple
571
+ @auto_docstring
572
+ def forward(
573
+ self,
574
+ input_ids: torch.LongTensor | None = None,
575
+ attention_mask: torch.Tensor | None = None,
576
+ position_ids: torch.LongTensor | None = None,
577
+ past_key_values: Cache | None = None,
578
+ token_type_ids: torch.LongTensor | None = None,
579
+ inputs_embeds: torch.FloatTensor | None = None,
580
+ labels: torch.LongTensor | None = None,
581
+ use_cache: bool | None = None,
582
+ logits_to_keep: int | torch.Tensor = 0,
583
+ **kwargs: Unpack[TransformersKwargs],
584
+ ) -> CausalLMOutputWithPast:
585
+ r"""
586
+ token_type_ids (`torch.LongTensor` of shape `(batch, seq_len)`, *optional*):
587
+ Per-position bidirectional/causal indicator. Tokens with `token_type_ids == 1`
588
+ form a single bidirectional block; all other positions are causal.
589
+ """
590
+ outputs: BaseModelOutputWithPast = self.model(
591
+ input_ids=input_ids,
592
+ attention_mask=attention_mask,
593
+ position_ids=position_ids,
594
+ past_key_values=past_key_values,
595
+ token_type_ids=token_type_ids,
596
+ inputs_embeds=inputs_embeds,
597
+ use_cache=use_cache,
598
+ **kwargs,
599
+ )
600
+
601
+ hidden_states = outputs.last_hidden_state
602
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
603
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
604
+
605
+ loss = None
606
+ if labels is not None:
607
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
608
+
609
+ return CausalLMOutputWithPast(
610
+ loss=loss,
611
+ logits=logits,
612
+ past_key_values=outputs.past_key_values,
613
+ hidden_states=outputs.hidden_states,
614
+ attentions=outputs.attentions,
615
+ )
616
+
617
+ @staticmethod
618
+ def create_masks_for_generate(
619
+ config: PreTrainedConfig,
620
+ inputs_embeds: torch.Tensor,
621
+ attention_mask: torch.Tensor | None,
622
+ past_key_values: Cache | None,
623
+ position_ids: torch.Tensor | None,
624
+ token_type_ids: torch.Tensor | None = None,
625
+ is_first_iteration: bool | None = False,
626
+ **kwargs,
627
+ ) -> dict:
628
+ mask_kwargs = {
629
+ "config": config,
630
+ "inputs_embeds": inputs_embeds,
631
+ "attention_mask": attention_mask,
632
+ "past_key_values": past_key_values,
633
+ "position_ids": position_ids,
634
+ }
635
+ if token_type_ids is not None and is_first_iteration:
636
+ if config.prefix_lm:
637
+ mask_kwargs["block_sequence_ids"] = torch.where(token_type_ids == 1, 0, -1)
638
+ else:
639
+ logger.warning_once("`token_type_ids` was provided but `config.prefix_lm=False`; ignoring it.")
640
+
641
+ return create_masks_for_generate(**mask_kwargs)
642
+
643
+
644
+ __all__ = ["HrmTextForCausalLM", "HrmTextModel", "HrmTextPreTrainedModel"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/led/__init__.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from ..roberta.tokenization_roberta import RobertaTokenizer as LEDTokenizer
22
+ from .configuration_led import *
23
+ from .modeling_led import *
24
+ else:
25
+ import sys
26
+
27
+ _file = globals()["__file__"]
28
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/led/configuration_led.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 Iz Beltagy, Matthew E. Peters, Arman Cohan 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
+ """LED model configuration"""
15
+
16
+ from huggingface_hub.dataclasses import strict
17
+
18
+ from ...configuration_utils import PreTrainedConfig
19
+ from ...utils import auto_docstring
20
+
21
+
22
+ @auto_docstring(checkpoint="allenai/led-base-16384")
23
+ @strict
24
+ class LEDConfig(PreTrainedConfig):
25
+ r"""
26
+ max_encoder_position_embeddings (`int`, *optional*, defaults to 16384):
27
+ The maximum sequence length that the encoder might ever be used with.
28
+ max_decoder_position_embeddings (`int`, *optional*, defaults to 16384):
29
+ The maximum sequence length that the decoder might ever be used with.
30
+ attention_window (`int` or `list[int]`, *optional*, defaults to 512):
31
+ Size of an attention window around each token. If an `int`, use the same size for all layers. To specify a
32
+ different window size for each layer, use a `list[int]` where `len(attention_window) == num_hidden_layers`.
33
+
34
+ Example:
35
+
36
+ ```python
37
+ >>> from transformers import LEDModel, LEDConfig
38
+
39
+ >>> # Initializing a LED allenai/led-base-16384 style configuration
40
+ >>> configuration = LEDConfig()
41
+
42
+ >>> # Initializing a model from the allenai/led-base-16384 style configuration
43
+ >>> model = LEDModel(configuration)
44
+
45
+ >>> # Accessing the model configuration
46
+ >>> configuration = model.config
47
+ ```"""
48
+
49
+ model_type = "led"
50
+ attribute_map = {
51
+ "num_attention_heads": "encoder_attention_heads",
52
+ "hidden_size": "d_model",
53
+ "attention_probs_dropout_prob": "attention_dropout",
54
+ "initializer_range": "init_std",
55
+ "num_hidden_layers": "encoder_layers",
56
+ }
57
+
58
+ vocab_size: int = 50265
59
+ max_encoder_position_embeddings: int = 16384
60
+ max_decoder_position_embeddings: int = 1024
61
+ encoder_layers: int = 12
62
+ encoder_ffn_dim: int = 4096
63
+ encoder_attention_heads: int = 16
64
+ decoder_layers: int = 12
65
+ decoder_ffn_dim: int = 4096
66
+ decoder_attention_heads: int = 16
67
+ encoder_layerdrop: float | int = 0.0
68
+ decoder_layerdrop: float | int = 0.0
69
+ use_cache: bool = True
70
+ is_encoder_decoder: bool = True
71
+ activation_function: str = "gelu"
72
+ d_model: int = 1024
73
+ dropout: float | int = 0.1
74
+ attention_dropout: float | int = 0.0
75
+ activation_dropout: float | int = 0.0
76
+ init_std: float = 0.02
77
+ decoder_start_token_id: int = 2
78
+ classifier_dropout: float | int = 0.0
79
+ pad_token_id: int | None = 1
80
+ bos_token_id: int | None = 0
81
+ eos_token_id: int | list[int] | None = 2
82
+ attention_window: list[int] | int = 512
83
+ tie_word_embeddings: bool = True
84
+
85
+
86
+ __all__ = ["LEDConfig"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/led/modeling_led.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/mistral/modular_mistral.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Callable
2
+
3
+ import torch
4
+ from torch import nn
5
+
6
+ from ...cache_utils import Cache, DynamicCache
7
+ from ...masking_utils import create_causal_mask, create_sliding_window_causal_mask
8
+ from ...modeling_flash_attention_utils import FlashAttentionKwargs
9
+ from ...modeling_layers import (
10
+ GenericForQuestionAnswering,
11
+ )
12
+ from ...modeling_outputs import BaseModelOutputWithPast
13
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS
14
+ from ...processing_utils import Unpack
15
+ from ...utils import TransformersKwargs, auto_docstring, logging
16
+ from ...utils.generic import merge_with_config_defaults
17
+ from ...utils.output_capturing import capture_outputs
18
+ from ..llama.modeling_llama import (
19
+ LlamaAttention,
20
+ LlamaDecoderLayer,
21
+ LlamaForCausalLM,
22
+ LlamaForSequenceClassification,
23
+ LlamaForTokenClassification,
24
+ LlamaMLP,
25
+ LlamaModel,
26
+ LlamaPreTrainedModel,
27
+ apply_rotary_pos_emb,
28
+ eager_attention_forward,
29
+ )
30
+ from .configuration_mistral import MistralConfig
31
+
32
+
33
+ logger = logging.get_logger(__name__)
34
+
35
+
36
+ class MistralMLP(LlamaMLP):
37
+ def __init__(self, config):
38
+ super().__init__(config)
39
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
40
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
41
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
42
+
43
+
44
+ class MistralAttention(LlamaAttention):
45
+ def __init__(self, config: MistralConfig, layer_idx: int):
46
+ super().__init__(config, layer_idx)
47
+ self.head_dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
48
+ self.q_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=False)
49
+ self.k_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=False)
50
+ self.v_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=False)
51
+ self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
52
+
53
+ def forward(
54
+ self,
55
+ hidden_states: torch.Tensor,
56
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
57
+ attention_mask: torch.Tensor | None,
58
+ past_key_values: Cache | None = None,
59
+ **kwargs: Unpack[FlashAttentionKwargs],
60
+ ) -> tuple[torch.Tensor, torch.Tensor | None]:
61
+ input_shape = hidden_states.shape[:-1]
62
+ hidden_shape = (*input_shape, -1, self.head_dim)
63
+
64
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
65
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
66
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
67
+
68
+ cos, sin = position_embeddings
69
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
70
+
71
+ if past_key_values is not None:
72
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
73
+
74
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
75
+ self.config._attn_implementation, eager_attention_forward
76
+ )
77
+
78
+ attn_output, attn_weights = attention_interface(
79
+ self,
80
+ query_states,
81
+ key_states,
82
+ value_states,
83
+ attention_mask,
84
+ dropout=0.0 if not self.training else self.attention_dropout,
85
+ scaling=self.scaling,
86
+ sliding_window=getattr(self.config, "sliding_window", None), # main diff with Llama
87
+ **kwargs,
88
+ )
89
+
90
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
91
+ attn_output = self.o_proj(attn_output)
92
+ return attn_output, attn_weights
93
+
94
+
95
+ class MistralDecoderLayer(LlamaDecoderLayer):
96
+ def __init__(self, config: MistralConfig, layer_idx: int):
97
+ super().__init__(config, layer_idx)
98
+ self.self_attn = MistralAttention(config=config, layer_idx=layer_idx)
99
+ self.mlp = MistralMLP(config)
100
+
101
+
102
+ class MistralPreTrainedModel(LlamaPreTrainedModel):
103
+ _can_record_outputs = {
104
+ "hidden_states": MistralDecoderLayer,
105
+ "attentions": MistralAttention,
106
+ }
107
+
108
+
109
+ class MistralModel(LlamaModel):
110
+ @merge_with_config_defaults
111
+ @capture_outputs
112
+ @auto_docstring
113
+ def forward(
114
+ self,
115
+ input_ids: torch.LongTensor | None = None,
116
+ attention_mask: torch.Tensor | None = None,
117
+ position_ids: torch.LongTensor | None = None,
118
+ past_key_values: Cache | None = None,
119
+ inputs_embeds: torch.FloatTensor | None = None,
120
+ use_cache: bool | None = None,
121
+ **kwargs: Unpack[TransformersKwargs],
122
+ ) -> BaseModelOutputWithPast:
123
+ if (input_ids is None) ^ (inputs_embeds is not None):
124
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
125
+
126
+ if inputs_embeds is None:
127
+ inputs_embeds = self.embed_tokens(input_ids)
128
+
129
+ if use_cache and past_key_values is None:
130
+ past_key_values = DynamicCache(config=self.config)
131
+
132
+ if position_ids is None:
133
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
134
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
135
+ position_ids = position_ids.unsqueeze(0)
136
+
137
+ mask_function = create_causal_mask if self.config.sliding_window is None else create_sliding_window_causal_mask
138
+ causal_mask = mask_function(
139
+ config=self.config,
140
+ inputs_embeds=inputs_embeds,
141
+ attention_mask=attention_mask,
142
+ past_key_values=past_key_values,
143
+ position_ids=position_ids,
144
+ )
145
+
146
+ hidden_states = inputs_embeds
147
+ position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
148
+
149
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
150
+ hidden_states = decoder_layer(
151
+ hidden_states,
152
+ attention_mask=causal_mask,
153
+ position_ids=position_ids,
154
+ past_key_values=past_key_values,
155
+ use_cache=use_cache,
156
+ position_embeddings=position_embeddings,
157
+ **kwargs,
158
+ )
159
+ hidden_states = self.norm(hidden_states)
160
+ return BaseModelOutputWithPast(
161
+ last_hidden_state=hidden_states,
162
+ past_key_values=past_key_values if use_cache else None,
163
+ )
164
+
165
+
166
+ class MistralForCausalLM(LlamaForCausalLM):
167
+ pass
168
+
169
+
170
+ class MistralForTokenClassification(LlamaForTokenClassification):
171
+ pass
172
+
173
+
174
+ class MistralForSequenceClassification(LlamaForSequenceClassification):
175
+ pass
176
+
177
+
178
+ class MistralForQuestionAnswering(GenericForQuestionAnswering, MistralPreTrainedModel): ...
179
+
180
+
181
+ __all__ = [
182
+ "MistralForCausalLM",
183
+ "MistralForQuestionAnswering",
184
+ "MistralModel",
185
+ "MistralPreTrainedModel",
186
+ "MistralForSequenceClassification",
187
+ "MistralForTokenClassification",
188
+ ]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/vit_msn/__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_vit_msn import *
22
+ from .modeling_vit_msn 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/vit_msn/configuration_vit_msn.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 Facebook 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
+ """ViT MSN model configuration"""
15
+
16
+ from huggingface_hub.dataclasses import strict
17
+
18
+ from ...configuration_utils import PreTrainedConfig
19
+ from ...utils import auto_docstring
20
+
21
+
22
+ @auto_docstring(checkpoint="facebook/vit_msn_base")
23
+ @strict
24
+ class ViTMSNConfig(PreTrainedConfig):
25
+ r"""
26
+ Example:
27
+
28
+ ```python
29
+ >>> from transformers import ViTMSNModel, ViTMSNConfig
30
+
31
+ >>> # Initializing a ViT MSN vit-msn-base style configuration
32
+ >>> configuration = ViTConfig()
33
+
34
+ >>> # Initializing a model from the vit-msn-base style configuration
35
+ >>> model = ViTMSNModel(configuration)
36
+
37
+ >>> # Accessing the model configuration
38
+ >>> configuration = model.config
39
+ ```"""
40
+
41
+ model_type = "vit_msn"
42
+
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.0
49
+ attention_probs_dropout_prob: float | int = 0.0
50
+ initializer_range: float = 0.02
51
+ layer_norm_eps: float = 1e-06
52
+ image_size: int | list[int] | tuple[int, int] = 224
53
+ patch_size: int | list[int] | tuple[int, int] = 16
54
+ num_channels: int = 3
55
+ qkv_bias: bool = True
56
+
57
+
58
+ __all__ = ["ViTMSNConfig"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/vit_msn/modeling_vit_msn.py ADDED
@@ -0,0 +1,457 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/vit_msn/modular_vit_msn.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_vit_msn.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # Copyright 2022 Facebook AI 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, Iterable
22
+
23
+ import torch
24
+ from torch import nn
25
+
26
+ from ... import initialization as init
27
+ from ...activations import ACT2FN
28
+ from ...masking_utils import create_bidirectional_mask
29
+ from ...modeling_layers import GradientCheckpointingLayer
30
+ from ...modeling_outputs import BaseModelOutput, ImageClassifierOutput
31
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
32
+ from ...processing_utils import Unpack
33
+ from ...utils import TransformersKwargs, auto_docstring, torch_int
34
+ from ...utils.generic import can_return_tuple, merge_with_config_defaults
35
+ from ...utils.output_capturing import capture_outputs
36
+ from .configuration_vit_msn import ViTMSNConfig
37
+
38
+
39
+ class ViTMSNPatchEmbeddings(nn.Module):
40
+ """
41
+ This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
42
+ `hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
43
+ Transformer.
44
+ """
45
+
46
+ def __init__(self, config: ViTMSNConfig):
47
+ super().__init__()
48
+ image_size = config.image_size
49
+ patch_size = config.patch_size
50
+ image_size = image_size if isinstance(image_size, Iterable) else (image_size, image_size)
51
+ patch_size = patch_size if isinstance(patch_size, Iterable) else (patch_size, patch_size)
52
+
53
+ self.num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
54
+ self.image_size = image_size
55
+ self.patch_size = patch_size
56
+ self.num_channels = config.num_channels
57
+ self.projection = nn.Conv2d(config.num_channels, config.hidden_size, kernel_size=patch_size, stride=patch_size)
58
+
59
+ def forward(self, pixel_values: torch.Tensor) -> torch.Tensor:
60
+ num_channels = pixel_values.shape[1]
61
+ if num_channels != self.num_channels:
62
+ raise ValueError(
63
+ "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
64
+ f" Expected {self.num_channels} but got {num_channels}."
65
+ )
66
+ return self.projection(pixel_values).flatten(2).transpose(1, 2)
67
+
68
+
69
+ class ViTMSNEmbeddings(nn.Module):
70
+ """
71
+ Construct the CLS token, position and patch embeddings. Optionally, also the mask token.
72
+ ViT MSN uses zeros initialization for cls_token and position_embeddings (vs ViT's randn).
73
+ """
74
+
75
+ def __init__(self, config: ViTMSNConfig, use_mask_token: bool = False) -> None:
76
+ super().__init__()
77
+ self.cls_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
78
+ self.mask_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size)) if use_mask_token else None
79
+ self.patch_embeddings = ViTMSNPatchEmbeddings(config)
80
+ num_patches = self.patch_embeddings.num_patches
81
+ self.position_embeddings = nn.Parameter(torch.zeros(1, num_patches + 1, config.hidden_size))
82
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
83
+ self.patch_size = config.patch_size
84
+ self.image_size = self.patch_embeddings.image_size
85
+
86
+ def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor:
87
+ """
88
+ This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher resolution
89
+ images. This method is also adapted to support torch.jit tracing.
90
+
91
+ Adapted from:
92
+ - https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174-L194, and
93
+ - https://github.com/facebookresearch/dinov2/blob/e1277af2ba9496fbadf7aec6eba56e8d882d1e35/dinov2/models/vision_transformer.py#L179-L211
94
+ """
95
+
96
+ num_patches = embeddings.shape[1] - 1
97
+ num_positions = self.position_embeddings.shape[1] - 1
98
+
99
+ # always interpolate when tracing to ensure the exported model works for dynamic input shapes
100
+ if not torch.jit.is_tracing() and num_patches == num_positions and height == width:
101
+ return self.position_embeddings
102
+
103
+ class_pos_embed = self.position_embeddings[:, :1]
104
+ patch_pos_embed = self.position_embeddings[:, 1:]
105
+
106
+ dim = embeddings.shape[-1]
107
+
108
+ new_height = height // self.patch_size
109
+ new_width = width // self.patch_size
110
+
111
+ sqrt_num_positions = torch_int(num_positions**0.5)
112
+ patch_pos_embed = patch_pos_embed.reshape(1, sqrt_num_positions, sqrt_num_positions, dim)
113
+ patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2)
114
+
115
+ patch_pos_embed = nn.functional.interpolate(
116
+ patch_pos_embed,
117
+ size=(new_height, new_width),
118
+ mode="bicubic",
119
+ align_corners=False,
120
+ )
121
+
122
+ patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
123
+
124
+ return torch.cat((class_pos_embed, patch_pos_embed), dim=1)
125
+
126
+ def forward(
127
+ self,
128
+ pixel_values: torch.Tensor,
129
+ bool_masked_pos: torch.BoolTensor | None = None,
130
+ interpolate_pos_encoding: bool = False,
131
+ ) -> torch.Tensor:
132
+ batch_size, num_channels, height, width = pixel_values.shape
133
+ embeddings = self.patch_embeddings(pixel_values)
134
+
135
+ if bool_masked_pos is not None:
136
+ seq_length = embeddings.shape[1]
137
+ mask_tokens = self.mask_token.expand(batch_size, seq_length, -1)
138
+ # replace the masked visual tokens by mask_tokens
139
+ mask = bool_masked_pos.unsqueeze(-1).type_as(mask_tokens)
140
+ embeddings = embeddings * (1.0 - mask) + mask_tokens * mask
141
+
142
+ # add the [CLS] token to the embedded patch tokens
143
+ cls_tokens = self.cls_token.expand(batch_size, -1, -1)
144
+ embeddings = torch.cat((cls_tokens, embeddings), dim=1)
145
+
146
+ if interpolate_pos_encoding:
147
+ embeddings = embeddings + self.interpolate_pos_encoding(embeddings, height, width)
148
+ else:
149
+ if height != self.image_size[0] or width != self.image_size[1]:
150
+ raise ValueError(
151
+ f"Input image size ({height}*{width}) doesn't match model"
152
+ f" ({self.image_size[0]}*{self.image_size[1]})."
153
+ )
154
+ embeddings = embeddings + self.position_embeddings
155
+
156
+ embeddings = self.dropout(embeddings)
157
+
158
+ return embeddings
159
+
160
+
161
+ def eager_attention_forward(
162
+ module: nn.Module,
163
+ query: torch.Tensor,
164
+ key: torch.Tensor,
165
+ value: torch.Tensor,
166
+ attention_mask: torch.Tensor | None,
167
+ scaling: float | None = None,
168
+ dropout: float = 0.0,
169
+ **kwargs: Unpack[TransformersKwargs],
170
+ ):
171
+ if scaling is None:
172
+ scaling = query.size(-1) ** -0.5
173
+
174
+ # Take the dot product between "query" and "key" to get the raw attention scores.
175
+ attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
176
+
177
+ if attention_mask is not None:
178
+ attn_weights = attn_weights + attention_mask
179
+
180
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
181
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
182
+
183
+ attn_output = torch.matmul(attn_weights, value)
184
+ attn_output = attn_output.transpose(1, 2).contiguous()
185
+
186
+ return attn_output, attn_weights
187
+
188
+
189
+ class ViTMSNAttention(nn.Module):
190
+ def __init__(self, config: ViTMSNConfig):
191
+ super().__init__()
192
+ self.config = config
193
+ self.num_attention_heads = config.num_attention_heads
194
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
195
+ self.attention_dropout = config.attention_probs_dropout_prob
196
+ self.scaling = self.head_dim**-0.5
197
+ self.is_causal = False
198
+
199
+ self.q_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.qkv_bias)
200
+ self.k_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.qkv_bias)
201
+ self.v_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.qkv_bias)
202
+ self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=True)
203
+
204
+ def forward(
205
+ self,
206
+ hidden_states: torch.Tensor,
207
+ attention_mask: torch.Tensor | None = None,
208
+ **kwargs: Unpack[TransformersKwargs],
209
+ ) -> tuple[torch.Tensor, torch.Tensor]:
210
+ input_shape = hidden_states.shape[:-1]
211
+ hidden_shape = (*input_shape, -1, self.head_dim)
212
+
213
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
214
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
215
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
216
+
217
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
218
+ self.config._attn_implementation, eager_attention_forward
219
+ )
220
+
221
+ attn_output, attn_weights = attention_interface(
222
+ self,
223
+ query_states,
224
+ key_states,
225
+ value_states,
226
+ attention_mask,
227
+ dropout=0.0 if not self.training else self.attention_dropout,
228
+ scaling=self.scaling,
229
+ **kwargs,
230
+ )
231
+
232
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
233
+ attn_output = self.o_proj(attn_output)
234
+
235
+ return attn_output, attn_weights
236
+
237
+
238
+ class ViTMSNMLP(nn.Module):
239
+ def __init__(self, config: ViTMSNConfig):
240
+ super().__init__()
241
+ self.config = config
242
+ self.activation_fn = ACT2FN[config.hidden_act]
243
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
244
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
245
+
246
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
247
+ hidden_states = self.fc1(hidden_states)
248
+ hidden_states = self.activation_fn(hidden_states)
249
+ hidden_states = self.fc2(hidden_states)
250
+
251
+ return hidden_states
252
+
253
+
254
+ class ViTMSNLayer(GradientCheckpointingLayer):
255
+ def __init__(self, config: ViTMSNConfig):
256
+ super().__init__()
257
+ self.attention = ViTMSNAttention(config)
258
+ self.layernorm_before = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
259
+ self.layernorm_after = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
260
+ self.mlp = ViTMSNMLP(config)
261
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
262
+
263
+ def forward(
264
+ self,
265
+ hidden_states: torch.Tensor,
266
+ attention_mask: torch.Tensor | None = None,
267
+ **kwargs: Unpack[TransformersKwargs],
268
+ ) -> torch.Tensor:
269
+ # Self Attention
270
+ residual = hidden_states
271
+ hidden_states = self.layernorm_before(hidden_states)
272
+ hidden_states, _ = self.attention(hidden_states, attention_mask, **kwargs)
273
+ hidden_states = self.dropout(hidden_states)
274
+ hidden_states = hidden_states + residual
275
+
276
+ # Fully Connected
277
+ residual = hidden_states
278
+ hidden_states = self.layernorm_after(hidden_states)
279
+ hidden_states = self.mlp(hidden_states)
280
+ hidden_states = self.dropout(hidden_states)
281
+ hidden_states = hidden_states + residual
282
+
283
+ return hidden_states
284
+
285
+
286
+ @auto_docstring
287
+ class ViTMSNPreTrainedModel(PreTrainedModel):
288
+ config: ViTMSNConfig
289
+ base_model_prefix = "vit"
290
+ main_input_name = "pixel_values"
291
+ input_modalities = ("image",)
292
+ supports_gradient_checkpointing = True
293
+ _no_split_modules = ["ViTMSNEmbeddings", "ViTMSNLayer"]
294
+ _supports_sdpa = True
295
+ _supports_flash_attn = True
296
+ _supports_flex_attn = True
297
+ _supports_attention_backend = True
298
+ _can_compile_fullgraph = True
299
+ _can_record_outputs = {
300
+ "hidden_states": ViTMSNLayer,
301
+ "attentions": ViTMSNAttention,
302
+ }
303
+ _input_embed_layer = "patch_embeddings"
304
+
305
+ @torch.no_grad()
306
+ def _init_weights(self, module):
307
+ """Initialize the weights"""
308
+ super()._init_weights(module)
309
+ if isinstance(module, ViTMSNEmbeddings):
310
+ init.zeros_(module.cls_token)
311
+ init.zeros_(module.position_embeddings)
312
+ if module.mask_token is not None:
313
+ init.zeros_(module.mask_token)
314
+
315
+
316
+ @auto_docstring
317
+ class ViTMSNModel(ViTMSNPreTrainedModel):
318
+ def __init__(self, config: ViTMSNConfig, use_mask_token: bool = False) -> None:
319
+ r"""
320
+ use_mask_token (`bool`, *optional*, defaults to `False`):
321
+ Whether to use a mask token for masked image modeling.
322
+ """
323
+ super().__init__(config)
324
+ self.config = config
325
+ self.embeddings = ViTMSNEmbeddings(config, use_mask_token=use_mask_token)
326
+ self.layers = nn.ModuleList([ViTMSNLayer(config) for _ in range(config.num_hidden_layers)])
327
+ self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
328
+ # Initialize weights and apply final processing
329
+ self.post_init()
330
+
331
+ @merge_with_config_defaults
332
+ @capture_outputs(tie_last_hidden_states=False)
333
+ @auto_docstring
334
+ def forward(
335
+ self,
336
+ pixel_values: torch.Tensor | None = None,
337
+ bool_masked_pos: torch.BoolTensor | None = None,
338
+ interpolate_pos_encoding: bool | None = None,
339
+ attention_mask: torch.Tensor | None = None,
340
+ **kwargs: Unpack[TransformersKwargs],
341
+ ) -> BaseModelOutput:
342
+ r"""
343
+ bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, num_patches)`, *optional*):
344
+ Boolean masked positions. Indicates which patches are masked (1) and which aren't (0).
345
+
346
+ Examples:
347
+
348
+ ```python
349
+ >>> from transformers import AutoImageProcessor, ViTMSNModel
350
+ >>> import torch
351
+ >>> from PIL import Image
352
+ >>> import httpx
353
+ >>> from io import BytesIO
354
+
355
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
356
+ >>> with httpx.stream("GET", url) as response:
357
+ ... image = Image.open(BytesIO(response.read()))
358
+
359
+ >>> image_processor = AutoImageProcessor.from_pretrained("facebook/vit-msn-small")
360
+ >>> model = ViTMSNModel.from_pretrained("facebook/vit-msn-small")
361
+ >>> inputs = image_processor(images=image, return_tensors="pt")
362
+ >>> with torch.no_grad():
363
+ ... outputs = model(**inputs)
364
+ >>> last_hidden_states = outputs.last_hidden_state
365
+ ```"""
366
+ expected_dtype = self.embeddings.patch_embeddings.projection.weight.dtype
367
+ if pixel_values is not None and pixel_values.dtype != expected_dtype:
368
+ pixel_values = pixel_values.to(expected_dtype)
369
+
370
+ embedding_output = self.embeddings(
371
+ pixel_values, bool_masked_pos=bool_masked_pos, interpolate_pos_encoding=interpolate_pos_encoding
372
+ )
373
+ attention_mask = create_bidirectional_mask(
374
+ config=self.config,
375
+ inputs_embeds=embedding_output,
376
+ attention_mask=attention_mask,
377
+ )
378
+ hidden_states = embedding_output
379
+ for layer in self.layers:
380
+ hidden_states = layer(hidden_states, attention_mask, **kwargs)
381
+ sequence_output = self.layernorm(hidden_states)
382
+
383
+ return BaseModelOutput(last_hidden_state=sequence_output)
384
+
385
+
386
+ @auto_docstring
387
+ class ViTMSNForImageClassification(ViTMSNPreTrainedModel):
388
+ def __init__(self, config: ViTMSNConfig) -> None:
389
+ super().__init__(config)
390
+ self.num_labels = config.num_labels
391
+ self.vit = ViTMSNModel(config)
392
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels) if config.num_labels > 0 else nn.Identity()
393
+ self.post_init()
394
+
395
+ @can_return_tuple
396
+ @auto_docstring
397
+ def forward(
398
+ self,
399
+ pixel_values: torch.Tensor | None = None,
400
+ labels: torch.Tensor | None = None,
401
+ interpolate_pos_encoding: bool | None = None,
402
+ attention_mask: torch.Tensor | None = None,
403
+ **kwargs: Unpack[TransformersKwargs],
404
+ ) -> ImageClassifierOutput:
405
+ r"""
406
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
407
+ Labels for computing the image classification/regression loss.
408
+
409
+ Examples:
410
+
411
+ ```python
412
+ >>> from transformers import AutoImageProcessor, ViTMSNForImageClassification
413
+ >>> import torch
414
+ >>> from PIL import Image
415
+ >>> import httpx
416
+ >>> from io import BytesIO
417
+
418
+ >>> torch.manual_seed(2) # doctest: +IGNORE_RESULT
419
+
420
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
421
+ >>> with httpx.stream("GET", url) as response:
422
+ ... image = Image.open(BytesIO(response.read())).convert("RGB")
423
+
424
+ >>> image_processor = AutoImageProcessor.from_pretrained("facebook/vit-msn-small")
425
+ >>> model = ViTMSNForImageClassification.from_pretrained("facebook/vit-msn-small")
426
+
427
+ >>> inputs = image_processor(images=image, return_tensors="pt")
428
+ >>> with torch.no_grad():
429
+ ... logits = model(**inputs).logits
430
+ >>> # model predicts one of the 1000 ImageNet classes
431
+ >>> predicted_label = logits.argmax(-1).item()
432
+ >>> print(model.config.id2label[predicted_label])
433
+ tusker
434
+ ```
435
+ """
436
+ outputs: BaseModelOutput = self.vit(
437
+ pixel_values,
438
+ interpolate_pos_encoding=interpolate_pos_encoding,
439
+ attention_mask=attention_mask,
440
+ **kwargs,
441
+ )
442
+ sequence_output = outputs.last_hidden_state
443
+ logits = self.classifier(sequence_output[:, 0, :])
444
+
445
+ loss = None
446
+ if labels is not None:
447
+ loss = self.loss_function(labels, logits, self.config, **kwargs)
448
+
449
+ return ImageClassifierOutput(
450
+ loss=loss,
451
+ logits=logits,
452
+ hidden_states=outputs.hidden_states,
453
+ attentions=outputs.attentions,
454
+ )
455
+
456
+
457
+ __all__ = ["ViTMSNModel", "ViTMSNForImageClassification", "ViTMSNPreTrainedModel"]
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/vit_msn/modular_vit_msn.py ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 Facebook 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
+ """PyTorch ViT MSN (masked siamese network) model - modular file inheriting from ViT."""
15
+
16
+ import torch
17
+ from torch import nn
18
+
19
+ from ... import initialization as init
20
+ from ...masking_utils import create_bidirectional_mask
21
+ from ...modeling_outputs import BaseModelOutput, ImageClassifierOutput
22
+ from ...processing_utils import Unpack
23
+ from ...utils import TransformersKwargs, auto_docstring
24
+ from ...utils.generic import can_return_tuple, merge_with_config_defaults
25
+ from ...utils.output_capturing import capture_outputs
26
+ from ..vit.modeling_vit import (
27
+ PreTrainedModel,
28
+ ViTAttention,
29
+ ViTEmbeddings,
30
+ ViTLayer,
31
+ ViTMLP,
32
+ ViTModel,
33
+ ViTPatchEmbeddings,
34
+ ViTPreTrainedModel,
35
+ )
36
+ from .configuration_vit_msn import ViTMSNConfig
37
+
38
+
39
+ class ViTMSNPatchEmbeddings(ViTPatchEmbeddings):
40
+ pass
41
+
42
+
43
+ class ViTMSNEmbeddings(ViTEmbeddings):
44
+ """
45
+ Construct the CLS token, position and patch embeddings. Optionally, also the mask token.
46
+ ViT MSN uses zeros initialization for cls_token and position_embeddings (vs ViT's randn).
47
+ """
48
+
49
+ def __init__(self, config: ViTMSNConfig, use_mask_token: bool = False) -> None:
50
+ super().__init__(config, use_mask_token=use_mask_token)
51
+ self.cls_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
52
+ num_patches = self.patch_embeddings.num_patches
53
+ self.position_embeddings = nn.Parameter(torch.zeros(1, num_patches + 1, config.hidden_size))
54
+
55
+
56
+ class ViTMSNAttention(ViTAttention):
57
+ pass
58
+
59
+
60
+ class ViTMSNMLP(ViTMLP):
61
+ pass
62
+
63
+
64
+ class ViTMSNLayer(ViTLayer):
65
+ pass
66
+
67
+
68
+ class ViTMSNPreTrainedModel(ViTPreTrainedModel):
69
+ base_model_prefix = "vit"
70
+
71
+ @torch.no_grad()
72
+ def _init_weights(self, module):
73
+ PreTrainedModel._init_weights(self, module)
74
+ if isinstance(module, ViTMSNEmbeddings):
75
+ init.zeros_(module.cls_token)
76
+ init.zeros_(module.position_embeddings)
77
+ if module.mask_token is not None:
78
+ init.zeros_(module.mask_token)
79
+
80
+
81
+ @auto_docstring
82
+ class ViTMSNModel(ViTModel):
83
+ def __init__(self, config: ViTMSNConfig, use_mask_token: bool = False) -> None:
84
+ r"""
85
+ use_mask_token (`bool`, *optional*, defaults to `False`):
86
+ Whether to use a mask token for masked image modeling.
87
+ """
88
+ super().__init__(config)
89
+ del self.pooler
90
+
91
+ @merge_with_config_defaults
92
+ @capture_outputs(tie_last_hidden_states=False)
93
+ @auto_docstring
94
+ def forward(
95
+ self,
96
+ pixel_values: torch.Tensor | None = None,
97
+ bool_masked_pos: torch.BoolTensor | None = None,
98
+ interpolate_pos_encoding: bool | None = None,
99
+ attention_mask: torch.Tensor | None = None,
100
+ **kwargs: Unpack[TransformersKwargs],
101
+ ) -> BaseModelOutput:
102
+ r"""
103
+ bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, num_patches)`, *optional*):
104
+ Boolean masked positions. Indicates which patches are masked (1) and which aren't (0).
105
+
106
+ Examples:
107
+
108
+ ```python
109
+ >>> from transformers import AutoImageProcessor, ViTMSNModel
110
+ >>> import torch
111
+ >>> from PIL import Image
112
+ >>> import httpx
113
+ >>> from io import BytesIO
114
+
115
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
116
+ >>> with httpx.stream("GET", url) as response:
117
+ ... image = Image.open(BytesIO(response.read()))
118
+
119
+ >>> image_processor = AutoImageProcessor.from_pretrained("facebook/vit-msn-small")
120
+ >>> model = ViTMSNModel.from_pretrained("facebook/vit-msn-small")
121
+ >>> inputs = image_processor(images=image, return_tensors="pt")
122
+ >>> with torch.no_grad():
123
+ ... outputs = model(**inputs)
124
+ >>> last_hidden_states = outputs.last_hidden_state
125
+ ```"""
126
+ expected_dtype = self.embeddings.patch_embeddings.projection.weight.dtype
127
+ if pixel_values is not None and pixel_values.dtype != expected_dtype:
128
+ pixel_values = pixel_values.to(expected_dtype)
129
+
130
+ embedding_output = self.embeddings(
131
+ pixel_values, bool_masked_pos=bool_masked_pos, interpolate_pos_encoding=interpolate_pos_encoding
132
+ )
133
+ attention_mask = create_bidirectional_mask(
134
+ config=self.config,
135
+ inputs_embeds=embedding_output,
136
+ attention_mask=attention_mask,
137
+ )
138
+ hidden_states = embedding_output
139
+ for layer in self.layers:
140
+ hidden_states = layer(hidden_states, attention_mask, **kwargs)
141
+ sequence_output = self.layernorm(hidden_states)
142
+
143
+ return BaseModelOutput(last_hidden_state=sequence_output)
144
+
145
+
146
+ @auto_docstring
147
+ class ViTMSNForImageClassification(ViTMSNPreTrainedModel):
148
+ def __init__(self, config: ViTMSNConfig) -> None:
149
+ super().__init__(config)
150
+ self.num_labels = config.num_labels
151
+ self.vit = ViTMSNModel(config)
152
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels) if config.num_labels > 0 else nn.Identity()
153
+ self.post_init()
154
+
155
+ @can_return_tuple
156
+ @auto_docstring
157
+ def forward(
158
+ self,
159
+ pixel_values: torch.Tensor | None = None,
160
+ labels: torch.Tensor | None = None,
161
+ interpolate_pos_encoding: bool | None = None,
162
+ attention_mask: torch.Tensor | None = None,
163
+ **kwargs: Unpack[TransformersKwargs],
164
+ ) -> ImageClassifierOutput:
165
+ r"""
166
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
167
+ Labels for computing the image classification/regression loss.
168
+
169
+ Examples:
170
+
171
+ ```python
172
+ >>> from transformers import AutoImageProcessor, ViTMSNForImageClassification
173
+ >>> import torch
174
+ >>> from PIL import Image
175
+ >>> import httpx
176
+ >>> from io import BytesIO
177
+
178
+ >>> torch.manual_seed(2) # doctest: +IGNORE_RESULT
179
+
180
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
181
+ >>> with httpx.stream("GET", url) as response:
182
+ ... image = Image.open(BytesIO(response.read())).convert("RGB")
183
+
184
+ >>> image_processor = AutoImageProcessor.from_pretrained("facebook/vit-msn-small")
185
+ >>> model = ViTMSNForImageClassification.from_pretrained("facebook/vit-msn-small")
186
+
187
+ >>> inputs = image_processor(images=image, return_tensors="pt")
188
+ >>> with torch.no_grad():
189
+ ... logits = model(**inputs).logits
190
+ >>> # model predicts one of the 1000 ImageNet classes
191
+ >>> predicted_label = logits.argmax(-1).item()
192
+ >>> print(model.config.id2label[predicted_label])
193
+ tusker
194
+ ```
195
+ """
196
+ outputs: BaseModelOutput = self.vit(
197
+ pixel_values,
198
+ interpolate_pos_encoding=interpolate_pos_encoding,
199
+ attention_mask=attention_mask,
200
+ **kwargs,
201
+ )
202
+ sequence_output = outputs.last_hidden_state
203
+ logits = self.classifier(sequence_output[:, 0, :])
204
+
205
+ loss = None
206
+ if labels is not None:
207
+ loss = self.loss_function(labels, logits, self.config, **kwargs)
208
+
209
+ return ImageClassifierOutput(
210
+ loss=loss,
211
+ logits=logits,
212
+ hidden_states=outputs.hidden_states,
213
+ attentions=outputs.attentions,
214
+ )
215
+
216
+
217
+ __all__ = ["ViTMSNModel", "ViTMSNForImageClassification", "ViTMSNPreTrainedModel"]