mineself2016 commited on
Commit
ec0b6f5
·
verified ·
1 Parent(s): 620603b

Remove continue pretraining example

Browse files
Files changed (1) hide show
  1. examples/3_continue_pretraining.py +0 -275
examples/3_continue_pretraining.py DELETED
@@ -1,275 +0,0 @@
1
- """
2
- Phase 3: Continue Pretraining
3
- Demonstrates how to continue pretraining GeneMamba on your own data using masked LM objective.
4
-
5
- Usage:
6
- python examples/3_continue_pretraining.py
7
- """
8
-
9
- import torch
10
- import numpy as np
11
- from pathlib import Path
12
- from torch.utils.data import Dataset
13
- from transformers import (
14
- AutoModelForMaskedLM,
15
- AutoTokenizer,
16
- Trainer,
17
- TrainingArguments,
18
- )
19
-
20
-
21
- class PretrainingDataset(Dataset):
22
- """
23
- Dataset for pretraining/continued pretraining.
24
- Loads sequences and their lengths.
25
- """
26
-
27
- def __init__(self, input_ids_list, max_length=2048):
28
- self.input_ids_list = input_ids_list
29
- self.max_length = max_length
30
-
31
- def __len__(self):
32
- return len(self.input_ids_list)
33
-
34
- def __getitem__(self, idx):
35
- input_ids = self.input_ids_list[idx]
36
-
37
- # Pad or truncate to max_length
38
- if len(input_ids) >= self.max_length:
39
- input_ids = input_ids[:self.max_length]
40
- else:
41
- input_ids = np.pad(
42
- input_ids,
43
- (0, self.max_length - len(input_ids)),
44
- constant_values=1 # Pad token ID
45
- )
46
-
47
- return {
48
- "input_ids": torch.tensor(input_ids, dtype=torch.long),
49
- }
50
-
51
-
52
- def create_mock_pretraining_data(n_sequences=5000, seq_len=2048):
53
- """Create mock single-cell sequences for pretraining."""
54
-
55
- print("Creating mock pretraining dataset...")
56
-
57
- # Create ranked gene sequences
58
- # In practice, these would come from your scRNA-seq data
59
- sequences = []
60
- for _ in range(n_sequences):
61
- # Random ranked sequence
62
- seq = np.random.randint(2, 25426, seq_len)
63
- sequences.append(seq)
64
-
65
- print(f"✓ Created {n_sequences} sequences of length {seq_len}")
66
-
67
- return sequences
68
-
69
-
70
- class GeneMambaMLMCollator:
71
- """GeneMamba MLM collator using [UNK] replacement for masked positions."""
72
-
73
- def __init__(self, pad_token_id: int, unk_token_id: int, mlm_probability: float = 0.15):
74
- self.pad_token_id = pad_token_id
75
- self.unk_token_id = unk_token_id
76
- self.mlm_probability = mlm_probability
77
-
78
- def __call__(self, features):
79
- input_ids = torch.stack([f["input_ids"] for f in features])
80
- labels = input_ids.clone()
81
-
82
- prob = torch.full(labels.shape, self.mlm_probability)
83
- mask_positions = torch.bernoulli(prob).bool()
84
- mask_positions &= input_ids.ne(self.pad_token_id)
85
-
86
- labels[~mask_positions] = -100
87
- input_ids[mask_positions] = self.unk_token_id
88
-
89
- return {"input_ids": input_ids, "labels": labels}
90
-
91
-
92
- def main():
93
- print("=" * 80)
94
- print("GeneMamba Phase 3: Continue Pretraining")
95
- print("=" * 80)
96
-
97
- # ============================================================
98
- # Step 1: Load pretrained model for masked LM
99
- # ============================================================
100
- print("\n[Step 1] Loading model for masked LM...")
101
-
102
- try:
103
- tokenizer = AutoTokenizer.from_pretrained(
104
- "mineself2016/GeneMamba",
105
- trust_remote_code=True,
106
- )
107
- model = AutoModelForMaskedLM.from_pretrained(
108
- "mineself2016/GeneMamba",
109
- trust_remote_code=True,
110
- )
111
- except Exception as e:
112
- print(f"Note: Could not load from hub ({e})")
113
- print("Using local initialization...")
114
-
115
- # Initialize locally
116
- from configuration_genemamba import GeneMambaConfig
117
- from modeling_genemamba import GeneMambaForMaskedLM
118
-
119
- config = GeneMambaConfig(
120
- vocab_size=25426,
121
- hidden_size=512,
122
- num_hidden_layers=24,
123
- )
124
- model = GeneMambaForMaskedLM(config)
125
- project_root = Path(__file__).resolve().parent.parent
126
- tokenizer = AutoTokenizer.from_pretrained(
127
- str(project_root),
128
- trust_remote_code=True,
129
- local_files_only=True,
130
- )
131
-
132
- print(f"✓ Model loaded")
133
- print(f" - Architecture: {model.config.num_hidden_layers} layers, "
134
- f"hidden_size={model.config.hidden_size}")
135
- print(f" - Vocab size: {tokenizer.vocab_size}")
136
- print(f" - [UNK] token/id: {tokenizer.unk_token}/{tokenizer.unk_token_id}")
137
- print(f" - [PAD] token/id: {tokenizer.pad_token}/{tokenizer.pad_token_id}")
138
- print(f" - [CLS] token/id: {tokenizer.cls_token}/{tokenizer.cls_token_id}")
139
- print(f" - [MASK] token/id: {tokenizer.mask_token}/{tokenizer.mask_token_id}")
140
-
141
- # ============================================================
142
- # Step 2: Prepare pretraining data
143
- # ============================================================
144
- print("\n[Step 2] Preparing pretraining dataset...")
145
-
146
- sequences = create_mock_pretraining_data(n_sequences=5000, seq_len=2048)
147
-
148
- # Split train/eval
149
- train_size = int(0.9 * len(sequences))
150
- train_sequences = sequences[:train_size]
151
- eval_sequences = sequences[train_size:]
152
-
153
- train_dataset = PretrainingDataset(train_sequences)
154
- eval_dataset = PretrainingDataset(eval_sequences)
155
-
156
- print(f"✓ Datasets created:")
157
- print(f" - Training: {len(train_dataset)} samples")
158
- print(f" - Evaluation: {len(eval_dataset)} samples")
159
-
160
- # ============================================================
161
- # Step 3: Set up data collator for MLM
162
- # ============================================================
163
- print("\n[Step 3] Setting up data collator...")
164
-
165
- data_collator = GeneMambaMLMCollator(
166
- pad_token_id=tokenizer.pad_token_id,
167
- unk_token_id=tokenizer.unk_token_id,
168
- mlm_probability=0.15,
169
- )
170
-
171
- print(f"✓ Data collator ready (MLM probability: 0.15)")
172
-
173
- # ============================================================
174
- # Step 4: Set up training arguments
175
- # ============================================================
176
- print("\n[Step 4] Setting up training...")
177
-
178
- output_dir = "./pretrain_results"
179
-
180
- training_args = TrainingArguments(
181
- output_dir=output_dir,
182
- num_train_epochs=2,
183
- per_device_train_batch_size=16,
184
- per_device_eval_batch_size=16,
185
- learning_rate=2e-5,
186
- weight_decay=0.01,
187
- warmup_steps=500,
188
- logging_steps=100,
189
- eval_strategy="epoch",
190
- save_strategy="epoch",
191
- load_best_model_at_end=True,
192
- metric_for_best_model="eval_loss",
193
- report_to="none", # Disable W&B
194
- seed=42,
195
- )
196
-
197
- print(f"✓ Training config:")
198
- print(f" - Output dir: {output_dir}")
199
- print(f" - Epochs: {training_args.num_train_epochs}")
200
- print(f" - Batch size: {training_args.per_device_train_batch_size}")
201
- print(f" - Learning rate: {training_args.learning_rate}")
202
- print(f" - MLM masking: 15%")
203
-
204
- # ============================================================
205
- # Step 5: Train
206
- # ============================================================
207
- print("\n[Step 5] Starting continued pretraining...")
208
-
209
- trainer = Trainer(
210
- model=model,
211
- args=training_args,
212
- train_dataset=train_dataset,
213
- eval_dataset=eval_dataset,
214
- data_collator=data_collator,
215
- )
216
-
217
- train_result = trainer.train()
218
-
219
- print(f"✓ Training complete!")
220
- print(f" - Final training loss: {train_result.training_loss:.4f}")
221
-
222
- # ============================================================
223
- # Step 6: Evaluate
224
- # ============================================================
225
- print("\n[Step 6] Evaluating on held-out set...")
226
-
227
- eval_results = trainer.evaluate()
228
-
229
- print(f"✓ Evaluation Results:")
230
- for metric, value in eval_results.items():
231
- if isinstance(value, (int, float)):
232
- print(f" - {metric}: {value:.4f}")
233
-
234
- # ============================================================
235
- # Step 7: Save model
236
- # ============================================================
237
- print("\n[Step 7] Saving continued pretrained model...")
238
-
239
- save_dir = "./genemamba_continued_pretrain"
240
- model.save_pretrained(save_dir)
241
- if tokenizer is not None:
242
- tokenizer.save_pretrained(save_dir)
243
-
244
- print(f"✓ Model saved to '{save_dir}'")
245
-
246
- # ============================================================
247
- # Step 8: Test model inference
248
- # ============================================================
249
- print("\n[Step 8] Testing inference on masked input...")
250
-
251
- model.eval()
252
-
253
- # Create sample input with masked tokens
254
- sample_input = torch.randint(2, 25426, (1, 2048))
255
- sample_input[0, :10] = 0 # Mask first 10 tokens
256
-
257
- with torch.no_grad():
258
- outputs = model(sample_input)
259
- logits = outputs.logits
260
- predictions = torch.argmax(logits, dim=-1)
261
-
262
- print(f"✓ Sample predictions generated")
263
- print(f" - Input shape: {sample_input.shape}")
264
- print(f" - Output logits shape: {logits.shape}")
265
- print(f" - Top predicted genes (tokens): {predictions[0, :10].tolist()}")
266
-
267
- print("\n" + "=" * 80)
268
- print("Phase 3 Complete! Model ready for downstream tasks or further training.")
269
- print("=" * 80)
270
-
271
- return model, trainer
272
-
273
-
274
- if __name__ == "__main__":
275
- model, trainer = main()