davanstrien HF Staff commited on
Commit
443fc75
·
verified ·
1 Parent(s): 0b93f74

Upload folder using huggingface_hub

Browse files
__pycache__/modeling_encoder_seq_cls.cpython-312.pyc ADDED
Binary file (3.38 kB). View file
 
config.json ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "EncoderForSequenceClassification"
4
+ ],
5
+ "auto_map": {
6
+ "AutoModel": "modeling_lfm2_bidirectional.Lfm2BidirectionalModel",
7
+ "AutoModelForMaskedLM": "modeling_lfm2_bidirectional.Lfm2BidirectionalForMaskedLM",
8
+ "AutoModelForSequenceClassification": "modeling_encoder_seq_cls.EncoderForSequenceClassification"
9
+ },
10
+ "block_auto_adjust_ff_dim": true,
11
+ "block_dim": 1024,
12
+ "block_ffn_dim_multiplier": 1.0,
13
+ "block_mlp_init_scale": 1.0,
14
+ "block_multiple_of": 256,
15
+ "block_norm_eps": 1e-05,
16
+ "block_out_init_scale": 1.0,
17
+ "block_use_swiglu": true,
18
+ "block_use_xavier_init": true,
19
+ "bos_token_id": 1,
20
+ "classifier_thresholds": [
21
+ 0.35,
22
+ 0.15,
23
+ 0.2,
24
+ 0.15,
25
+ 0.15,
26
+ 0.4,
27
+ 0.1,
28
+ 0.15,
29
+ 0.2,
30
+ 0.1,
31
+ 0.2,
32
+ 0.3,
33
+ 0.2,
34
+ 0.35,
35
+ 0.3,
36
+ 0.25,
37
+ 0.55,
38
+ 0.5,
39
+ 0.3,
40
+ 0.05,
41
+ 0.4,
42
+ 0.25,
43
+ 0.4,
44
+ 0.3,
45
+ 0.2,
46
+ 0.35,
47
+ 0.25,
48
+ 0.45,
49
+ 0.3,
50
+ 0.25,
51
+ 0.25,
52
+ 0.1,
53
+ 0.1,
54
+ 0.2,
55
+ 0.15
56
+ ],
57
+ "conv_L_cache": 3,
58
+ "conv_bias": false,
59
+ "conv_dim": 1024,
60
+ "conv_dim_out": 1024,
61
+ "conv_use_xavier_init": true,
62
+ "dtype": "float32",
63
+ "eos_token_id": 7,
64
+ "full_attn_idxs": null,
65
+ "hidden_size": 1024,
66
+ "id2label": {
67
+ "0": "audio-classification",
68
+ "1": "audio-to-audio",
69
+ "10": "image-to-image",
70
+ "11": "image-to-text",
71
+ "12": "multiple-choice",
72
+ "13": "object-detection",
73
+ "14": "question-answering",
74
+ "15": "reinforcement-learning",
75
+ "16": "robotics",
76
+ "17": "sentence-similarity",
77
+ "18": "summarization",
78
+ "19": "table-question-answering",
79
+ "2": "automatic-speech-recognition",
80
+ "20": "tabular-classification",
81
+ "21": "tabular-regression",
82
+ "22": "text-classification",
83
+ "23": "text-generation",
84
+ "24": "text-retrieval",
85
+ "25": "text-to-image",
86
+ "26": "text-to-speech",
87
+ "27": "text-to-video",
88
+ "28": "time-series-forecasting",
89
+ "29": "token-classification",
90
+ "3": "feature-extraction",
91
+ "30": "translation",
92
+ "31": "video-classification",
93
+ "32": "video-text-to-text",
94
+ "33": "visual-question-answering",
95
+ "34": "zero-shot-classification",
96
+ "4": "fill-mask",
97
+ "5": "image-classification",
98
+ "6": "image-feature-extraction",
99
+ "7": "image-segmentation",
100
+ "8": "image-text-to-text",
101
+ "9": "image-to-3d"
102
+ },
103
+ "initializer_range": 0.02,
104
+ "intermediate_size": 6656,
105
+ "label2id": {
106
+ "audio-classification": 0,
107
+ "audio-to-audio": 1,
108
+ "automatic-speech-recognition": 2,
109
+ "feature-extraction": 3,
110
+ "fill-mask": 4,
111
+ "image-classification": 5,
112
+ "image-feature-extraction": 6,
113
+ "image-segmentation": 7,
114
+ "image-text-to-text": 8,
115
+ "image-to-3d": 9,
116
+ "image-to-image": 10,
117
+ "image-to-text": 11,
118
+ "multiple-choice": 12,
119
+ "object-detection": 13,
120
+ "question-answering": 14,
121
+ "reinforcement-learning": 15,
122
+ "robotics": 16,
123
+ "sentence-similarity": 17,
124
+ "summarization": 18,
125
+ "table-question-answering": 19,
126
+ "tabular-classification": 20,
127
+ "tabular-regression": 21,
128
+ "text-classification": 22,
129
+ "text-generation": 23,
130
+ "text-retrieval": 24,
131
+ "text-to-image": 25,
132
+ "text-to-speech": 26,
133
+ "text-to-video": 27,
134
+ "time-series-forecasting": 28,
135
+ "token-classification": 29,
136
+ "translation": 30,
137
+ "video-classification": 31,
138
+ "video-text-to-text": 32,
139
+ "visual-question-answering": 33,
140
+ "zero-shot-classification": 34
141
+ },
142
+ "layer_types": [
143
+ "conv",
144
+ "conv",
145
+ "full_attention",
146
+ "conv",
147
+ "conv",
148
+ "full_attention",
149
+ "conv",
150
+ "conv",
151
+ "full_attention",
152
+ "conv",
153
+ "full_attention",
154
+ "conv",
155
+ "full_attention",
156
+ "conv",
157
+ "full_attention",
158
+ "conv"
159
+ ],
160
+ "max_position_embeddings": 128000,
161
+ "model_type": "lfm2",
162
+ "norm_eps": 1e-05,
163
+ "num_attention_heads": 16,
164
+ "num_heads": 16,
165
+ "num_hidden_layers": 16,
166
+ "num_key_value_heads": 8,
167
+ "pad_token_id": 0,
168
+ "problem_type": "multi_label_classification",
169
+ "rope_parameters": {
170
+ "rope_theta": 1000000.0,
171
+ "rope_type": "default"
172
+ },
173
+ "tie_word_embeddings": true,
174
+ "transformers_version": "5.14.1",
175
+ "use_cache": false,
176
+ "use_pos_enc": true,
177
+ "vocab_size": 65536
178
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3bf5c212f49c333d3e0e522e4cd61672774559c8292146670d7fbc2269f214a0
3
+ size 1418095980
modeling_encoder_seq_cls.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generic sequence classification head: AutoModel backbone + mean pooling + linear.
2
+
3
+ Auto-generated by the uv-scripts `train-classifier.py` recipe. Loaded via
4
+ `AutoModelForSequenceClassification.from_pretrained(repo, trust_remote_code=True)`;
5
+ the backbone class is resolved from this repo's own `auto_map`/code files.
6
+ """
7
+
8
+ import torch
9
+ from torch import nn
10
+ from transformers import AutoModel, PreTrainedModel
11
+ from transformers.modeling_outputs import SequenceClassifierOutput
12
+
13
+
14
+ class EncoderForSequenceClassification(PreTrainedModel):
15
+ base_model_prefix = "model"
16
+ supports_gradient_checkpointing = True
17
+
18
+ def __init__(self, config):
19
+ super().__init__(config)
20
+ self.num_labels = config.num_labels
21
+ self.model = AutoModel.from_config(config, trust_remote_code=True)
22
+ dropout = getattr(config, "classifier_dropout", None)
23
+ self.dropout = nn.Dropout(0.1 if dropout is None else dropout)
24
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
25
+ self.post_init()
26
+
27
+ def forward(self, input_ids=None, attention_mask=None, labels=None, **kwargs):
28
+ outputs = self.model(input_ids=input_ids, attention_mask=attention_mask)
29
+ hidden = outputs.last_hidden_state
30
+ if attention_mask is None:
31
+ pooled = hidden.mean(dim=1)
32
+ else:
33
+ mask = attention_mask.unsqueeze(-1).to(hidden.dtype)
34
+ pooled = (hidden * mask).sum(dim=1) / mask.sum(dim=1).clamp(min=1e-9)
35
+ logits = self.classifier(self.dropout(pooled))
36
+ loss = None
37
+ if labels is not None:
38
+ if self.config.problem_type == "multi_label_classification":
39
+ loss = nn.functional.binary_cross_entropy_with_logits(
40
+ logits, labels.to(logits.dtype)
41
+ )
42
+ else:
43
+ loss = nn.functional.cross_entropy(logits, labels.view(-1))
44
+ return SequenceClassifierOutput(loss=loss, logits=logits)
45
+
46
+
47
+ # AutoModelForSequenceClassification.from_pretrained registers this class against the
48
+ # config class, and that requires config_class to be set (transformers v5 crashes on None).
49
+ try:
50
+ from transformers import Lfm2Config
51
+ EncoderForSequenceClassification.config_class = Lfm2Config
52
+ except ImportError: # flat import during training; the trainer sets config_class itself
53
+ pass
modeling_lfm2_bidirectional.py ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """LFM2 backbone with bidirectional attention + non-causal short-conv.
2
+
3
+ Wired into the HF repo via `auto_map` in config.json so that
4
+
5
+ AutoModel.from_pretrained(repo, trust_remote_code=True)
6
+ AutoModelForMaskedLM.from_pretrained(repo, trust_remote_code=True)
7
+
8
+ both return a model with the encoder-style patches already applied.
9
+
10
+ Supports `attn_implementation` in {"eager", "sdpa", "flash_attention_2"}:
11
+
12
+ eager/sdpa consume a 4D additive pad-only mask and reproduce the exact
13
+ training-time behavior; flash_attention_2 receives the 2D padding mask (or
14
+ None) and runs the kernel non-causally via `Lfm2Attention.is_causal = False`,
15
+ yielding outputs equivalent to the unpadded forward.
16
+ """
17
+
18
+ from typing import Optional
19
+
20
+ import torch
21
+ import torch.nn as nn
22
+ import torch.nn.functional as F
23
+ from transformers.configuration_utils import PretrainedConfig
24
+ from transformers.modeling_outputs import BaseModelOutput, MaskedLMOutput
25
+ from transformers.modeling_utils import PreTrainedModel
26
+ from transformers.models.lfm2 import modeling_lfm2 as _lfm2_mod
27
+ from transformers.models.lfm2.configuration_lfm2 import Lfm2Config
28
+ from transformers.models.lfm2.modeling_lfm2 import (
29
+ Lfm2Attention,
30
+ Lfm2Model,
31
+ Lfm2PreTrainedModel,
32
+ Lfm2ShortConv,
33
+ apply_mask_to_padding_states,
34
+ )
35
+
36
+
37
+ def _bidirectional_mask(
38
+ config,
39
+ input_embeds: torch.Tensor = None,
40
+ attention_mask: Optional[torch.Tensor] = None,
41
+ cache_position: Optional[torch.LongTensor] = None,
42
+ past_key_values=None,
43
+ position_ids: Optional[torch.LongTensor] = None,
44
+ **kwargs,
45
+ ) -> Optional[torch.Tensor]:
46
+ # transformers has renamed the embeds kwarg across versions
47
+ # (input_embeds <-> inputs_embeds); accept either to stay forward-compatible.
48
+ if input_embeds is None:
49
+ input_embeds = kwargs.get("inputs_embeds")
50
+
51
+ if config._attn_implementation == "flash_attention_2":
52
+ # FA2 only uses the 2D padding mask to unpad sequences; causality is
53
+ # controlled by `Lfm2Attention.is_causal` (set to False below).
54
+ if attention_mask is not None and not attention_mask.all():
55
+ return attention_mask
56
+ return None
57
+
58
+ device = input_embeds.device
59
+ dtype = input_embeds.dtype
60
+ bsz, q_len = input_embeds.shape[:2]
61
+ past = past_key_values.get_seq_length() if past_key_values is not None else 0
62
+ kv_len = past + q_len
63
+
64
+ mask = torch.zeros((bsz, 1, q_len, kv_len), device=device, dtype=dtype)
65
+ if attention_mask is not None:
66
+ cur_len = attention_mask.size(-1)
67
+ key_pad_flags = (attention_mask == 0).to(device=device, dtype=torch.float32)
68
+ pad_vec = torch.zeros((bsz, kv_len), device=device, dtype=torch.float32)
69
+ if cur_len > 0:
70
+ pad_vec[:, past:past + cur_len] = key_pad_flags * -1e9
71
+ mask = mask + pad_vec.to(dtype)[:, None, None, :]
72
+ return mask
73
+
74
+
75
+ def _noncausal_shortconv_forward(
76
+ self,
77
+ hidden_states: torch.Tensor,
78
+ past_key_values=None,
79
+ cache_position=None,
80
+ attention_mask: Optional[torch.Tensor] = None,
81
+ **kwargs,
82
+ ) -> torch.Tensor:
83
+ x = apply_mask_to_padding_states(hidden_states, attention_mask)
84
+
85
+ BCx = self.in_proj(x).transpose(-1, -2)
86
+ B, C, x = BCx.chunk(3, dim=-2)
87
+ Bx = B * x
88
+
89
+ k = self.conv.weight.shape[-1]
90
+ pad = k // 2
91
+ conv_out = F.conv1d(
92
+ Bx, weight=self.conv.weight, bias=self.conv.bias,
93
+ stride=1, padding=pad, dilation=1, groups=Bx.shape[1],
94
+ )
95
+ if conv_out.shape[-1] > Bx.shape[-1]:
96
+ conv_out = conv_out[..., :Bx.shape[-1]]
97
+ elif conv_out.shape[-1] < Bx.shape[-1]:
98
+ conv_out = F.pad(conv_out, (0, Bx.shape[-1] - conv_out.shape[-1]))
99
+
100
+ y = C * conv_out
101
+ y = y.transpose(-1, -2).contiguous()
102
+ return self.out_proj(y)
103
+
104
+
105
+ def _shortconv_forward(self, *args, **kwargs):
106
+ return self.slow_forward(*args, **kwargs)
107
+
108
+
109
+ _PATCHED = False
110
+
111
+
112
+ def _install_patches() -> None:
113
+ global _PATCHED
114
+ if _PATCHED:
115
+ return
116
+ _lfm2_mod.create_causal_mask = _bidirectional_mask
117
+ Lfm2ShortConv.slow_forward = _noncausal_shortconv_forward
118
+ Lfm2ShortConv.forward = _shortconv_forward
119
+ _PATCHED = True
120
+
121
+
122
+ _install_patches()
123
+
124
+
125
+ def _set_attention_noncausal(model) -> None:
126
+ for module in model.modules():
127
+ if isinstance(module, Lfm2Attention):
128
+ module.is_causal = False
129
+
130
+
131
+ class Lfm2BidirectionalModel(Lfm2Model):
132
+ """LFM2 patched for encoder-style use:
133
+ full bidirectional attention + non-causal short-conv."""
134
+
135
+ def __init__(self, config):
136
+ _install_patches()
137
+ super().__init__(config)
138
+ _set_attention_noncausal(self)
139
+
140
+
141
+ class Lfm2BidirectionalForMaskedLM(Lfm2PreTrainedModel):
142
+ """LFM2 bidirectional encoder with a tied masked-LM head."""
143
+
144
+ config_class = Lfm2Config
145
+ base_model_prefix = "lfm2"
146
+ _tied_weights_keys = {"lm_head.weight": "lfm2.embed_tokens.weight"}
147
+
148
+ def __init__(self, config: Lfm2Config):
149
+ _install_patches()
150
+ config = type(config).from_dict({**config.to_dict(), "use_cache": False})
151
+ super().__init__(config)
152
+ self.lfm2 = Lfm2BidirectionalModel(config)
153
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
154
+ self.post_init()
155
+ self.lm_head.weight = self.lfm2.embed_tokens.weight
156
+
157
+ def get_input_embeddings(self):
158
+ return self.lfm2.embed_tokens
159
+
160
+ def set_input_embeddings(self, value):
161
+ self.lfm2.embed_tokens = value
162
+
163
+ def get_output_embeddings(self):
164
+ return self.lm_head
165
+
166
+ def set_output_embeddings(self, new_embeddings):
167
+ self.lm_head = new_embeddings
168
+
169
+ def forward(
170
+ self,
171
+ input_ids: Optional[torch.LongTensor] = None,
172
+ attention_mask: Optional[torch.Tensor] = None,
173
+ position_ids: Optional[torch.LongTensor] = None,
174
+ inputs_embeds: Optional[torch.FloatTensor] = None,
175
+ labels: Optional[torch.LongTensor] = None,
176
+ output_hidden_states: Optional[bool] = None,
177
+ output_attentions: Optional[bool] = None,
178
+ return_dict: Optional[bool] = None,
179
+ **kwargs,
180
+ ) -> MaskedLMOutput:
181
+ return_dict = True if return_dict is None else return_dict
182
+ outputs = self.lfm2(
183
+ input_ids=input_ids,
184
+ attention_mask=attention_mask,
185
+ position_ids=position_ids,
186
+ inputs_embeds=inputs_embeds,
187
+ use_cache=False,
188
+ output_attentions=output_attentions,
189
+ output_hidden_states=output_hidden_states,
190
+ return_dict=True,
191
+ )
192
+ hidden = outputs.last_hidden_state
193
+ logits = self.lm_head(hidden)
194
+
195
+ loss = None
196
+ if labels is not None:
197
+ loss = F.cross_entropy(
198
+ logits.view(-1, self.config.vocab_size),
199
+ labels.view(-1),
200
+ ignore_index=-100,
201
+ )
202
+
203
+ if not return_dict:
204
+ out = (logits,) + outputs[1:]
205
+ return ((loss,) + out) if loss is not None else out
206
+ return MaskedLMOutput(
207
+ loss=loss,
208
+ logits=logits,
209
+ hidden_states=outputs.hidden_states,
210
+ attentions=outputs.attentions,
211
+ )
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "backend": "tokenizers",
3
+ "bos_token": "<|startoftext|>",
4
+ "clean_up_tokenization_spaces": false,
5
+ "eos_token": "<|im_end|>",
6
+ "is_local": false,
7
+ "local_files_only": false,
8
+ "mask_token": "<|mask|>",
9
+ "model_max_length": 1000000000000000019884624838656,
10
+ "pad_token": "<|pad|>",
11
+ "tokenizer_class": "TokenizersBackend"
12
+ }