GenerTeam commited on
Commit
e9bb082
·
verified ·
1 Parent(s): 770aa84

Upload 7 files

Browse files
configuration_generanno.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
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
+ """LLaMA model configuration"""
21
+
22
+ from transformers.configuration_utils import PretrainedConfig
23
+ from transformers.modeling_rope_utils import rope_config_validation
24
+
25
+
26
+ class GenerannoConfig(PretrainedConfig):
27
+ r"""
28
+ This is the configuration class to store the configuration of a [`GenerannoModel`]. It is used to instantiate an LLaMA
29
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
30
+ defaults will yield a similar configuration to that of the LLaMA-7B.
31
+
32
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
33
+ documentation from [`PretrainedConfig`] for more information.
34
+
35
+
36
+ Args:
37
+ vocab_size (`int`, *optional*, defaults to 32000):
38
+ Vocabulary size of the LLaMA model. Defines the number of different tokens that can be represented by the
39
+ `inputs_ids` passed when calling [`GenerannoModel`]
40
+ hidden_size (`int`, *optional*, defaults to 4096):
41
+ Dimension of the hidden representations.
42
+ intermediate_size (`int`, *optional*, defaults to 11008):
43
+ Dimension of the MLP representations.
44
+ num_hidden_layers (`int`, *optional*, defaults to 32):
45
+ Number of hidden layers in the Transformer decoder.
46
+ num_attention_heads (`int`, *optional*, defaults to 32):
47
+ Number of attention heads for each attention layer in the Transformer decoder.
48
+ num_key_value_heads (`int`, *optional*):
49
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
50
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
51
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
52
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
53
+ by meanpooling all the original heads within that group. For more details checkout [this
54
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
55
+ `num_attention_heads`.
56
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
57
+ The non-linear activation function (function or string) in the decoder.
58
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
59
+ The maximum sequence length that this model might ever be used with. Generanno 1 supports up to 2048 tokens,
60
+ Generanno 2 up to 4096, CodeGeneranno up to 16384.
61
+ initializer_range (`float`, *optional*, defaults to 0.02):
62
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
63
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
64
+ The epsilon used by the rms normalization layers.
65
+ use_cache (`bool`, *optional*, defaults to `True`):
66
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
67
+ relevant if `config.is_decoder=True`.
68
+ pad_token_id (`int`, *optional*):
69
+ Padding token id.
70
+ bos_token_id (`int`, *optional*, defaults to 1):
71
+ Beginning of stream token id.
72
+ eos_token_id (`int`, *optional*, defaults to 2):
73
+ End of stream token id.
74
+ pretraining_tp (`int`, *optional*, defaults to 1):
75
+ Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
76
+ document](https://huggingface.co/docs/transformers/main/perf_train_gpu_many#tensor-parallelism) to
77
+ understand more about it. This value is necessary to ensure exact reproducibility of the pretraining
78
+ results. Please refer to [this issue](https://github.com/pytorch/pytorch/issues/76232).
79
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
80
+ Whether to tie weight embeddings
81
+ rope_theta (`float`, *optional*, defaults to 10000.0):
82
+ The base period of the RoPE embeddings.
83
+ rope_scaling (`Dict`, *optional*):
84
+ Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
85
+ and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
86
+ accordingly.
87
+ Expected contents:
88
+ `rope_type` (`str`):
89
+ The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
90
+ 'llama3'], with 'default' being the original RoPE implementation.
91
+ `factor` (`float`, *optional*):
92
+ Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
93
+ most scaling types, a `factor` of x will enable the model to handle sequences of length x *
94
+ original maximum pre-trained length.
95
+ `original_max_position_embeddings` (`int`, *optional*):
96
+ Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
97
+ pretraining.
98
+ `attention_factor` (`float`, *optional*):
99
+ Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
100
+ computation. If unspecified, it defaults to value recommended by the implementation, using the
101
+ `factor` field to infer the suggested value.
102
+ `beta_fast` (`float`, *optional*):
103
+ Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
104
+ ramp function. If unspecified, it defaults to 32.
105
+ `beta_slow` (`float`, *optional*):
106
+ Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
107
+ ramp function. If unspecified, it defaults to 1.
108
+ `short_factor` (`List[float]`, *optional*):
109
+ Only used with 'longrope'. The scaling factor to be applied to short contexts (<
110
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
111
+ size divided by the number of attention heads divided by 2
112
+ `long_factor` (`List[float]`, *optional*):
113
+ Only used with 'longrope'. The scaling factor to be applied to long contexts (<
114
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
115
+ size divided by the number of attention heads divided by 2
116
+ `low_freq_factor` (`float`, *optional*):
117
+ Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
118
+ `high_freq_factor` (`float`, *optional*):
119
+ Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
120
+ attention_bias (`bool`, *optional*, defaults to `False`):
121
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
122
+ attention_dropout (`float`, *optional*, defaults to 0.0):
123
+ The dropout ratio for the attention probabilities.
124
+ mlp_bias (`bool`, *optional*, defaults to `False`):
125
+ Whether to use a bias in up_proj, down_proj and gate_proj layers in the MLP layers.
126
+ """
127
+
128
+ model_type = "generanno"
129
+
130
+ def __init__(
131
+ self,
132
+ vocab_size=32000,
133
+ hidden_size=4096,
134
+ intermediate_size=11008,
135
+ num_hidden_layers=32,
136
+ num_attention_heads=32,
137
+ num_key_value_heads=None,
138
+ hidden_act="silu",
139
+ max_position_embeddings=2048,
140
+ initializer_range=0.02,
141
+ rms_norm_eps=1e-6,
142
+ pad_token_id=None,
143
+ bos_token_id=1,
144
+ eos_token_id=2,
145
+ mask_token_id=4,
146
+ pretraining_tp=1,
147
+ tie_word_embeddings=False,
148
+ rope_theta=10000.0,
149
+ rope_scaling=None,
150
+ attention_bias=False,
151
+ attention_dropout=0.0,
152
+ mlp_bias=False,
153
+ **kwargs,
154
+ ):
155
+ self.vocab_size = vocab_size
156
+ self.max_position_embeddings = max_position_embeddings
157
+ self.hidden_size = hidden_size
158
+ self.intermediate_size = intermediate_size
159
+ self.num_hidden_layers = num_hidden_layers
160
+ self.num_attention_heads = num_attention_heads
161
+
162
+ # for backward compatibility
163
+ if num_key_value_heads is None:
164
+ num_key_value_heads = num_attention_heads
165
+
166
+ self.num_key_value_heads = num_key_value_heads
167
+ self.hidden_act = hidden_act
168
+ self.initializer_range = initializer_range
169
+ self.rms_norm_eps = rms_norm_eps
170
+ self.pretraining_tp = pretraining_tp
171
+ self.rope_theta = rope_theta
172
+ self.rope_scaling = rope_scaling
173
+ self.attention_bias = attention_bias
174
+ self.attention_dropout = attention_dropout
175
+ self.mlp_bias = mlp_bias
176
+
177
+ # Validate the correctness of rotary position embeddings parameters
178
+ # BC: if there is a 'type' field, move it to 'rope_type'.
179
+ if self.rope_scaling is not None and "type" in self.rope_scaling:
180
+ self.rope_scaling["rope_type"] = self.rope_scaling["type"]
181
+ rope_config_validation(self)
182
+
183
+ super().__init__(
184
+ pad_token_id=pad_token_id,
185
+ bos_token_id=bos_token_id,
186
+ eos_token_id=eos_token_id,
187
+ mask_token_id=mask_token_id,
188
+ tie_word_embeddings=tie_word_embeddings,
189
+ **kwargs,
190
+ )
custom_trainer.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import Trainer
2
+ import torch
3
+ import torch.nn.functional as F
4
+ import numpy as np
5
+
6
+
7
+ class AnnotationTrainer(Trainer):
8
+ def __init__(self, **kwargs):
9
+ """
10
+ Custom Trainer for genome annotation tasks.
11
+ """
12
+ if "compute_metrics" not in kwargs:
13
+ kwargs["compute_metrics"] = self.compute_metrics
14
+
15
+ super().__init__(**kwargs)
16
+
17
+ def compute_metrics(self, eval_pred):
18
+ """
19
+ Compute metrics using efficient NumPy operations.
20
+ """
21
+ predictions, labels = eval_pred
22
+
23
+ # Retrieve indices of all valid positions at once
24
+ valid_mask = labels != -100
25
+ valid_indices = np.where(valid_mask)
26
+
27
+ if len(valid_indices[0]) == 0:
28
+ return {
29
+ "accuracy": 0.0,
30
+ "precision": 0.0,
31
+ "recall": 0.0,
32
+ "f1": 0.0,
33
+ }
34
+
35
+ # Extract predictions and labels at valid positions only
36
+ valid_predictions = predictions[valid_indices]
37
+ valid_labels = labels[valid_indices]
38
+
39
+ # Predicted classes
40
+ pred_classes = np.argmax(valid_predictions, axis=1)
41
+
42
+ # Accuracy
43
+ accuracy = np.mean(pred_classes == valid_labels)
44
+
45
+ # Manually compute binary classification metrics
46
+ tp = np.sum((pred_classes == 1) & (valid_labels == 1))
47
+ fp = np.sum((pred_classes == 1) & (valid_labels == 0))
48
+ fn = np.sum((pred_classes == 0) & (valid_labels == 1))
49
+
50
+ precision = tp / (tp + fp) if (tp + fp) > 0 else 0.0
51
+ recall = tp / (tp + fn) if (tp + fn) > 0 else 0.0
52
+ f1 = (
53
+ 2 * precision * recall / (precision + recall)
54
+ if (precision + recall) > 0
55
+ else 0.0
56
+ )
57
+
58
+ return {
59
+ "accuracy": accuracy,
60
+ "precision": precision,
61
+ "recall": recall,
62
+ "f1": f1,
63
+ }
64
+
65
+
66
+ class BPTrainer(Trainer):
67
+ """Base-pair level trainer for k-mer tokenized DNA sequences."""
68
+ def __init__(self, processing_class=None, bp_loss_only=True, **kwargs):
69
+ kwargs.pop("tokenizer", None) # Remove deprecation warning
70
+ super().__init__(**kwargs)
71
+ self.dna_tokenizer = processing_class
72
+ self.bp_loss_only = bp_loss_only
73
+ # Class-level cache: built only once
74
+ self._special_ids = None
75
+ self._nucleotide_indices = None # [V, k] long
76
+ self._nucleotide_map = {'A': 0, 'T': 1, 'C': 2, 'G': 3}
77
+
78
+ # ------------------ Entry point ------------------
79
+ def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None):
80
+ labels = inputs.get("labels") # [B, S]
81
+ logits = model(**inputs).logits # [B, S, V]
82
+ shift_logits = logits[..., :-1, :].contiguous() # [B, S, V]
83
+ shift_labels = labels[..., 1:].contiguous() # [B, S]
84
+ device = shift_logits.device
85
+ k = self.dna_tokenizer.k
86
+
87
+ # 1. Build and cache special token IDs and nucleotide indices once
88
+ if self._special_ids is None:
89
+ self._build_static_cache(model, k)
90
+
91
+ ignore_ids = torch.tensor(
92
+ [
93
+ self.dna_tokenizer.unk_token_id,
94
+ self.dna_tokenizer.pad_token_id,
95
+ -100,
96
+ ],
97
+ device=device,
98
+ )
99
+ ignore_mask = torch.isin(shift_labels, ignore_ids)
100
+ shift_labels = shift_labels.masked_fill(ignore_mask, -100)
101
+
102
+ # 2. Masks
103
+ valid_mask = shift_labels != -100
104
+ special_mask = torch.isin(shift_labels, self._special_ids) & valid_mask
105
+ regular_mask = valid_mask & (~special_mask)
106
+
107
+ # 3. Loss computation
108
+ if regular_mask.any():
109
+ bp_loss = self._marginal_bp_loss(
110
+ shift_logits, shift_labels, regular_mask, k, device
111
+ )
112
+ else:
113
+ bp_loss = torch.tensor(0.0, device=device)
114
+
115
+ if special_mask.any():
116
+ token_loss = F.cross_entropy(
117
+ shift_logits[special_mask],
118
+ shift_labels[special_mask],
119
+ ignore_index=-100,
120
+ reduction="mean",
121
+ )
122
+ token_loss = token_loss / k
123
+ else:
124
+ token_loss = torch.tensor(0.0, device=device)
125
+
126
+ # 4. Weighted combination
127
+ bp_count = regular_mask.sum()
128
+ special_count = special_mask.sum()
129
+ total = bp_count + special_count
130
+ if total == 0:
131
+ total_loss = torch.tensor(0.0, device=device)
132
+ else:
133
+ total_loss = (bp_loss * bp_count + token_loss * special_count) / total
134
+
135
+ total_loss = total_loss / self.args.gradient_accumulation_steps
136
+
137
+ if self.bp_loss_only:
138
+ return (bp_loss, logits) if return_outputs else bp_loss
139
+
140
+ return (total_loss, logits) if return_outputs else total_loss
141
+
142
+ # ------------------ Static cache (executed once) ------------------
143
+ def _build_static_cache(self, model, k):
144
+ # Unwrap the actual model if wrapped by DDP
145
+ if hasattr(model, "module"):
146
+ model = model.module
147
+
148
+ vocab_size = model.config.vocab_size
149
+ device = model.device
150
+ self._special_ids = torch.tensor(
151
+ [self.dna_tokenizer.vocab[e] for e in self.dna_tokenizer.special_tokens],
152
+ dtype=torch.long,
153
+ device=device,
154
+ )
155
+
156
+ # 2. Nucleotide indices [V, k], tensorized once
157
+ indices = torch.zeros(vocab_size, k, dtype=torch.long, device=device)
158
+ for tid in range(vocab_size):
159
+ tok = self.dna_tokenizer.ids_to_tokens[tid]
160
+ if tok in self.dna_tokenizer.special_tokens:
161
+ indices[tid] = 0
162
+ else:
163
+ seq = tok[:k]
164
+ idx = [self._nucleotide_map.get(c, 0) for c in seq]
165
+ indices[tid] = torch.tensor(idx, dtype=torch.long, device=device)
166
+ self._nucleotide_indices = indices
167
+
168
+ # ------------------ Marginal BP loss (no Python loops over tokens) ------------------
169
+ def _marginal_bp_loss(self, shift_logits, shift_labels, regular_mask, k, device):
170
+ token_probs = F.softmax(shift_logits, dim=-1) # [B, S, V]
171
+ bp_loss = torch.tensor(0.0, device=device)
172
+
173
+ for pos in range(k):
174
+ # 1. Ground-truth nucleotide index at this position [B, S]
175
+ target_nt = self._nucleotide_indices[
176
+ shift_labels, pos
177
+ ].masked_fill(~regular_mask, -100)
178
+
179
+ # 2. Construct 4-class marginal probabilities [B, S, 4]
180
+ marginal_probs = torch.zeros(
181
+ *shift_logits.shape[:2], 4, device=device
182
+ )
183
+
184
+ # 3. Aggregate probabilities via scatter-style summation
185
+ src_indices = self._nucleotide_indices[:, pos] # [V], values in [0, 3]
186
+ for nt_idx in range(4):
187
+ mask = src_indices == nt_idx # [V]
188
+ marginal_probs[..., nt_idx] = token_probs[..., mask].sum(dim=-1)
189
+
190
+ marginal_probs = marginal_probs.clamp(min=1e-8)
191
+ log_marginal_probs = marginal_probs.log()
192
+
193
+ # 4. Single-step NLL loss
194
+ pos_loss = F.nll_loss(
195
+ log_marginal_probs.view(-1, 4),
196
+ target_nt.view(-1),
197
+ ignore_index=-100,
198
+ reduction="mean",
199
+ )
200
+ bp_loss += pos_loss
201
+
202
+ return bp_loss / k
fsdp_config_generanno.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "auto_wrap_policy": "TRANSFORMER_BASED_WRAP",
3
+ "backward_prefetch_policy": "BACKWARD_PRE",
4
+ "cpu_ram_efficient_loading": "true",
5
+ "forward_prefetch": "false",
6
+ "offload_params": "false",
7
+ "sharding_strategy": "SHARD_GRAD_OP",
8
+ "state_dict_type": "SHARDED_STATE_DICT",
9
+ "sync_module_states": "true",
10
+ "transformer_layer_cls_to_wrap": "GenerannoEncoderLayer",
11
+ "use_orig_params": "true"
12
+ }
h5_dataset.py ADDED
@@ -0,0 +1,261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import h5py
2
+ import os
3
+ import torch
4
+ import numpy as np
5
+ from torch.utils.data import Dataset
6
+
7
+
8
+ class HDF5TokenizedDataset(Dataset):
9
+ """
10
+ Generic HDF5 dataset supporting multiple tasks and multiple data sources:
11
+ - Language modeling (labels = input_ids)
12
+ - Genome annotation (labels loaded from HDF5 files)
13
+ """
14
+ def __init__(self, data_dir, task_type="language_modeling", max_length=16384, k=6):
15
+ """
16
+ Args:
17
+ data_dir: A single directory path (str) or multiple directory paths (list/tuple)
18
+ max_length: Maximum sequence length
19
+ task_type: Task type
20
+ - "language_modeling": language modeling, labels = input_ids
21
+ - "annotation": genome annotation, labels read from HDF5
22
+ k: k-mer length
23
+ """
24
+ self.task_type = task_type
25
+ self.max_length = max_length
26
+ self.k = k
27
+
28
+ # Unified handling of single / multiple data sources
29
+ if isinstance(data_dir, str):
30
+ data_dirs = [data_dir]
31
+ elif isinstance(data_dir, list):
32
+ data_dirs = data_dir
33
+ else:
34
+ raise TypeError("data_dir must be a string path or a list of paths")
35
+
36
+ # Collect all HDF5 files
37
+ self.file_paths = []
38
+ for data_dir_path in data_dirs:
39
+ if not os.path.isdir(data_dir_path):
40
+ print(f"Warning: directory does not exist: {data_dir_path}")
41
+ continue
42
+
43
+ h5_files = [f for f in os.listdir(data_dir_path) if f.endswith(".h5")]
44
+ for h5_file in h5_files:
45
+ file_path = os.path.join(data_dir_path, h5_file)
46
+ self.file_paths.append(file_path)
47
+
48
+ if not self.file_paths:
49
+ raise ValueError(f"No HDF5 files found in: {data_dirs}")
50
+
51
+ # Build index mapping (original indexing logic)
52
+ self.total_samples = 0
53
+ self.file_offsets = []
54
+ for fp in self.file_paths:
55
+ with h5py.File(fp, "r") as f:
56
+ n = f["input_ids"].shape[0]
57
+ self.file_offsets.append((self.total_samples, n, fp))
58
+ self.total_samples += n
59
+
60
+ # Store data source information
61
+ self.data_dirs = data_dirs
62
+ self.is_multi_source = len(data_dirs) > 1
63
+
64
+ if self.is_multi_source:
65
+ print(
66
+ f"Multi-source loading: {len(data_dirs)} directories, "
67
+ f"{len(self.file_paths)} files, {self.total_samples} samples"
68
+ )
69
+ else:
70
+ print(
71
+ f"Single-source loading: {data_dirs[0]}, "
72
+ f"{len(self.file_paths)} files, {self.total_samples} samples"
73
+ )
74
+
75
+ def __len__(self):
76
+ return self.total_samples
77
+
78
+ def _find_file(self, idx):
79
+ low, high = 0, len(self.file_offsets)
80
+ while low < high:
81
+ mid = (low + high) // 2
82
+ start, size, _ = self.file_offsets[mid]
83
+ if idx < start:
84
+ high = mid
85
+ else:
86
+ low = mid + 1
87
+ file_idx = low - 1
88
+ start, size, path = self.file_offsets[file_idx]
89
+ return path, idx - start
90
+
91
+ def __getitem__(self, idx):
92
+ file_path, local_idx = self._find_file(idx)
93
+ with h5py.File(file_path, "r") as f:
94
+ input_ids = f["input_ids"][local_idx]
95
+
96
+ # Handle labels based on task type
97
+ if self.task_type == "annotation":
98
+ if "label_plus" in f and "label_minus" in f:
99
+ label_plus = f["label_plus"][local_idx]
100
+ label_minus = f["label_minus"][local_idx]
101
+ labels = np.concatenate([label_plus, label_minus])
102
+ labels = (labels != 0).astype(labels.dtype)
103
+ else:
104
+ labels = None
105
+ print(
106
+ f"Warning: 'label_plus' or 'label_minus' not found in {file_path}"
107
+ )
108
+ else:
109
+ labels = None
110
+
111
+ # Truncate input_ids if needed
112
+ if self.max_length is not None and len(input_ids) > self.max_length:
113
+ input_ids = input_ids[: self.max_length]
114
+ if self.task_type == "annotation" and labels is not None:
115
+ max_label_length = self.max_length * self.k
116
+ labels = labels[:max_label_length]
117
+
118
+ result = {
119
+ "input_ids": torch.tensor(input_ids, dtype=torch.long),
120
+ }
121
+
122
+ if self.task_type == "language_modeling":
123
+ result["labels"] = torch.tensor(input_ids, dtype=torch.long)
124
+ elif self.task_type == "annotation" and labels is not None:
125
+ result["labels"] = torch.tensor(labels, dtype=torch.long)
126
+
127
+ return result
128
+
129
+
130
+ class TokenizedCollator:
131
+ """
132
+ Collator for already-tokenized input_ids:
133
+ performs padding / truncation / label copying only.
134
+ attention_mask is generated on the fly (0 = pad, 1 = valid).
135
+ """
136
+ def __init__(self, tokenizer, max_length=16384, pad_to_multiple_of=None):
137
+ self.tokenizer = tokenizer
138
+ self.max_length = max_length
139
+ self.pad_to_multiple_of = pad_to_multiple_of
140
+
141
+ def __call__(self, examples):
142
+ # Use tokenizer for padding (attention_mask is generated automatically)
143
+ batch = self.tokenizer.pad(
144
+ examples,
145
+ padding="longest" if self.max_length is None else "max_length",
146
+ max_length=self.max_length,
147
+ return_tensors="pt",
148
+ pad_to_multiple_of=self.pad_to_multiple_of,
149
+ )
150
+ # Labels = input_ids (language modeling)
151
+ batch["labels"] = batch["input_ids"].clone()
152
+ return batch
153
+
154
+
155
+ class AnnotationDataCollator:
156
+ """
157
+ Collator for genome annotation tasks.
158
+ Handles padding of input_ids and corresponding padding of labels.
159
+ """
160
+ def __init__(
161
+ self,
162
+ tokenizer,
163
+ max_length=16384,
164
+ pad_to_multiple_of=None,
165
+ k=6,
166
+ num_prediction_heads=2,
167
+ ):
168
+ self.tokenizer = tokenizer
169
+ self.max_length = max_length
170
+ self.pad_to_multiple_of = pad_to_multiple_of
171
+ self.k = k # k-mer length
172
+ self.num_prediction_heads = num_prediction_heads
173
+
174
+ # Collect all special token IDs that should be ignored
175
+ self.special_token_ids = self._get_special_token_ids()
176
+
177
+ def _get_special_token_ids(self):
178
+ """Get all special token IDs to be ignored."""
179
+ special_tokens = ["<oov>", "<s>", "</s>", "<pad>", "<mask>"]
180
+ special_token_ids = self.tokenizer.convert_tokens_to_ids(special_tokens)
181
+ return special_token_ids
182
+
183
+ def _apply_special_token_mask(self, labels, input_ids):
184
+ """
185
+ Create a special-token mask and apply it to labels.
186
+ """
187
+ if not self.special_token_ids or labels is None:
188
+ return labels
189
+
190
+ batch_size, seq_len = input_ids.shape
191
+ device = input_ids.device
192
+
193
+ # Base special token mask [batch_size, seq_len]
194
+ special_tokens_tensor = torch.tensor(
195
+ self.special_token_ids, device=device
196
+ )
197
+ special_token_mask = torch.isin(input_ids, special_tokens_tensor)
198
+
199
+ # Expand each token by k [batch_size, seq_len * k]
200
+ special_token_mask_expanded = special_token_mask.repeat_interleave(
201
+ self.k, dim=1
202
+ )
203
+
204
+ # Duplicate for num_prediction_heads and concatenate
205
+ # [batch_size, seq_len * k * num_prediction_heads]
206
+ masks_list = []
207
+ for _ in range(self.num_prediction_heads):
208
+ masks_list.append(special_token_mask_expanded)
209
+ special_token_mask_final = torch.cat(masks_list, dim=1)
210
+
211
+ # Apply mask: set labels corresponding to special tokens to -100
212
+ labels[special_token_mask_final] = -100
213
+
214
+ return labels
215
+
216
+ def __call__(self, examples):
217
+ # Use tokenizer for padding (attention_mask is generated automatically)
218
+ batch = self.tokenizer.pad(
219
+ examples,
220
+ padding="longest" if self.max_length is None else "max_length",
221
+ max_length=self.max_length,
222
+ return_tensors="pt",
223
+ pad_to_multiple_of=self.pad_to_multiple_of,
224
+ )
225
+
226
+ # Process labels
227
+ if "labels" in examples[0]:
228
+ labels = [example["labels"] for example in examples]
229
+ batch["labels"] = self._pad_labels(
230
+ labels, batch["input_ids"].shape[1]
231
+ )
232
+ batch["labels"] = self._apply_special_token_mask(
233
+ batch["labels"], batch["input_ids"]
234
+ )
235
+ else:
236
+ raise ValueError(
237
+ "Labels not found in examples. This is required for training."
238
+ )
239
+
240
+ return batch
241
+
242
+ def _pad_labels(self, labels, padded_token_len):
243
+ batch_size = len(labels)
244
+ target_length = padded_token_len * self.k * self.num_prediction_heads
245
+
246
+ padded_labels = torch.full(
247
+ (batch_size, target_length), -100, dtype=torch.long
248
+ )
249
+
250
+ for i, label_seq in enumerate(labels):
251
+ if isinstance(label_seq, torch.Tensor):
252
+ label_seq = label_seq.tolist()
253
+
254
+ current_length = min(len(label_seq), target_length)
255
+ if current_length > 0:
256
+ # Direct assignment to avoid creating temporary tensors
257
+ padded_labels[i, :current_length] = torch.tensor(
258
+ label_seq[:current_length], dtype=torch.long
259
+ )
260
+
261
+ return padded_labels
modeling_generanno.py ADDED
@@ -0,0 +1,1849 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
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
+ import math
21
+ from dataclasses import dataclass
22
+ from typing import Optional, Tuple, Union, List, Any
23
+
24
+ import torch
25
+ import torch.nn.functional as F
26
+ from torch import nn, Tensor
27
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
28
+ from transformers.activations import ACT2FN
29
+ from transformers.modeling_attn_mask_utils import (
30
+ _prepare_4d_attention_mask_for_sdpa,
31
+ _prepare_4d_attention_mask
32
+ )
33
+
34
+ from transformers.modeling_outputs import (
35
+ ModelOutput,
36
+ TokenClassifierOutput,
37
+ BaseModelOutput,
38
+ MaskedLMOutput,
39
+ SequenceClassifierOutput,
40
+ CausalLMOutputWithPast
41
+ )
42
+
43
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
44
+ from transformers.modeling_utils import PreTrainedModel
45
+ from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS
46
+ from transformers.generation.utils import GenerationMixin
47
+ from transformers.utils import (
48
+ logging,
49
+ )
50
+
51
+ from configuration_generanno import GenerannoConfig
52
+
53
+ logger = logging.get_logger(__name__)
54
+
55
+ _CONFIG_FOR_DOC = "GenerannoConfig"
56
+
57
+ try:
58
+ from flash_attn import flash_attn_func
59
+ FLASH_ATTN_AVAILABLE = True
60
+ except ImportError:
61
+ FLASH_ATTN_AVAILABLE = False
62
+
63
+
64
+ class GenerannoRMSNorm(nn.Module):
65
+ def __init__(self, hidden_size, eps=1e-6):
66
+ """
67
+ GenerannoRMSNorm is equivalent to T5LayerNorm
68
+ """
69
+ super().__init__()
70
+ self.weight = nn.Parameter(torch.ones(hidden_size))
71
+ self.variance_epsilon = eps
72
+
73
+ def forward(self, hidden_states):
74
+ input_dtype = hidden_states.dtype
75
+ hidden_states = hidden_states.to(torch.float32)
76
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
77
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
78
+ return self.weight * hidden_states.to(input_dtype)
79
+
80
+ def extra_repr(self):
81
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
82
+
83
+
84
+ ALL_LAYERNORM_LAYERS.append(GenerannoRMSNorm)
85
+
86
+
87
+ class GenerannoRotaryEmbedding(nn.Module):
88
+ def __init__(
89
+ self,
90
+ dim=None,
91
+ max_position_embeddings=2048,
92
+ base=10000,
93
+ device=None,
94
+ scaling_factor=1.0,
95
+ rope_type="default",
96
+ config: Optional[GenerannoConfig] = None,
97
+ ):
98
+ super().__init__()
99
+ # TODO (joao): remove the `if` below, only used for BC
100
+ self.rope_kwargs = {}
101
+ if config is None:
102
+ logger.warning_once(
103
+ "`GenerannoRotaryEmbedding` can now be fully parameterized by passing the model config through the "
104
+ "`config` argument. All other arguments will be removed in v4.45"
105
+ )
106
+ self.rope_kwargs = {
107
+ "rope_type": rope_type,
108
+ "factor": scaling_factor,
109
+ "dim": dim,
110
+ "base": base,
111
+ "max_position_embeddings": max_position_embeddings,
112
+ }
113
+ self.rope_type = rope_type
114
+ self.max_seq_len_cached = max_position_embeddings
115
+ self.original_max_seq_len = max_position_embeddings
116
+ else:
117
+ # BC: "rope_type" was originally "type"
118
+ if config.rope_scaling is not None:
119
+ self.rope_type = config.rope_scaling.get(
120
+ "rope_type", config.rope_scaling.get("type")
121
+ )
122
+ else:
123
+ self.rope_type = "default"
124
+ self.max_seq_len_cached = config.max_position_embeddings
125
+ self.original_max_seq_len = config.max_position_embeddings
126
+
127
+ self.config = config
128
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
129
+
130
+ inv_freq, self.attention_scaling = self.rope_init_fn(
131
+ self.config, device, **self.rope_kwargs
132
+ )
133
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
134
+ self.original_inv_freq = self.inv_freq
135
+
136
+ def _dynamic_frequency_update(self, position_ids, device):
137
+ """
138
+ dynamic RoPE layers should recompute `inv_freq` in the following situations:
139
+ 1 - growing beyond the cached sequence length (allow scaling)
140
+ 2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
141
+ """
142
+ seq_len = torch.max(position_ids) + 1
143
+ if seq_len > self.max_seq_len_cached: # growth
144
+ inv_freq, self.attention_scaling = self.rope_init_fn(
145
+ self.config, device, seq_len=seq_len, **self.rope_kwargs
146
+ )
147
+ self.register_buffer(
148
+ "inv_freq", inv_freq, persistent=False
149
+ ) # TODO joao: may break with compilation
150
+ self.max_seq_len_cached = seq_len
151
+
152
+ if (
153
+ seq_len < self.original_max_seq_len
154
+ and self.max_seq_len_cached > self.original_max_seq_len
155
+ ): # reset
156
+ self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
157
+ self.max_seq_len_cached = self.original_max_seq_len
158
+
159
+ @torch.no_grad()
160
+ def forward(self, x, position_ids):
161
+ if "dynamic" in self.rope_type:
162
+ self._dynamic_frequency_update(position_ids, device=x.device)
163
+
164
+ # Core RoPE block
165
+ inv_freq_expanded = (
166
+ self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
167
+ )
168
+ position_ids_expanded = position_ids[:, None, :].float()
169
+ # Force float32 (see https://github.com/huggingface/transformers/pull/29285)
170
+ device_type = x.device.type
171
+ device_type = (
172
+ device_type
173
+ if isinstance(device_type, str) and device_type != "mps"
174
+ else "cpu"
175
+ )
176
+ with torch.autocast(device_type=device_type, enabled=False):
177
+ freqs = (
178
+ inv_freq_expanded.float() @ position_ids_expanded.float()
179
+ ).transpose(1, 2)
180
+ emb = torch.cat((freqs, freqs), dim=-1)
181
+ cos = emb.cos()
182
+ sin = emb.sin()
183
+
184
+ # Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
185
+ cos = cos * self.attention_scaling
186
+ sin = sin * self.attention_scaling
187
+
188
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
189
+
190
+
191
+ class GenerannoLinearScalingRotaryEmbedding(GenerannoRotaryEmbedding):
192
+ """GenerannoRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
193
+
194
+ def __init__(self, *args, **kwargs):
195
+ logger.warning_once(
196
+ "`GenerannoLinearScalingRotaryEmbedding` is deprecated an will be removed in v4.45. Please use "
197
+ "`GenerannoRotaryEmbedding`, which now also does linear scaling (simply pass the model config to __init__)."
198
+ )
199
+ kwargs["rope_type"] = "linear"
200
+ super().__init__(*args, **kwargs)
201
+
202
+
203
+ class GenerannoDynamicNTKScalingRotaryEmbedding(GenerannoRotaryEmbedding):
204
+ """GenerannoRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
205
+
206
+ def __init__(self, *args, **kwargs):
207
+ logger.warning_once(
208
+ "`GenerannoDynamicNTKScalingRotaryEmbedding` is deprecated an will be removed in v4.45. Please use "
209
+ "`GenerannoRotaryEmbedding`, which now also does dynamic ntk scaling (simply pass the model config to "
210
+ "__init__)."
211
+ )
212
+ kwargs["rope_type"] = "dynamic"
213
+ super().__init__(*args, **kwargs)
214
+
215
+
216
+ def rotate_half(x):
217
+ """Rotates half the hidden dims of the input."""
218
+ x1 = x[..., : x.shape[-1] // 2]
219
+ x2 = x[..., x.shape[-1] // 2 :]
220
+ return torch.cat((-x2, x1), dim=-1)
221
+
222
+
223
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
224
+ """Applies Rotary Position Embedding to the query and key tensors.
225
+
226
+ Args:
227
+ q (`torch.Tensor`): The query tensor.
228
+ k (`torch.Tensor`): The key tensor.
229
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
230
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
231
+ position_ids (`torch.Tensor`, *optional*):
232
+ Deprecated and unused.
233
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
234
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
235
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
236
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
237
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
238
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
239
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
240
+ Returns:
241
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
242
+ """
243
+ cos = cos.unsqueeze(unsqueeze_dim)
244
+ sin = sin.unsqueeze(unsqueeze_dim)
245
+ q_embed = (q * cos) + (rotate_half(q) * sin)
246
+ k_embed = (k * cos) + (rotate_half(k) * sin)
247
+ return q_embed, k_embed
248
+
249
+
250
+ class GenerannoMLP(nn.Module):
251
+ def __init__(self, config):
252
+ super().__init__()
253
+ self.config = config
254
+ self.hidden_size = config.hidden_size
255
+ self.intermediate_size = config.intermediate_size
256
+ self.gate_proj = nn.Linear(
257
+ self.hidden_size, self.intermediate_size, bias=config.mlp_bias
258
+ )
259
+ self.up_proj = nn.Linear(
260
+ self.hidden_size, self.intermediate_size, bias=config.mlp_bias
261
+ )
262
+ self.down_proj = nn.Linear(
263
+ self.intermediate_size, self.hidden_size, bias=config.mlp_bias
264
+ )
265
+ self.act_fn = ACT2FN[config.hidden_act]
266
+
267
+ def forward(self, x):
268
+ if self.config.pretraining_tp > 1:
269
+ slice = self.intermediate_size // self.config.pretraining_tp
270
+ gate_proj_slices = self.gate_proj.weight.split(slice, dim=0)
271
+ up_proj_slices = self.up_proj.weight.split(slice, dim=0)
272
+ down_proj_slices = self.down_proj.weight.split(slice, dim=1)
273
+
274
+ gate_proj = torch.cat(
275
+ [
276
+ F.linear(x, gate_proj_slices[i])
277
+ for i in range(self.config.pretraining_tp)
278
+ ],
279
+ dim=-1,
280
+ )
281
+ up_proj = torch.cat(
282
+ [
283
+ F.linear(x, up_proj_slices[i])
284
+ for i in range(self.config.pretraining_tp)
285
+ ],
286
+ dim=-1,
287
+ )
288
+
289
+ intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
290
+ down_proj = [
291
+ F.linear(intermediate_states[i], down_proj_slices[i])
292
+ for i in range(self.config.pretraining_tp)
293
+ ]
294
+ down_proj = sum(down_proj)
295
+ else:
296
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
297
+
298
+ return down_proj
299
+
300
+
301
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
302
+ """
303
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
304
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
305
+ """
306
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
307
+ if n_rep == 1:
308
+ return hidden_states
309
+ hidden_states = hidden_states[:, :, None, :, :].expand(
310
+ batch, num_key_value_heads, n_rep, slen, head_dim
311
+ )
312
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
313
+
314
+
315
+ class GenerannoAttention(nn.Module):
316
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
317
+
318
+ def __init__(self, config: GenerannoConfig, layer_idx: Optional[int] = None):
319
+ super().__init__()
320
+ self.config = config
321
+ self.layer_idx = layer_idx
322
+ if layer_idx is None:
323
+ logger.warning_once(
324
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
325
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
326
+ "when creating this class."
327
+ )
328
+
329
+ self.attention_dropout = config.attention_dropout
330
+ self.hidden_size = config.hidden_size
331
+ self.num_heads = config.num_attention_heads
332
+ self.head_dim = self.hidden_size // self.num_heads
333
+ self.num_key_value_heads = config.num_key_value_heads
334
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
335
+ self.max_position_embeddings = config.max_position_embeddings
336
+ self.rope_theta = config.rope_theta
337
+
338
+ if (self.head_dim * self.num_heads) != self.hidden_size:
339
+ raise ValueError(
340
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
341
+ f" and `num_heads`: {self.num_heads})."
342
+ )
343
+
344
+ self.q_proj = nn.Linear(
345
+ self.hidden_size,
346
+ self.num_heads * self.head_dim,
347
+ bias=config.attention_bias
348
+ )
349
+ self.k_proj = nn.Linear(
350
+ self.hidden_size,
351
+ self.num_key_value_heads * self.head_dim,
352
+ bias=config.attention_bias,
353
+ )
354
+ self.v_proj = nn.Linear(
355
+ self.hidden_size,
356
+ self.num_key_value_heads * self.head_dim,
357
+ bias=config.attention_bias,
358
+ )
359
+ self.o_proj = nn.Linear(
360
+ self.hidden_size, self.hidden_size, bias=config.attention_bias
361
+ )
362
+
363
+ self.rotary_emb = GenerannoRotaryEmbedding(config=self.config)
364
+
365
+ def forward(
366
+ self,
367
+ hidden_states: torch.Tensor,
368
+ attention_mask: Optional[torch.Tensor] = None, # 期望是 4D additive mask: (bsz,1,q_len,k_len) 或 None
369
+ position_ids: Optional[torch.LongTensor] = None,
370
+ output_attentions: bool = False,
371
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
372
+ is_causal: bool = False,
373
+ **kwargs,
374
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
375
+ bsz, q_len, _ = hidden_states.size()
376
+
377
+ if self.config.pretraining_tp > 1:
378
+ key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp
379
+ query_slices = self.q_proj.weight.split(
380
+ (self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
381
+ )
382
+ key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
383
+ value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
384
+
385
+ query_states = torch.cat([F.linear(hidden_states, query_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1)
386
+ key_states = torch.cat([F.linear(hidden_states, key_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1)
387
+ value_states = torch.cat([F.linear(hidden_states, value_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1)
388
+ else:
389
+ query_states = self.q_proj(hidden_states)
390
+ key_states = self.k_proj(hidden_states)
391
+ value_states = self.v_proj(hidden_states)
392
+
393
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
394
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
395
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
396
+
397
+ if position_embeddings is None:
398
+ logger.warning_once(
399
+ "The attention layers in this model are transitioning from computing the RoPE embeddings internally "
400
+ "through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
401
+ "`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.45 `position_ids` will be "
402
+ "removed and `position_embeddings` will be mandatory."
403
+ )
404
+ cos, sin = self.rotary_emb(value_states, position_ids)
405
+ else:
406
+ cos, sin = position_embeddings
407
+
408
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
409
+
410
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
411
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
412
+
413
+ # (bsz, heads, q_len, k_len)
414
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
415
+
416
+ # ✅ 1) eager/manual 自己加 causal 上三角 mask(防止未来信息泄露)
417
+ if is_causal:
418
+ # 这里 k_len == q_len(无 KV cache 时)
419
+ k_len = attn_weights.size(-1)
420
+ causal = torch.full((q_len, k_len), float("-inf"), device=attn_weights.device, dtype=attn_weights.dtype)
421
+ causal = torch.triu(causal, diagonal=1) # 上三角为 -inf
422
+ attn_weights = attn_weights + causal # broadcast 到 (bsz, heads, q_len, k_len)
423
+
424
+ # ✅ 2) 加 padding / 外部 mask(如果提供的是 4D additive mask)
425
+ if attention_mask is not None:
426
+ attn_weights = attn_weights + attention_mask
427
+
428
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
429
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
430
+
431
+ attn_output = torch.matmul(attn_weights, value_states) # (bsz, heads, q_len, head_dim)
432
+
433
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
434
+ raise ValueError(
435
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is {attn_output.size()}"
436
+ )
437
+
438
+ attn_output = attn_output.transpose(1, 2).contiguous().reshape(bsz, q_len, -1)
439
+
440
+ if self.config.pretraining_tp > 1:
441
+ attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2)
442
+ o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1)
443
+ attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.config.pretraining_tp)])
444
+ else:
445
+ attn_output = self.o_proj(attn_output)
446
+
447
+ if not output_attentions:
448
+ attn_weights = None
449
+
450
+ return attn_output, attn_weights
451
+
452
+
453
+ class GenerannoSdpaAttention(GenerannoAttention):
454
+ """
455
+ Generanno attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
456
+ `GenerannoAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
457
+ SDPA API.
458
+ """
459
+
460
+ # Adapted from GenerannoAttention.forward
461
+ def forward(
462
+ self,
463
+ hidden_states: torch.Tensor,
464
+ attention_mask: Optional[torch.Tensor] = None, # None 或 4D additive mask
465
+ position_ids: Optional[torch.LongTensor] = None,
466
+ output_attentions: bool = False,
467
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
468
+ is_causal: bool = False,
469
+ **kwargs,
470
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
471
+ if output_attentions:
472
+ logger.warning_once(
473
+ "GenerannoModel is using GenerannoSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` "
474
+ "does not support `output_attentions=True`. Falling back to the manual attention implementation."
475
+ )
476
+ # ✅ 关键:把 is_causal 传下去,否则 NTP 会泄露未来
477
+ return super().forward(
478
+ hidden_states=hidden_states,
479
+ attention_mask=attention_mask,
480
+ position_ids=position_ids,
481
+ output_attentions=output_attentions,
482
+ position_embeddings=position_embeddings,
483
+ is_causal=is_causal,
484
+ )
485
+
486
+ bsz, q_len, _ = hidden_states.size()
487
+
488
+ query_states = self.q_proj(hidden_states)
489
+ key_states = self.k_proj(hidden_states)
490
+ value_states = self.v_proj(hidden_states)
491
+
492
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
493
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
494
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
495
+
496
+ if position_embeddings is None:
497
+ logger.warning_once(
498
+ "The attention layers in this model are transitioning from computing the RoPE embeddings internally "
499
+ "through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
500
+ "`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.45 `position_ids` will be "
501
+ "removed and `position_embeddings` will be mandatory."
502
+ )
503
+ cos, sin = self.rotary_emb(value_states, position_ids)
504
+ else:
505
+ cos, sin = position_embeddings
506
+
507
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
508
+
509
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
510
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
511
+
512
+ if query_states.device.type == "cuda" and attention_mask is not None:
513
+ query_states = query_states.contiguous()
514
+ key_states = key_states.contiguous()
515
+ value_states = value_states.contiguous()
516
+
517
+ # ✅ 如果 attention_mask 是 4D additive mask,就不要再同时 is_causal=True
518
+ # 因为我们在 model 侧会把 causal + padding 合并进这个 mask(下面第3部分会实现)
519
+ sdpa_is_causal = is_causal if attention_mask is None else False
520
+
521
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
522
+ query_states,
523
+ key_states,
524
+ value_states,
525
+ attn_mask=attention_mask,
526
+ dropout_p=self.attention_dropout if self.training else 0.0,
527
+ is_causal=sdpa_is_causal,
528
+ )
529
+
530
+ attn_output = attn_output.transpose(1, 2).contiguous().view(bsz, q_len, -1)
531
+ attn_output = self.o_proj(attn_output)
532
+
533
+ return attn_output, None
534
+
535
+
536
+ class GenerannoFlashAttention2(GenerannoSdpaAttention):
537
+ """
538
+ Generanno attention module using Flash Attention 2. This module inherits from
539
+ `GenerannoSdpaAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
540
+ Flash Attention 2 API.
541
+ """
542
+
543
+ def forward(
544
+ self,
545
+ hidden_states: torch.Tensor,
546
+ attention_mask: Optional[torch.Tensor] = None,
547
+ position_ids: Optional[torch.LongTensor] = None,
548
+ output_attentions: bool = False,
549
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
550
+ is_causal: bool = False,
551
+ **kwargs,
552
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
553
+ if output_attentions:
554
+ logger.warning_once(
555
+ "GenerannoModel is using GenerannoFlashAttention2, but `flash_attn_func` does not support `output_attentions=True`. Falling back to the manual attention implementation."
556
+ )
557
+ return super().forward( # 现在会回退到SDPA!
558
+ hidden_states=hidden_states,
559
+ attention_mask=attention_mask,
560
+ position_ids=position_ids,
561
+ output_attentions=output_attentions,
562
+ position_embeddings=position_embeddings,
563
+ is_causal=is_causal,
564
+ )
565
+
566
+ if not FLASH_ATTN_AVAILABLE:
567
+ raise ImportError("Flash Attention 2 is not available. Please install it via `pip install flash-attn --no-build-isolation`")
568
+
569
+ # 检查是否需要回退到SDPA(有padding的情况)
570
+ if attention_mask is not None:
571
+ # 检查是否有真正的padding
572
+ if not torch.all(attention_mask == 1):
573
+ logger.warning_once(
574
+ "GenerannoModel is using GenerannoFlashAttention2, but `flash_attn_func` does not support `attention_mask`. Falling back to the manual attention implementation."
575
+ )
576
+ return super().forward( # 调用父类SDPA的实现
577
+ hidden_states=hidden_states,
578
+ attention_mask=attention_mask,
579
+ position_ids=position_ids,
580
+ output_attentions=output_attentions,
581
+ position_embeddings=position_embeddings,
582
+ is_causal=is_causal,
583
+ )
584
+
585
+ # flash attenton 2 只处理不带padding的情况
586
+ bsz, q_len, _ = hidden_states.size()
587
+
588
+ query_states = self.q_proj(hidden_states)
589
+ key_states = self.k_proj(hidden_states)
590
+ value_states = self.v_proj(hidden_states)
591
+
592
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
593
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
594
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
595
+
596
+ if position_embeddings is None:
597
+ cos, sin = self.rotary_emb(value_states, position_ids)
598
+ else:
599
+ cos, sin = position_embeddings
600
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
601
+
602
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
603
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
604
+
605
+ # Flash Attention 2 expects (batch_size, seqlen, nheads, headdim)
606
+ query_states = query_states.transpose(1, 2)
607
+ key_states = key_states.transpose(1, 2)
608
+ value_states = value_states.transpose(1, 2)
609
+
610
+ # 确保张量是连续的
611
+ query_states = query_states.contiguous()
612
+ key_states = key_states.contiguous()
613
+ value_states = value_states.contiguous()
614
+
615
+ attn_output = flash_attn_func(
616
+ query_states,
617
+ key_states,
618
+ value_states,
619
+ dropout_p=self.attention_dropout if self.training else 0.0,
620
+ softmax_scale=1.0 / math.sqrt(self.head_dim),
621
+ causal=is_causal,
622
+ )
623
+
624
+ attn_output = attn_output.reshape(bsz, q_len, -1)
625
+ attn_output = self.o_proj(attn_output)
626
+
627
+ return attn_output, None
628
+
629
+ GENERANNO_ATTENTION_CLASSES = {
630
+ "eager": GenerannoAttention,
631
+ "sdpa": GenerannoSdpaAttention,
632
+ "flash_attention_2": GenerannoFlashAttention2,
633
+ }
634
+
635
+ class GenerannoEncoderLayer(nn.Module):
636
+ def __init__(self, config: GenerannoConfig, layer_idx: int):
637
+ super().__init__()
638
+ self.hidden_size = config.hidden_size
639
+
640
+ self.self_attn = GENERANNO_ATTENTION_CLASSES[config._attn_implementation](
641
+ config=config, layer_idx=layer_idx
642
+ )
643
+
644
+ self.mlp = GenerannoMLP(config)
645
+ self.input_layernorm = GenerannoRMSNorm(
646
+ config.hidden_size, eps=config.rms_norm_eps
647
+ )
648
+ self.post_attention_layernorm = GenerannoRMSNorm(
649
+ config.hidden_size, eps=config.rms_norm_eps
650
+ )
651
+
652
+ def forward(
653
+ self,
654
+ hidden_states: torch.Tensor,
655
+ attention_mask: Optional[torch.Tensor] = None,
656
+ position_ids: Optional[torch.LongTensor] = None,
657
+ output_attentions: Optional[bool] = False,
658
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
659
+ is_causal: bool = False,
660
+ **kwargs,
661
+ ) -> tuple[Tensor | Any]:
662
+ """
663
+ Args:
664
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
665
+ attention_mask (`torch.FloatTensor`, *optional*):
666
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
667
+ query_sequence_length, key_sequence_length)` if default attention is used.
668
+ output_attentions (`bool`, *optional*):
669
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
670
+ returned tensors for more detail.
671
+ position_embeddings (`Tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
672
+ Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
673
+ with `head_dim` being the embedding dimension of each attention head.
674
+ kwargs (`dict`, *optional*):
675
+ Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
676
+ into the model
677
+ """
678
+ residual = hidden_states
679
+
680
+ hidden_states = self.input_layernorm(hidden_states)
681
+
682
+ # Self Attention
683
+ hidden_states, self_attn_weights = self.self_attn(
684
+ hidden_states=hidden_states,
685
+ attention_mask=attention_mask,
686
+ position_ids=position_ids,
687
+ output_attentions=output_attentions,
688
+ position_embeddings=position_embeddings,
689
+ is_causal=is_causal,
690
+ **kwargs,
691
+ )
692
+ hidden_states = residual + hidden_states
693
+
694
+ # Fully Connected
695
+ residual = hidden_states
696
+ hidden_states = self.post_attention_layernorm(hidden_states)
697
+ hidden_states = self.mlp(hidden_states)
698
+ hidden_states = residual + hidden_states
699
+
700
+ outputs = (hidden_states,)
701
+
702
+ if output_attentions:
703
+ outputs += (self_attn_weights,)
704
+
705
+ return outputs
706
+
707
+
708
+ class GenerannoPreTrainedModel(PreTrainedModel):
709
+ config_class = GenerannoConfig
710
+ base_model_prefix = "model"
711
+ supports_gradient_checkpointing = True
712
+ _no_split_modules = ["GenerannoEncoderLayer"]
713
+ _supports_flash_attn_2 = True
714
+ _supports_sdpa = True
715
+
716
+ def _init_weights(self, module):
717
+ std = self.config.initializer_range
718
+
719
+ if isinstance(module, nn.Linear):
720
+ module.weight.data.normal_(mean=0.0, std=std)
721
+ if module.bias is not None:
722
+ module.bias.data.zero_()
723
+ elif isinstance(module, nn.Embedding):
724
+ module.weight.data.normal_(mean=0.0, std=std)
725
+ if module.padding_idx is not None:
726
+ module.weight.data[module.padding_idx].zero_()
727
+
728
+
729
+ class GenerannoModel(GenerannoPreTrainedModel):
730
+ """
731
+ Transformer encoder consisting of *config.num_hidden_layers* layers. Each layer is a [`GenerannoEncoderLayer`]
732
+
733
+ Args:
734
+ config: GenerannoConfig
735
+ """
736
+
737
+ def __init__(self, config: GenerannoConfig):
738
+ super().__init__(config)
739
+ self.pad_token_id = config.pad_token_id
740
+ self.vocab_size = config.vocab_size
741
+
742
+ self.embed_tokens = nn.Embedding(
743
+ config.vocab_size, config.hidden_size, self.pad_token_id
744
+ )
745
+ self.layers = nn.ModuleList(
746
+ [
747
+ GenerannoEncoderLayer(config, layer_idx)
748
+ for layer_idx in range(config.num_hidden_layers)
749
+ ]
750
+ )
751
+ self.norm = GenerannoRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
752
+ self.rotary_emb = GenerannoRotaryEmbedding(config=config)
753
+ self.gradient_checkpointing = getattr(config, "gradient_checkpointing", False)
754
+ self.target_dtype = self.embed_tokens.weight.dtype
755
+
756
+ # Initialize weights and apply final processing
757
+ self.post_init()
758
+
759
+ # 添加gradient_checkpointing_enable方法供Trainer调用
760
+ def gradient_checkpointing_enable(self, gradient_checkpointing_kwargs=None):
761
+ if gradient_checkpointing_kwargs is None:
762
+ gradient_checkpointing_kwargs = {}
763
+
764
+ self.gradient_checkpointing = True
765
+ # 确保配置一致性
766
+ self.config.gradient_checkpointing = True
767
+
768
+ # 调用父类的方法来设置_gradient_checkpointing_func
769
+ if hasattr(super(), 'gradient_checkpointing_enable'):
770
+ super().gradient_checkpointing_enable(gradient_checkpointing_kwargs=gradient_checkpointing_kwargs)
771
+
772
+ def get_input_embeddings(self):
773
+ return self.embed_tokens
774
+
775
+ def set_input_embeddings(self, value):
776
+ self.embed_tokens = value
777
+
778
+ def _prepare_attention_mask(self, attention_mask, inputs_embeds, is_causal: bool):
779
+ attn_impl = self.config._attn_implementation
780
+ seq_len = inputs_embeds.shape[1]
781
+ device = inputs_embeds.device
782
+ dtype = self.target_dtype
783
+
784
+ # helper: 生成 4D causal additive mask (1,1,seq,seq)
785
+ def _make_4d_causal_mask():
786
+ m = torch.full((seq_len, seq_len), float("-inf"), device=device, dtype=dtype)
787
+ m = torch.triu(m, diagonal=1) # upper triangle -inf
788
+ return m.view(1, 1, seq_len, seq_len)
789
+
790
+ # 情况1: eager/manual:返回 padding 4D mask(causal 在 attention.forward 里加)
791
+ if attn_impl == "eager":
792
+ if attention_mask is None:
793
+ attention_mask = torch.ones_like(inputs_embeds[:, :, 0])
794
+ return _prepare_4d_attention_mask(attention_mask, dtype, tgt_len=seq_len)
795
+
796
+ # 情况2: sdpa/flash
797
+ elif attn_impl in ["sdpa", "flash_attention_2"]:
798
+ if (attention_mask is None) or torch.all(attention_mask == 1):
799
+ # ✅ 无 padding:让 SDPA/Flash 用 is_causal 处理 causal
800
+ return None
801
+
802
+ # 有 padding:先做 padding 4D additive mask
803
+ pad_4d = _prepare_4d_attention_mask_for_sdpa(attention_mask, dtype, tgt_len=seq_len)
804
+
805
+ if is_causal:
806
+ # ✅ 合并 causal + padding,确保 SDPA 在 mask!=None 时也严格 causal
807
+ return pad_4d + _make_4d_causal_mask()
808
+ else:
809
+ return pad_4d
810
+
811
+ else:
812
+ raise ValueError(f"Unsupported attention implementation: {attn_impl}")
813
+
814
+ def forward(
815
+ self,
816
+ input_ids: torch.LongTensor = None,
817
+ attention_mask: Optional[torch.Tensor] = None,
818
+ noise_mask: Optional[torch.Tensor] = None,
819
+ position_ids: Optional[torch.LongTensor] = None,
820
+ inputs_embeds: Optional[torch.FloatTensor] = None,
821
+ output_attentions: Optional[bool] = None,
822
+ output_hidden_states: Optional[bool] = None,
823
+ return_dict: Optional[bool] = None,
824
+ is_causal: bool = False,
825
+ ) -> tuple[tuple, ...] | BaseModelOutput:
826
+
827
+ output_attentions = (
828
+ output_attentions
829
+ if output_attentions is not None
830
+ else self.config.output_attentions
831
+ )
832
+ output_hidden_states = (
833
+ output_hidden_states
834
+ if output_hidden_states is not None
835
+ else self.config.output_hidden_states
836
+ )
837
+ return_dict = (
838
+ return_dict
839
+ if return_dict is not None
840
+ else self.config.use_return_dict
841
+ )
842
+
843
+ if (input_ids is None) ^ (inputs_embeds is not None):
844
+ raise ValueError(
845
+ "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
846
+ )
847
+
848
+ if inputs_embeds is None:
849
+ inputs_embeds = self.embed_tokens(input_ids)
850
+
851
+ # ========== 添加noise_mask处理 ==========
852
+ if noise_mask is not None:
853
+ # 如果有noise_mask,则应用zero_mask_embedding,将mask位置的embedding置零
854
+ batch_size, seq_len = inputs_embeds.shape[:2] # [batch_size, seq_len, hidden_size]
855
+
856
+ # 验证noise_mask形状
857
+ if noise_mask.dim() != 2:
858
+ raise ValueError(f"noise_mask应该是2D tensor [batch_size, seq_len],但得到的是{noise_mask.shape}")
859
+
860
+ if noise_mask.shape[0] != batch_size:
861
+ raise ValueError(f"noise_mask的batch_size不匹配:{noise_mask.shape[0]} != {batch_size}")
862
+
863
+ if noise_mask.shape[1] != seq_len:
864
+ raise ValueError(f"noise_mask的seq_len不匹配:{noise_mask.shape[1]} != {seq_len}")
865
+
866
+ # 应用noise_mask:将mask位置的embedding置零
867
+ noise_mask_float = (noise_mask == 1).unsqueeze(-1).float() # [batch, seq_len, 1]
868
+ inputs_embeds = inputs_embeds * (1 - noise_mask_float)
869
+
870
+ # 或者用torch.where,可以稍微节约显存
871
+ # zero = torch.tensor(0.0, device=inputs_embeds.device, dtype=inputs_embeds.dtype)
872
+ # inputs_embeds = torch.where(noise_mask.unsqueeze(-1), zero, inputs_embeds)
873
+ # =======================================
874
+
875
+ if position_ids is None:
876
+ position_ids = torch.arange(
877
+ 0, inputs_embeds.shape[1], device=inputs_embeds.device
878
+ ).unsqueeze(0)
879
+
880
+ attention_mask = self._prepare_attention_mask(attention_mask, inputs_embeds, is_causal=is_causal)
881
+
882
+ hidden_states = inputs_embeds
883
+
884
+ # create position embeddings to be shared across the encoder layers
885
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
886
+
887
+ # encoder layers
888
+ all_hidden_states = () if output_hidden_states else None
889
+ all_self_attns = () if output_attentions else None
890
+
891
+ for encoder_layer in self.layers:
892
+ if output_hidden_states:
893
+ all_hidden_states += (hidden_states,)
894
+
895
+ if self.gradient_checkpointing and self.training:
896
+ layer_outputs = self._gradient_checkpointing_func(
897
+ encoder_layer.__call__,
898
+ hidden_states,
899
+ attention_mask,
900
+ position_ids,
901
+ output_attentions,
902
+ position_embeddings,
903
+ is_causal, # 传递参数
904
+ )
905
+ else:
906
+ layer_outputs = encoder_layer(
907
+ hidden_states,
908
+ attention_mask=attention_mask,
909
+ position_ids=position_ids,
910
+ output_attentions=output_attentions,
911
+ position_embeddings=position_embeddings,
912
+ is_causal=is_causal, # 传递参数
913
+ )
914
+
915
+ hidden_states = layer_outputs[0]
916
+
917
+ if output_attentions:
918
+ all_self_attns += (layer_outputs[1],)
919
+
920
+ hidden_states = self.norm(hidden_states)
921
+
922
+ # add hidden states from the last encoder layer
923
+ if output_hidden_states:
924
+ all_hidden_states += (hidden_states,)
925
+
926
+ if not return_dict:
927
+ return tuple(
928
+ v
929
+ for v in [hidden_states, all_hidden_states, all_self_attns]
930
+ if v is not None
931
+ )
932
+ return BaseModelOutput(
933
+ last_hidden_state=hidden_states,
934
+ hidden_states=all_hidden_states,
935
+ attentions=all_self_attns,
936
+ )
937
+
938
+
939
+ class GenerannoForMaskedLM(GenerannoPreTrainedModel):
940
+ _tied_weights_keys = ["lm_head.weight"]
941
+
942
+ def __init__(self, config):
943
+ super().__init__(config)
944
+
945
+ self.model = GenerannoModel(config)
946
+ self.vocab_size = config.vocab_size
947
+
948
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
949
+ # self.lm_head.weight = self.model.embed_tokens.weight
950
+
951
+ # self.init_weights()
952
+ self.post_init()
953
+
954
+ def get_input_embeddings(self):
955
+ return self.model.embed_tokens
956
+
957
+ def set_input_embeddings(self, value):
958
+ self.model.embed_tokens = value
959
+
960
+ def get_output_embeddings(self):
961
+ return self.lm_head
962
+
963
+ def set_output_embeddings(self, new_embeddings):
964
+ self.lm_head = new_embeddings
965
+
966
+ def set_encoder(self, encoder):
967
+ self.model = encoder
968
+
969
+ def get_encoder(self):
970
+ return self.model
971
+
972
+ def forward(
973
+ self,
974
+ input_ids: torch.LongTensor = None,
975
+ attention_mask: Optional[torch.Tensor] = None,
976
+ noise_mask: Optional[torch.Tensor] = None,
977
+ position_ids: Optional[torch.LongTensor] = None,
978
+ inputs_embeds: Optional[torch.FloatTensor] = None,
979
+ labels: Optional[torch.LongTensor] = None,
980
+ output_attentions: Optional[bool] = None,
981
+ output_hidden_states: Optional[bool] = None,
982
+ return_dict: Optional[bool] = None,
983
+ ) -> Union[Tuple, MaskedLMOutput]:
984
+ r"""
985
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
986
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
987
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
988
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
989
+ kwargs (`Dict[str, any]`, *optional*, defaults to `{}`):
990
+ Used to hide legacy arguments that have been deprecated.
991
+ """
992
+ return_dict = (
993
+ return_dict if return_dict is not None else self.config.use_return_dict
994
+ )
995
+
996
+ outputs = self.model(
997
+ input_ids,
998
+ attention_mask=attention_mask,
999
+ noise_mask=noise_mask,
1000
+ position_ids=position_ids,
1001
+ inputs_embeds=inputs_embeds,
1002
+ output_attentions=output_attentions,
1003
+ output_hidden_states=output_hidden_states,
1004
+ return_dict=return_dict,
1005
+ )
1006
+ hidden_states = outputs[0]
1007
+ if self.config.pretraining_tp > 1:
1008
+ lm_head_slices = self.lm_head.weight.split(
1009
+ self.vocab_size // self.config.pretraining_tp, dim=0
1010
+ )
1011
+ logits = [
1012
+ F.linear(hidden_states, lm_head_slices[i])
1013
+ for i in range(self.config.pretraining_tp)
1014
+ ]
1015
+ logits = torch.cat(logits, dim=-1)
1016
+ else:
1017
+ logits = self.lm_head(hidden_states)
1018
+
1019
+ masked_lm_loss = None
1020
+ if labels is not None:
1021
+ loss_fct = CrossEntropyLoss()
1022
+
1023
+ labels = labels.to(logits.device)
1024
+ masked_lm_loss = loss_fct(
1025
+ logits.view(-1, self.config.vocab_size).float(), labels.view(-1)
1026
+ )
1027
+
1028
+ if not return_dict:
1029
+ output = (logits,) + outputs[2:]
1030
+ return (
1031
+ ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
1032
+ )
1033
+
1034
+ return MaskedLMOutput(
1035
+ loss=masked_lm_loss,
1036
+ logits=logits,
1037
+ hidden_states=outputs.hidden_states,
1038
+ attentions=outputs.attentions,
1039
+ )
1040
+
1041
+
1042
+ class GenerannoForCausalLM(GenerannoPreTrainedModel, GenerationMixin):
1043
+ _tied_weights_keys = ["lm_head.weight"]
1044
+
1045
+ def __init__(self, config: GenerannoConfig):
1046
+ super().__init__(config)
1047
+ self.model = GenerannoModel(config)
1048
+ self.vocab_size = config.vocab_size
1049
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1050
+
1051
+ # 可选:tie weights(推荐)
1052
+ # self.lm_head.weight = self.model.embed_tokens.weight
1053
+
1054
+ # 没实现 KV cache 前,建议关掉 use_cache,避免 generate 误以为你会返回 past_key_values
1055
+ if not hasattr(self.config, "use_cache"):
1056
+ self.config.use_cache = False
1057
+
1058
+ self.post_init()
1059
+
1060
+ def get_input_embeddings(self):
1061
+ return self.model.embed_tokens
1062
+
1063
+ def set_input_embeddings(self, value):
1064
+ self.model.embed_tokens = value
1065
+
1066
+ def get_output_embeddings(self):
1067
+ return self.lm_head
1068
+
1069
+ def set_output_embeddings(self, new_embeddings):
1070
+ self.lm_head = new_embeddings
1071
+
1072
+ def forward(
1073
+ self,
1074
+ input_ids: torch.LongTensor = None,
1075
+ attention_mask: Optional[torch.Tensor] = None,
1076
+ position_ids: Optional[torch.LongTensor] = None,
1077
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1078
+ labels: Optional[torch.LongTensor] = None,
1079
+ use_cache: Optional[bool] = None, # 兼容 generate
1080
+ past_key_values: Optional[Tuple] = None, # 兼容 generate(但我们不使用)
1081
+ output_attentions: Optional[bool] = None,
1082
+ output_hidden_states: Optional[bool] = None,
1083
+ return_dict: Optional[bool] = None,
1084
+ **kwargs,
1085
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1086
+
1087
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1088
+
1089
+ outputs = self.model(
1090
+ input_ids=input_ids,
1091
+ attention_mask=attention_mask,
1092
+ position_ids=position_ids,
1093
+ inputs_embeds=inputs_embeds,
1094
+ output_attentions=output_attentions,
1095
+ output_hidden_states=output_hidden_states,
1096
+ return_dict=True,
1097
+ is_causal=True, # ✅ 关键
1098
+ )
1099
+
1100
+ hidden_states = outputs.last_hidden_state
1101
+
1102
+ if self.config.pretraining_tp > 1:
1103
+ lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
1104
+ logits = torch.cat([F.linear(hidden_states, s) for s in lm_head_slices], dim=-1)
1105
+ else:
1106
+ logits = self.lm_head(hidden_states)
1107
+
1108
+ loss = None
1109
+ if labels is not None:
1110
+ # 标准 next-token prediction
1111
+ shift_logits = logits[..., :-1, :].contiguous()
1112
+ shift_labels = labels[..., 1:].contiguous().to(shift_logits.device)
1113
+ loss_fct = CrossEntropyLoss(ignore_index=-100)
1114
+ loss = loss_fct(
1115
+ shift_logits.view(-1, self.config.vocab_size).float(),
1116
+ shift_labels.view(-1),
1117
+ )
1118
+
1119
+ past = None # 目前不返回 cache
1120
+
1121
+ if not return_dict:
1122
+ output = (logits, past, outputs.hidden_states, outputs.attentions)
1123
+ return ((loss,) + output) if loss is not None else output
1124
+
1125
+ return CausalLMOutputWithPast(
1126
+ loss=loss,
1127
+ logits=logits,
1128
+ past_key_values=past,
1129
+ hidden_states=outputs.hidden_states,
1130
+ attentions=outputs.attentions,
1131
+ )
1132
+
1133
+ def prepare_inputs_for_generation(
1134
+ self,
1135
+ input_ids: torch.LongTensor,
1136
+ past_key_values: Optional[Tuple] = None,
1137
+ attention_mask: Optional[torch.Tensor] = None,
1138
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1139
+ **kwargs,
1140
+ ):
1141
+ """
1142
+ 不实现 KV cache 的正确版本:
1143
+ - 每一步都喂完整 prefix(慢但正确)
1144
+ - position_ids 用 attention_mask 累加生成,兼容 padding
1145
+ """
1146
+ if attention_mask is None:
1147
+ attention_mask = torch.ones_like(input_ids)
1148
+
1149
+ position_ids = attention_mask.long().cumsum(-1) - 1
1150
+ position_ids = position_ids.masked_fill(attention_mask == 0, 0)
1151
+
1152
+ if inputs_embeds is not None and past_key_values is None:
1153
+ return {
1154
+ "inputs_embeds": inputs_embeds,
1155
+ "attention_mask": attention_mask,
1156
+ "position_ids": position_ids,
1157
+ }
1158
+
1159
+ return {
1160
+ "input_ids": input_ids,
1161
+ "attention_mask": attention_mask,
1162
+ "position_ids": position_ids,
1163
+ }
1164
+
1165
+ @staticmethod
1166
+ def _reorder_cache(past_key_values, beam_idx):
1167
+ return past_key_values
1168
+
1169
+
1170
+ class GenerannoForSequenceClassification(GenerannoPreTrainedModel):
1171
+ def __init__(self, config):
1172
+ super().__init__(config)
1173
+ self.num_labels = config.num_labels
1174
+ self.config = config
1175
+
1176
+ self.model = GenerannoModel(config)
1177
+ self.feature_layer = getattr(config, "feature_layer", -1)
1178
+ self.use_mean_pooling = getattr(config, "use_mean_pooling", True)
1179
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1180
+ if getattr(config, "use_mlp_classifier", False):
1181
+ self.score = nn.Sequential(
1182
+ nn.Linear(config.hidden_size, config.hidden_size),
1183
+ nn.GELU(),
1184
+ nn.Dropout(0.1),
1185
+ nn.Linear(config.hidden_size, self.num_labels, bias=False),
1186
+ )
1187
+
1188
+ # Initialize weights and apply final processing
1189
+ self.post_init()
1190
+
1191
+ def _apply_mean_pooling(self, hidden_states, attention_mask):
1192
+ if attention_mask is None:
1193
+ return torch.mean(hidden_states, dim=1)
1194
+
1195
+ # Expand attention mask to match hidden states dimensions
1196
+ input_mask_expanded = attention_mask.unsqueeze(-1).expand(hidden_states.size()).float()
1197
+ sum_embeddings = torch.sum(hidden_states * input_mask_expanded, dim=1)
1198
+
1199
+ # Compute number of valid tokens per sequence
1200
+ sum_mask = input_mask_expanded.sum(dim=1)
1201
+ sum_mask = torch.clamp(sum_mask, min=1e-9)
1202
+
1203
+ # Compute mean
1204
+ pooled_output = sum_embeddings / sum_mask
1205
+
1206
+ return pooled_output
1207
+
1208
+ def forward(
1209
+ self,
1210
+ input_ids: Optional[torch.LongTensor] = None,
1211
+ attention_mask: Optional[torch.Tensor] = None,
1212
+ position_ids: Optional[torch.LongTensor] = None,
1213
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1214
+ labels: Optional[torch.LongTensor] = None,
1215
+ output_attentions: Optional[bool] = None,
1216
+ output_hidden_states: Optional[bool] = None,
1217
+ return_dict: Optional[bool] = None,
1218
+ ) -> Union[Tuple, SequenceClassifierOutput]:
1219
+ r"""
1220
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1221
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1222
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1223
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1224
+ """
1225
+ return_dict = (
1226
+ return_dict if return_dict is not None else self.config.use_return_dict
1227
+ )
1228
+
1229
+ if self.feature_layer == -1:
1230
+ outputs = self.model(
1231
+ input_ids,
1232
+ attention_mask=attention_mask,
1233
+ position_ids=position_ids,
1234
+ inputs_embeds=inputs_embeds,
1235
+ output_attentions=output_attentions,
1236
+ output_hidden_states=output_hidden_states,
1237
+ return_dict=return_dict,
1238
+ )
1239
+ hidden_states = outputs[0]
1240
+ else:
1241
+ outputs = self.model(
1242
+ input_ids,
1243
+ attention_mask=attention_mask,
1244
+ position_ids=position_ids,
1245
+ inputs_embeds=inputs_embeds,
1246
+ output_attentions=output_attentions,
1247
+ output_hidden_states=True,
1248
+ return_dict=return_dict,
1249
+ )
1250
+ hidden_states = outputs.hidden_states[self.feature_layer]
1251
+
1252
+ if self.use_mean_pooling:
1253
+ pooled_hidden_states = self._apply_mean_pooling(hidden_states, attention_mask)
1254
+ else:
1255
+ pooled_hidden_states = hidden_states[:, 0]
1256
+ logits = self.score(pooled_hidden_states)
1257
+
1258
+ loss = None
1259
+ if labels is not None:
1260
+ labels = labels.to(logits.device)
1261
+
1262
+ if self.config.problem_type is None:
1263
+ if self.num_labels == 1:
1264
+ self.config.problem_type = "regression"
1265
+ elif self.num_labels > 1 and (
1266
+ labels.dtype == torch.long or labels.dtype == torch.int
1267
+ ):
1268
+ self.config.problem_type = "single_label_classification"
1269
+ else:
1270
+ self.config.problem_type = "multi_label_classification"
1271
+
1272
+ if self.config.problem_type == "regression":
1273
+ loss_fct = MSELoss()
1274
+ if self.num_labels == 1:
1275
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
1276
+ else:
1277
+ loss = loss_fct(logits, labels)
1278
+ elif self.config.problem_type == "single_label_classification":
1279
+ loss_fct = CrossEntropyLoss()
1280
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1281
+ elif self.config.problem_type == "multi_label_classification":
1282
+ loss_fct = BCEWithLogitsLoss()
1283
+ loss = loss_fct(logits, labels)
1284
+ if not return_dict:
1285
+ output = (logits,)
1286
+ return ((loss,) + output) if loss is not None else output
1287
+
1288
+ return SequenceClassifierOutput(loss=loss, logits=logits)
1289
+
1290
+
1291
+ class GenerannoForTokenClassification(GenerannoPreTrainedModel):
1292
+ def __init__(self, config):
1293
+ super().__init__(config)
1294
+ self.num_labels = config.num_labels
1295
+ self.num_prediction_heads = getattr(config, "num_prediction_heads", 2)
1296
+ self.k = getattr(config, "k", 6)
1297
+
1298
+ self.model = GenerannoModel(config)
1299
+ self.feature_layer = getattr(config, "feature_layer", -1)
1300
+
1301
+ if self.num_prediction_heads > 1:
1302
+ self.score = nn.ModuleList()
1303
+ for _ in range(self.num_prediction_heads):
1304
+ if getattr(config, "use_mlp_classifier", False):
1305
+ head = nn.Sequential(
1306
+ nn.Linear(config.hidden_size, config.hidden_size),
1307
+ nn.GELU(),
1308
+ nn.Dropout(0.1),
1309
+ nn.Linear(config.hidden_size, self.num_labels * self.k, bias=False),
1310
+ )
1311
+ else:
1312
+ head = nn.Linear(config.hidden_size, self.num_labels * self.k, bias=False)
1313
+ self.score.append(head)
1314
+ else:
1315
+ if getattr(config, "use_mlp_classifier", False):
1316
+ self.score = nn.Sequential(
1317
+ nn.Linear(config.hidden_size, config.hidden_size),
1318
+ nn.GELU(),
1319
+ nn.Dropout(0.1),
1320
+ nn.Linear(config.hidden_size, self.num_labels * self.k, bias=False),
1321
+ )
1322
+ else:
1323
+ self.score = nn.Linear(config.hidden_size, self.num_labels * self.k, bias=False)
1324
+
1325
+ self.label_weights = (
1326
+ torch.tensor(config.label_weights)
1327
+ if hasattr(config, "label_weights")
1328
+ else None
1329
+ )
1330
+
1331
+ self.post_init()
1332
+
1333
+ def forward(
1334
+ self,
1335
+ input_ids: Optional[torch.LongTensor] = None,
1336
+ attention_mask: Optional[torch.Tensor] = None,
1337
+ position_ids: Optional[torch.LongTensor] = None,
1338
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1339
+ labels: Optional[torch.LongTensor] = None,
1340
+ output_attentions: Optional[bool] = None,
1341
+ output_hidden_states: Optional[bool] = None,
1342
+ return_dict: Optional[bool] = None,
1343
+ ) -> Union[Tuple, TokenClassifierOutput]:
1344
+ return_dict = (
1345
+ return_dict if return_dict is not None else self.config.use_return_dict
1346
+ )
1347
+
1348
+ if self.feature_layer == -1:
1349
+ outputs = self.model(
1350
+ input_ids,
1351
+ attention_mask=attention_mask,
1352
+ position_ids=position_ids,
1353
+ inputs_embeds=inputs_embeds,
1354
+ output_attentions=output_attentions,
1355
+ output_hidden_states=output_hidden_states,
1356
+ return_dict=return_dict,
1357
+ )
1358
+ hidden_states = outputs[0]
1359
+ else:
1360
+ outputs = self.model(
1361
+ input_ids,
1362
+ attention_mask=attention_mask,
1363
+ position_ids=position_ids,
1364
+ inputs_embeds=inputs_embeds,
1365
+ output_attentions=output_attentions,
1366
+ output_hidden_states=True,
1367
+ return_dict=return_dict,
1368
+ )
1369
+ hidden_states = outputs.hidden_states[self.feature_layer]
1370
+
1371
+ batch_size, padded_token_len, hidden_size = hidden_states.shape
1372
+
1373
+ if self.num_prediction_heads > 1:
1374
+ unpadded_token_lengths = attention_mask.sum(dim=1)
1375
+ all_logits_list = [head(hidden_states) for head in self.score]
1376
+
1377
+ # 最终预测位置数量 = padded_token_len * k * 头数
1378
+ total_prediction_positions = padded_token_len * self.k * self.num_prediction_heads
1379
+
1380
+ logits = hidden_states.new_full(
1381
+ (batch_size, total_prediction_positions, self.num_labels),
1382
+ fill_value=float("-inf"),
1383
+ )
1384
+
1385
+ for i in range(batch_size):
1386
+ actual_token_len = unpadded_token_lengths[i].item() # 当前样本的实际token数
1387
+ head_outputs = [
1388
+ logits_head[i, :actual_token_len] for logits_head in all_logits_list
1389
+ ]
1390
+
1391
+ reshaped_outputs = []
1392
+ for head_out in head_outputs:
1393
+ # head_out形状: [actual_token_len, num_labels * k]
1394
+ # 重塑为: [actual_token_len * k, num_labels]
1395
+ head_reshaped = head_out.view(actual_token_len * self.k, self.num_labels)
1396
+ reshaped_outputs.append(head_reshaped)
1397
+
1398
+ combined = torch.cat(reshaped_outputs, dim=0)
1399
+ total_combined_len = actual_token_len * self.k * self.num_prediction_heads
1400
+ logits[i, :total_combined_len] = combined
1401
+
1402
+ else:
1403
+ # 单头情况
1404
+ raw_logits = self.score(hidden_states)
1405
+ # raw_logits形状: [batch_size, padded_token_len, num_labels * k]
1406
+ # reshape为: [batch_size, padded_token_len * k, num_labels]
1407
+ logits = raw_logits.view(batch_size, padded_token_len * self.k, self.num_labels)
1408
+
1409
+ loss = None
1410
+ if labels is not None:
1411
+ if self.label_weights is not None:
1412
+ self.label_weights = self.label_weights.to(
1413
+ device=logits.device, dtype=logits.dtype
1414
+ )
1415
+ loss_fct = CrossEntropyLoss(weight=self.label_weights)
1416
+ else:
1417
+ loss_fct = CrossEntropyLoss()
1418
+
1419
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1420
+
1421
+ if not return_dict:
1422
+ output = (logits,)
1423
+ return ((loss,) + output) if loss is not None else output
1424
+
1425
+ return TokenClassifierOutput(loss=loss, logits=logits)
1426
+
1427
+
1428
+ @dataclass
1429
+ class DiffusionOutput(ModelOutput):
1430
+ loss: Optional[torch.FloatTensor] = None
1431
+ logits: torch.FloatTensor = None
1432
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
1433
+
1434
+ class GenerannoForDiscreteDiffusionLM(GenerannoPreTrainedModel):
1435
+ """
1436
+ 把 GENERanno 的 Encoder 权重完整继承,
1437
+ 外挂一个 Diffusion-Head(=MLM head)做离散扩散。
1438
+ """
1439
+ _tied_weights_keys = ["lm_head.weight"]
1440
+ def __init__(self, config: GenerannoConfig, **kwargs):
1441
+ super().__init__(config)
1442
+
1443
+ # Encoder
1444
+ self.model = GenerannoModel(config)
1445
+ self.vocab_size = config.vocab_size
1446
+
1447
+ # Diffusion-Head
1448
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1449
+
1450
+ # 初始化权重
1451
+ self.post_init()
1452
+
1453
+ # 添加gradient_checkpointing_enable方法,委托给内部的model
1454
+ def gradient_checkpointing_enable(self, gradient_checkpointing_kwargs=None):
1455
+ self.model.gradient_checkpointing_enable(gradient_checkpointing_kwargs)
1456
+
1457
+ # ------------- 前向 -------------
1458
+ def forward(
1459
+ self,
1460
+ input_ids: Optional[torch.LongTensor] = None, # 已经加噪的序列
1461
+ attention_mask: Optional[torch.Tensor] = None,
1462
+ noise_mask: Optional[torch.Tensor] = None,
1463
+ position_ids: Optional[torch.LongTensor] = None,
1464
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1465
+ labels: Optional[torch.LongTensor] = None,
1466
+ output_attentions: Optional[bool] = None,
1467
+ output_hidden_states: Optional[bool] = None,
1468
+ return_dict: Optional[bool] = None,
1469
+ ):
1470
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1471
+
1472
+ x_t = input_ids
1473
+
1474
+ # 2. encoder
1475
+ outputs = self.model(
1476
+ x_t,
1477
+ attention_mask=attention_mask,
1478
+ noise_mask=noise_mask,
1479
+ position_ids=position_ids,
1480
+ inputs_embeds=inputs_embeds,
1481
+ output_attentions=output_attentions,
1482
+ output_hidden_states=output_hidden_states,
1483
+ return_dict=return_dict,
1484
+ )
1485
+ hidden_states = outputs[0]
1486
+
1487
+ # 3. 预测 logits
1488
+ if self.config.pretraining_tp > 1:
1489
+ lm_head_slices = self.lm_head.weight.split(
1490
+ self.vocab_size // self.config.pretraining_tp, dim=0
1491
+ )
1492
+ logits = [
1493
+ F.linear(hidden_states, lm_head_slices[i])
1494
+ for i in range(self.config.pretraining_tp)
1495
+ ]
1496
+ logits = torch.cat(logits, dim=-1)
1497
+ else:
1498
+ logits = self.lm_head(hidden_states) # [B, L, V]
1499
+
1500
+ loss = None
1501
+ if labels is not None:
1502
+ # 计算损失,自动忽略ignore_index的位置
1503
+ loss_fct = CrossEntropyLoss(ignore_index=-100)
1504
+ loss = loss_fct(
1505
+ logits.view(-1, self.config.vocab_size),
1506
+ labels.view(-1)
1507
+ )
1508
+
1509
+ if not return_dict:
1510
+ return (loss, logits) if loss is not None else logits
1511
+
1512
+ return DiffusionOutput(loss=loss, logits=logits)
1513
+
1514
+ # ------------- 采样 -------------
1515
+ @torch.no_grad()
1516
+ def sample_iterative(
1517
+ self,
1518
+ tokenizer,
1519
+ input_ids,
1520
+ steps=1024,
1521
+ strategy="mixed",
1522
+ strategy_params={
1523
+ "topk_ratio": 0.1,
1524
+ "topk_fixed": 3,
1525
+ "confidence": 0.6,},
1526
+ temperature=1.0,
1527
+ min_confidence=0.3, # random guess = 0.25
1528
+ early_stop=True,
1529
+ verbose=False
1530
+ ):
1531
+ """
1532
+ 高级分步生成采样函数,支持多种采样策略和自定义初始序列
1533
+
1534
+ Args:
1535
+ tokenizer: tokenizer实例
1536
+ input_ids: 初始序列张量或None(从全mask开始)
1537
+ steps: 最大采样步数
1538
+ strategy: 采样策略,可选:
1539
+ - "topk_ratio": 每步替换固定比例的mask
1540
+ - "topk_fixed": 每步替换固定数量的mask
1541
+ - "confidence": 只替换置信度高于阈值的mask
1542
+ - "mixed": 混合策略,结合比例和置信度
1543
+ strategy_params: 策略参数字典
1544
+ temperature: 温度参数
1545
+ min_confidence: 最小置信度阈值
1546
+ early_stop: 是否在没有mask时提前停止
1547
+ verbose: 是否打印详细信息
1548
+ """
1549
+
1550
+ # 处理输入序列
1551
+ device = input_ids.device
1552
+ x = input_ids.clone().to(device)
1553
+ B, L = x.shape
1554
+ if verbose:
1555
+ print(f"使用自定义初始序列,形状: {x.shape}")
1556
+
1557
+ # 获取dna_base_ids
1558
+ if hasattr(tokenizer, "dna_base_ids"):
1559
+ dna_base_ids = tokenizer.dna_base_ids
1560
+ else:
1561
+ dna_base_ids = tokenizer.convert_tokens_to_ids(["A", "C", "G", "T"])
1562
+
1563
+ valid_token_ids = dna_base_ids
1564
+ mask_token_id = tokenizer.mask_token_id
1565
+ # bos_token_id = tokenizer.bos_token_id
1566
+ # unk_token_id = tokenizer.unk_token_id
1567
+ # valid_token_ids = dna_base_ids + [bos_token_id, mask_token_id]
1568
+
1569
+ if verbose:
1570
+ initial_mask_count = (x == mask_token_id).sum().item()
1571
+ print(f"初始mask数量: {initial_mask_count}/{B*L}")
1572
+ if tokenizer is not None:
1573
+ decoded = tokenizer.decode(x[0].cpu().tolist())
1574
+ print(f"初始序列: {decoded}")
1575
+
1576
+ # 逐步去噪
1577
+ for step in range(steps):
1578
+ # 计算当前mask位置
1579
+ mask_positions = (x == mask_token_id)
1580
+ current_mask_count = mask_positions.sum().item()
1581
+
1582
+ # 如果没有mask了且启用提前停止,提前结束
1583
+ if early_stop and current_mask_count == 0:
1584
+ if verbose:
1585
+ print(f"步骤 {step+1}/{steps}: 没有mask了,提前结束")
1586
+ break
1587
+
1588
+ # 模型预测
1589
+ logits = self.forward(x, return_dict=True).logits # [B, L, V]
1590
+
1591
+ # 温度调节
1592
+ scaled_logits = logits / temperature
1593
+
1594
+ # 只保留有效token的概率
1595
+ if tokenizer is not None:
1596
+ invalid_mask = torch.ones(logits.size(-1), dtype=torch.bool, device=device)
1597
+ invalid_mask[valid_token_ids] = False
1598
+ scaled_logits[..., invalid_mask] = -float('inf')
1599
+
1600
+ # 转换为概率分布
1601
+ probs = F.softmax(scaled_logits, dim=-1)
1602
+
1603
+ # 获取每个位置的最大概率和对应的token
1604
+ max_probs, max_tokens = probs.max(dim=-1) # [B, L]
1605
+
1606
+ # 只考虑mask位置的预测
1607
+ mask_max_probs = torch.where(mask_positions, max_probs, torch.tensor(-float('inf'), device=device))
1608
+
1609
+ # 根据策略选择要替换的mask
1610
+ replace_mask = torch.zeros_like(mask_positions, dtype=torch.bool)
1611
+
1612
+ if strategy == "topk_ratio":
1613
+ # 每步替换固定比例的mask
1614
+ ratio = strategy_params["topk_ratio"]
1615
+ masks_per_step = max(1, int(ratio * current_mask_count))
1616
+ replace_mask = self._select_by_topk(mask_max_probs, masks_per_step, mask_positions)
1617
+
1618
+ elif strategy == "topk_fixed":
1619
+ # 每步替换固定数量的mask
1620
+ fixed_count = strategy_params["topk_fixed"]
1621
+ masks_per_step = min(fixed_count, current_mask_count)
1622
+ replace_mask = self._select_by_topk(mask_max_probs, masks_per_step, mask_positions)
1623
+
1624
+ elif strategy == "confidence":
1625
+ # 只替换置信度高于阈值的mask
1626
+ threshold = strategy_params["confidence"]
1627
+ confidence_mask = (mask_max_probs >= threshold)
1628
+ replace_mask = mask_positions & confidence_mask
1629
+
1630
+ elif strategy == "mixed":
1631
+ # 混合策略:先按置信度筛选,再按比例选择
1632
+ threshold = strategy_params["confidence"]
1633
+ ratio = strategy_params["topk_ratio"]
1634
+
1635
+ # 先筛选出高置信度的mask
1636
+ confidence_mask = (mask_max_probs >= threshold)
1637
+ high_conf_mask_positions = mask_positions & confidence_mask
1638
+ high_conf_count = high_conf_mask_positions.sum().item()
1639
+
1640
+ if high_conf_count > 0:
1641
+ # 在高置信度mask中按比例选择
1642
+ masks_per_step = max(1, int(ratio * high_conf_count))
1643
+ high_conf_probs = torch.where(high_conf_mask_positions, mask_max_probs,
1644
+ torch.tensor(-float('inf'), device=device))
1645
+ replace_mask = self._select_by_topk(high_conf_probs, masks_per_step, high_conf_mask_positions)
1646
+ else:
1647
+ # 如果没有高置信度mask,回退到普通topk策略
1648
+ masks_per_step = max(1, int(ratio * current_mask_count))
1649
+ replace_mask = self._select_by_topk(mask_max_probs, masks_per_step, mask_positions)
1650
+
1651
+ else:
1652
+ raise ValueError(f"未知的采样策略: {strategy}")
1653
+
1654
+ # 应用最小置信度过滤
1655
+ if min_confidence > 0:
1656
+ low_confidence_mask = (mask_max_probs < min_confidence) & replace_mask
1657
+ replace_mask = replace_mask & ~low_confidence_mask
1658
+
1659
+ # 更新序列
1660
+ for i in range(B):
1661
+ seq_replace_positions = replace_mask[i]
1662
+ if seq_replace_positions.any():
1663
+ replace_indices = torch.where(seq_replace_positions)[0]
1664
+ predicted_tokens = max_tokens[i][replace_indices]
1665
+ x[i, replace_indices] = predicted_tokens
1666
+
1667
+ if verbose:
1668
+ current_mask_count = (x == mask_token_id).sum().item()
1669
+ replaced_count = replace_mask.sum().item()
1670
+ avg_confidence = mask_max_probs[replace_mask].mean().item() if replace_mask.any() else 0
1671
+
1672
+ print(f"步骤 {step+1}/{steps}: 替换了 {replaced_count} 个mask, "
1673
+ f"剩余mask: {current_mask_count}, 平均置信度: {avg_confidence:.3f}")
1674
+
1675
+ if tokenizer is not None and step % max(1, steps//5) == 0:
1676
+ decoded = tokenizer.decode(x[0].cpu().tolist())
1677
+ print(f"当前序列: {decoded}")
1678
+
1679
+ if verbose and tokenizer is not None:
1680
+ final_mask_count = (x == mask_token_id).sum().item()
1681
+ final_decoded = tokenizer.decode(x[0].cpu().tolist())
1682
+ print(f"最终序列: {final_decoded}")
1683
+ print(f"最终mask数量: {final_mask_count}")
1684
+
1685
+ return x
1686
+
1687
+ def _select_by_topk(self, mask_max_probs, k, mask_positions):
1688
+ """
1689
+ 辅助函数:选择概率���高的k个mask位置
1690
+ """
1691
+ B, L = mask_max_probs.shape
1692
+ device = mask_max_probs.device
1693
+
1694
+ replace_mask = torch.zeros_like(mask_positions, dtype=torch.bool)
1695
+
1696
+ for i in range(B):
1697
+ # 获取当前序列的mask位置和对应的概率
1698
+ seq_mask_positions = mask_positions[i]
1699
+ seq_mask_probs = mask_max_probs[i]
1700
+
1701
+ # 如果当前序列没有mask了,跳过
1702
+ if not seq_mask_positions.any():
1703
+ continue
1704
+
1705
+ # 选择概率最高的k个mask位置
1706
+ _, topk_indices = torch.topk(seq_mask_probs, min(k, seq_mask_positions.sum().item()))
1707
+
1708
+ # 设置替换掩码
1709
+ replace_mask[i, topk_indices] = True
1710
+
1711
+ return replace_mask
1712
+
1713
+
1714
+ @dataclass
1715
+ class MixedLMOutput(ModelOutput):
1716
+ loss: Optional[torch.FloatTensor] = None
1717
+ logits: torch.FloatTensor = None
1718
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
1719
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
1720
+ task_losses: Optional[dict] = None
1721
+ task_type: Optional[str] = None
1722
+
1723
+ class GenerannoForMixedLM(GenerannoPreTrainedModel):
1724
+ """
1725
+ 简洁的多任务语言模型
1726
+ - 共享隐藏层,任务特定的输出头
1727
+ """
1728
+
1729
+ def __init__(self, config):
1730
+ super().__init__(config)
1731
+
1732
+ # 共享的骨干网络
1733
+ self.model = GenerannoModel(config)
1734
+ self.vocab_size = config.vocab_size
1735
+
1736
+ # 任务特定的输出头
1737
+ self.ntp_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1738
+ self.mlm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1739
+ self.diff_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1740
+
1741
+ # 初始化权重
1742
+ self.post_init()
1743
+
1744
+ # 添加gradient_checkpointing_enable方法,委托给内部的model
1745
+ def gradient_checkpointing_enable(self, gradient_checkpointing_kwargs=None):
1746
+ self.model.gradient_checkpointing_enable(gradient_checkpointing_kwargs)
1747
+
1748
+ def set_task_tokens(self, ntp_token_id, mlm_token_id, diff_token_id):
1749
+ """设置任务token ID(在tokenizer添加特殊token后调用)"""
1750
+ self.ntp_token_id = ntp_token_id
1751
+ self.mlm_token_id = mlm_token_id
1752
+ self.diff_token_id = diff_token_id
1753
+
1754
+ def get_output_head(self, task_type):
1755
+ """根据任务类型获取对应的输出头"""
1756
+ if task_type == "ntp":
1757
+ return self.ntp_head
1758
+ elif task_type == "mlm":
1759
+ return self.mlm_head
1760
+ elif task_type == "diff":
1761
+ return self.diff_head
1762
+ else:
1763
+ raise ValueError(f"Unknown task type: {task_type}")
1764
+
1765
+ def _detect_task_type_from_input(self, input_ids):
1766
+ """根据输入的第一个token检测任务类型"""
1767
+ if self.ntp_token_id is None or self.mlm_token_id is None or self.diff_token_id is None:
1768
+ raise ValueError("Task tokens not set. Please call set_task_tokens() first.")
1769
+
1770
+ first_token = input_ids[0, 0].item()
1771
+ if first_token == self.ntp_token_id:
1772
+ return "ntp"
1773
+ elif first_token == self.mlm_token_id:
1774
+ return "mlm"
1775
+ elif first_token == self.diff_token_id:
1776
+ return "diff"
1777
+ else:
1778
+ # 默认使用NTP
1779
+ return "ntp"
1780
+
1781
+ def forward(
1782
+ self,
1783
+ input_ids: torch.LongTensor = None,
1784
+ attention_mask: Optional[torch.Tensor] = None,
1785
+ position_ids: Optional[torch.LongTensor] = None,
1786
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1787
+ labels: Optional[torch.LongTensor] = None,
1788
+ task_type: Optional[str] = None,
1789
+ output_attentions: Optional[bool] = None,
1790
+ output_hidden_states: Optional[bool] = None,
1791
+ return_dict: Optional[bool] = None,
1792
+ ) -> Union[Tuple, MixedLMOutput]:
1793
+
1794
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1795
+
1796
+ # 检测任务类型
1797
+ if task_type is None:
1798
+ task_type = self._detect_task_type_from_input(input_ids)
1799
+
1800
+ is_causal = (task_type == "ntp")
1801
+
1802
+ # 共享隐藏层前向传播
1803
+ outputs = self.model(
1804
+ input_ids=input_ids,
1805
+ attention_mask=attention_mask,
1806
+ position_ids=position_ids,
1807
+ inputs_embeds=inputs_embeds,
1808
+ output_attentions=output_attentions,
1809
+ output_hidden_states=output_hidden_states,
1810
+ return_dict=return_dict,
1811
+ is_causal=is_causal
1812
+ )
1813
+
1814
+ hidden_states = outputs[0]
1815
+
1816
+ # 任务特定的输出头
1817
+ output_head = self.get_output_head(task_type)
1818
+ logits = output_head(hidden_states)
1819
+
1820
+ # 计算任务特定损失
1821
+ loss = None
1822
+ if labels is not None:
1823
+ loss_fct = CrossEntropyLoss(ignore_index=-100)
1824
+
1825
+ if task_type == "ntp":
1826
+ # NTP损失:下一个token预测
1827
+ shift_logits = logits[..., :-1, :].contiguous()
1828
+ shift_labels = labels[..., 1:].contiguous()
1829
+ loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
1830
+ else:
1831
+ # MDM损失:当前掩码位置预测
1832
+ loss = loss_fct(logits.view(-1, self.config.vocab_size), labels.view(-1))
1833
+
1834
+ if not return_dict:
1835
+ output = (logits,)
1836
+ if output_hidden_states:
1837
+ output += (outputs.hidden_states,)
1838
+ if output_attentions:
1839
+ output += (outputs.attentions,)
1840
+ return ((loss,) + output) if loss is not None else output
1841
+
1842
+ return MixedLMOutput(
1843
+ loss=loss,
1844
+ logits=logits,
1845
+ hidden_states=outputs.hidden_states if output_hidden_states else None,
1846
+ attentions=outputs.attentions if output_attentions else None,
1847
+ task_losses={task_type: loss.item() if loss is not None else 0.0},
1848
+ task_type=task_type
1849
+ )
train_annotation_model.py ADDED
@@ -0,0 +1,283 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import argparse
3
+ import wandb
4
+ import logging
5
+ import torch
6
+
7
+ from datetime import datetime
8
+ from transformers import TrainingArguments
9
+ from transformers import AutoTokenizer, AutoModelForTokenClassification
10
+ from transformers.trainer_utils import get_last_checkpoint
11
+
12
+ from custom_trainer import *
13
+ from h5_dataset import *
14
+ from utility import *
15
+
16
+ # Configure logging
17
+ logging.basicConfig(level=logging.INFO)
18
+ logger = logging.getLogger(__name__)
19
+
20
+
21
+ def parse_args():
22
+ parser = argparse.ArgumentParser(description="Pretrain GENERanno model")
23
+
24
+ # ===== Model & data =====
25
+ parser.add_argument("--model_path", type=str, default="./GENERanno-6mer-eukaryote-1.2b-annotator/", help="Path to pretrained model / tokenizer")
26
+ parser.add_argument("--data_dir", type=str, action="append", help="HDF5 data directories (can be specified multiple times)")
27
+ parser.add_argument("--output_dir", type=str, default=None, help="Output directory for training checkpoints")
28
+ parser.add_argument("--saved_model_dir", type=str, default=None, help="Directory to save the final model")
29
+ parser.add_argument("--max_token_length", type=int, default=16384, help="Maximum token length")
30
+ parser.add_argument("--label_weight", type=float, default=1.0, help="Label weight")
31
+
32
+ # ===== WandB =====
33
+ parser.add_argument("--wandb_key", type=str, default="38968f496b92f8815425fc514159096e41a51c86", help="WandB API key")
34
+ parser.add_argument("--wandb_project", type=str, default="DNA_pretrain", help="WandB project name")
35
+ parser.add_argument("--run_name", type=str, default=None, help="WandB run name")
36
+
37
+ # ===== Training =====
38
+ parser.add_argument("--epochs", type=int, default=1, help="Number of training epochs")
39
+ parser.add_argument("--batch_size", type=int, default=4, help="Training batch size per GPU")
40
+ parser.add_argument("--lr", type=float, default=5e-5, help="Learning rate")
41
+ parser.add_argument("--warm_up", type=int, default=2000, help="Number of warmup steps")
42
+ parser.add_argument("--gradient_accumulation", type=int, default=1, help="Gradient accumulation steps")
43
+ parser.add_argument("--save_steps", type=int, default=10000, help="Checkpoint saving interval (in steps)")
44
+ parser.add_argument("--save_total_limit", type=int, default=10, help="Maximum number of saved checkpoints")
45
+ parser.add_argument("--logging_steps", type=int, default=10, help="Logging interval (in steps)")
46
+
47
+ # ===== Precision (mutually exclusive) =====
48
+ precision_group = parser.add_mutually_exclusive_group()
49
+ precision_group.add_argument("--fp16", action="store_true", help="Enable FP16 precision training")
50
+ precision_group.add_argument("--bf16", action="store_true", help="Enable BF16 precision training")
51
+
52
+ # ===== Distributed / system =====
53
+ parser.add_argument("--report_to", type=str, default="wandb", help="Logging backend")
54
+ parser.add_argument("--fsdp_config", type=str, default="./fsdp_config_generanno.json", help="Path to FSDP config file")
55
+ # parser.add_argument("--ds_config", type=str, default="./ds_config.json", help="Path to DeepSpeed config file")
56
+ parser.add_argument("--local_rank", type=int, default=0, help="Local rank for distributed training")
57
+ parser.add_argument("--attn_implementation", type=str, default="auto", choices=["auto", "sdpa", "flash_attention_2"],
58
+ help="Attention implementation: auto, sdpa, or flash_attention_2 (requires flash-attn)")
59
+
60
+ return parser.parse_args()
61
+
62
+
63
+
64
+ def setup_logging_and_wandb(args):
65
+ os.environ["WANDB_PROJECT"] = args.wandb_project
66
+ os.environ["WANDB_NAME"] = args.run_name
67
+
68
+ wandb.login(key=args.wandb_key, force=True)
69
+ logger.info(
70
+ f"WandB login successful. Project: {args.wandb_project}, Run: {args.run_name}"
71
+ )
72
+
73
+
74
+ def get_training_args(args):
75
+ # Check BF16 hardware support
76
+ if args.bf16 and not torch.cuda.is_bf16_supported():
77
+ logger.warning(
78
+ "Current hardware does not support BF16. Falling back to FP16."
79
+ )
80
+ args.bf16 = False
81
+ args.fp16 = True
82
+
83
+ # Log precision mode
84
+ if args.bf16:
85
+ logger.info("Using BF16 precision training")
86
+ elif args.fp16:
87
+ logger.info("Using FP16 precision training")
88
+ else:
89
+ logger.info("Using FP32 precision training")
90
+
91
+ return TrainingArguments(
92
+ output_dir=args.output_dir,
93
+ overwrite_output_dir=True,
94
+ num_train_epochs=args.epochs,
95
+ per_device_train_batch_size=args.batch_size,
96
+ gradient_accumulation_steps=args.gradient_accumulation,
97
+ save_steps=args.save_steps,
98
+ save_total_limit=args.save_total_limit,
99
+ logging_steps=args.logging_steps,
100
+ report_to=args.report_to,
101
+ fp16=args.fp16,
102
+ bf16=args.bf16,
103
+ max_grad_norm=1.0,
104
+
105
+ # =============== Distributed training ===============
106
+ fsdp=["shard_grad_op", "auto_wrap"],
107
+ fsdp_config=args.fsdp_config,
108
+ # deepspeed=args.ds_config, # Enable when switching to DeepSpeed
109
+
110
+ # =============== Optimizer & LR scheduler ===============
111
+ run_name=args.run_name,
112
+ warmup_steps=args.warm_up,
113
+ weight_decay=0.01,
114
+ learning_rate=args.lr,
115
+ lr_scheduler_type="cosine_with_min_lr",
116
+ lr_scheduler_kwargs={"min_lr_rate": 0.1},
117
+
118
+ # =============== Evaluation ===============
119
+ eval_strategy="steps",
120
+ eval_steps=args.save_steps,
121
+ eval_accumulation_steps=1,
122
+ per_device_eval_batch_size=args.batch_size,
123
+
124
+ # =============== Gradient checkpointing ===============
125
+ gradient_checkpointing=True,
126
+ gradient_checkpointing_kwargs={
127
+ "use_reentrant": False,
128
+ "preserve_rng_state": False,
129
+ },
130
+
131
+ # =============== Dataset column handling ===============
132
+ remove_unused_columns=False,
133
+ )
134
+
135
+
136
+ def main():
137
+ args = parse_args()
138
+
139
+ # Set run name
140
+ if args.run_name is None:
141
+ args.run_name = f"H5_{args.max_token_length}_{datetime.now().strftime('%Y%m%d_%H%M')}"
142
+
143
+ # Set directories
144
+ if args.output_dir is None:
145
+ args.output_dir = os.path.join("checkpoints", args.run_name)
146
+ if args.saved_model_dir is None:
147
+ args.saved_model_dir = os.path.join("saved_model", args.run_name)
148
+
149
+ # Setup WandB
150
+ setup_logging_and_wandb(args)
151
+
152
+ # Load tokenizer
153
+ logger.info(f"Loading tokenizer from {args.model_path}")
154
+ tokenizer = AutoTokenizer.from_pretrained(
155
+ args.model_path, trust_remote_code=True
156
+ )
157
+
158
+ # Load model (supports attn_implementation and bf16)
159
+ model = AutoModelForTokenClassification.from_pretrained(
160
+ args.model_path,
161
+ attn_implementation="flash_attention_2",
162
+ dtype=torch.bfloat16,
163
+ trust_remote_code=True,
164
+ )
165
+ model.vocab_size = tokenizer.vocab_size
166
+ model.label_weights = torch.tensor(
167
+ [1.0, args.label_weight], dtype=torch.bfloat16
168
+ )
169
+
170
+ # Prepare datasets
171
+ logger.info("Preparing datasets...")
172
+ train_dataset = HDF5TokenizedDataset(
173
+ data_dir=args.data_dir,
174
+ max_length=args.max_token_length,
175
+ task_type="annotation",
176
+ k=6,
177
+ )
178
+ logger.info(f"Training dataset size: {len(train_dataset)}")
179
+
180
+ human_val_dataset = HDF5TokenizedDataset("./eval/human", args.max_token_length, "annotation", 6)
181
+ mouse_val_dataset = HDF5TokenizedDataset("./eval/mouse", args.max_token_length, "annotation", 6)
182
+ pig_val_dataset = HDF5TokenizedDataset("./eval/pig", args.max_token_length, "annotation", 6)
183
+ fish_val_dataset = HDF5TokenizedDataset("./eval/fish", args.max_token_length, "annotation", 6)
184
+ chicken_val_dataset = HDF5TokenizedDataset("./eval/chicken", args.max_token_length, "annotation", 6)
185
+ frog_val_dataset = HDF5TokenizedDataset("./eval/frog", args.max_token_length, "annotation", 6)
186
+ elegans_val_dataset = HDF5TokenizedDataset("./eval/elegans", args.max_token_length, "annotation", 6)
187
+ star_val_dataset = HDF5TokenizedDataset("./eval/star", args.max_token_length, "annotation", 6)
188
+ urchin_val_dataset = HDF5TokenizedDataset("./eval/urchin", args.max_token_length, "annotation", 6)
189
+ fly_val_dataset = HDF5TokenizedDataset("./eval/fly", args.max_token_length, "annotation", 6)
190
+ shell_val_dataset = HDF5TokenizedDataset("./eval/shell", args.max_token_length, "annotation", 6)
191
+
192
+ plant1_val_dataset = HDF5TokenizedDataset("./eval/plant1", args.max_token_length, "annotation", 6)
193
+ plant2_val_dataset = HDF5TokenizedDataset("./eval/plant2", args.max_token_length, "annotation", 6)
194
+ plant3_val_dataset = HDF5TokenizedDataset("./eval/plant3", args.max_token_length, "annotation", 6)
195
+ plant4_val_dataset = HDF5TokenizedDataset("./eval/plant4", args.max_token_length, "annotation", 6)
196
+ plant5_val_dataset = HDF5TokenizedDataset("./eval/plant5", args.max_token_length, "annotation", 6)
197
+
198
+ fungi1_val_dataset = HDF5TokenizedDataset("./eval/fungi1", args.max_token_length, "annotation", 6)
199
+ fungi2_val_dataset = HDF5TokenizedDataset("./eval/fungi2", args.max_token_length, "annotation", 6)
200
+ fungi3_val_dataset = HDF5TokenizedDataset("./eval/fungi3", args.max_token_length, "annotation", 6)
201
+ fungi4_val_dataset = HDF5TokenizedDataset("./eval/fungi4", args.max_token_length, "annotation", 6)
202
+ fungi5_val_dataset = HDF5TokenizedDataset("./eval/fungi5", args.max_token_length, "annotation", 6)
203
+
204
+ protozoa1_val_dataset = HDF5TokenizedDataset("./eval/protozoa1", args.max_token_length, "annotation", 6)
205
+ protozoa2_val_dataset = HDF5TokenizedDataset("./eval/protozoa2", args.max_token_length, "annotation", 6)
206
+ protozoa3_val_dataset = HDF5TokenizedDataset("./eval/protozoa3", args.max_token_length, "annotation", 6)
207
+ protozoa4_val_dataset = HDF5TokenizedDataset("./eval/protozoa4", args.max_token_length, "annotation", 6)
208
+ protozoa5_val_dataset = HDF5TokenizedDataset("./eval/protozoa5", args.max_token_length, "annotation", 6)
209
+
210
+ # Data collator
211
+ data_collator = AnnotationDataCollator(
212
+ tokenizer=tokenizer,
213
+ max_length=args.max_token_length,
214
+ k=6,
215
+ num_prediction_heads=2,
216
+ )
217
+
218
+ # Training arguments
219
+ training_args = get_training_args(args)
220
+
221
+ # Auto resume from last checkpoint
222
+ resume_from_checkpoint = (
223
+ get_last_checkpoint(args.output_dir)
224
+ if os.path.exists(args.output_dir)
225
+ else None
226
+ )
227
+ if resume_from_checkpoint:
228
+ logger.info(f"Resuming training from checkpoint: {resume_from_checkpoint}")
229
+
230
+ eval_datasets = {
231
+ "human": human_val_dataset,
232
+ "mouse": mouse_val_dataset,
233
+ "pig": pig_val_dataset,
234
+ "fish": fish_val_dataset,
235
+ "chicken": chicken_val_dataset,
236
+ "frog": frog_val_dataset,
237
+ "elegans": elegans_val_dataset,
238
+ "star": star_val_dataset,
239
+ "urchin": urchin_val_dataset,
240
+ "fly": fly_val_dataset,
241
+ "shell": shell_val_dataset,
242
+ "plant1": plant1_val_dataset,
243
+ "plant2": plant2_val_dataset,
244
+ "plant3": plant3_val_dataset,
245
+ "plant4": plant4_val_dataset,
246
+ "plant5": plant5_val_dataset,
247
+ "fungi1": fungi1_val_dataset,
248
+ "fungi2": fungi2_val_dataset,
249
+ "fungi3": fungi3_val_dataset,
250
+ "fungi4": fungi4_val_dataset,
251
+ "fungi5": fungi5_val_dataset,
252
+ "protozoa1": protozoa1_val_dataset,
253
+ "protozoa2": protozoa2_val_dataset,
254
+ "protozoa3": protozoa3_val_dataset,
255
+ "protozoa4": protozoa4_val_dataset,
256
+ "protozoa5": protozoa5_val_dataset,
257
+ }
258
+
259
+ eval_callback = MultiDatasetEvalCallback(eval_datasets)
260
+
261
+ trainer = AnnotationTrainer(
262
+ model=model,
263
+ args=training_args,
264
+ train_dataset=train_dataset,
265
+ data_collator=data_collator,
266
+ eval_dataset={},
267
+ callbacks=[eval_callback],
268
+ )
269
+ eval_callback.trainer = trainer
270
+
271
+ # Start training
272
+ logger.info("Starting training...")
273
+ trainer.train(resume_from_checkpoint=resume_from_checkpoint)
274
+
275
+ # Save final model
276
+ logger.info(f"Saving final model to {args.saved_model_dir}")
277
+ model.save_pretrained(args.saved_model_dir)
278
+ tokenizer.save_pretrained(args.saved_model_dir)
279
+ logger.info("Training finished successfully!")
280
+
281
+
282
+ if __name__ == "__main__":
283
+ main()
utility.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import TrainerCallback
2
+
3
+
4
+ class MultiDatasetEvalCallback(TrainerCallback):
5
+ def __init__(self, eval_datasets):
6
+ self.eval_datasets = eval_datasets
7
+
8
+ def on_step_end(self, args, state, control, **kwargs):
9
+ """Evaluation on multiple datasets at saving steps"""
10
+ if (state.global_step > 0 and
11
+ args.eval_strategy == "steps" and
12
+ state.global_step % args.eval_steps == 0 and
13
+ self.eval_datasets):
14
+
15
+ is_main = (getattr(args, 'local_rank', -1) in [-1, 0])
16
+
17
+ if is_main:
18
+ print(f"\n=== Multi-dataset evaluation at step {state.global_step} ===")
19
+
20
+ for dataset_name, dataset in self.eval_datasets.items():
21
+ if is_main:
22
+ print(f"Evaluating on {dataset_name}...")
23
+
24
+ eval_metrics = self.trainer.evaluate(
25
+ eval_dataset=dataset,
26
+ metric_key_prefix=f"eval_{dataset_name}"
27
+ )
28
+
29
+ def on_train_end(self, args, state, control, **kwargs):
30
+ """Evaluation on multiple datasets at the end of training"""
31
+ is_main = (getattr(args, 'local_rank', -1) in [-1, 0])
32
+
33
+ if is_main:
34
+ print(f"\n=== Multi-dataset evaluation at end of training ===")
35
+
36
+ for dataset_name, dataset in self.eval_datasets.items():
37
+ if is_main:
38
+ print(f"Evaluating on {dataset_name}...")
39
+
40
+ eval_metrics = self.trainer.evaluate(
41
+ eval_dataset=dataset,
42
+ metric_key_prefix=f"eval_{dataset_name}"
43
+ )