mineself2016 commited on
Commit
eb4d1c7
·
verified ·
1 Parent(s): 89a3262

Remove stale file: examples/10_finetune_classification.py

Browse files
examples/10_finetune_classification.py DELETED
@@ -1,248 +0,0 @@
1
- """
2
- Phase 2: Downstream Task - Fine-tune for Classification
3
- Demonstrates cell type annotation and other sequence classification tasks.
4
-
5
- Usage:
6
- python examples/2_finetune_classification.py
7
- """
8
-
9
- import torch
10
- import numpy as np
11
- from torch.utils.data import Dataset, DataLoader
12
- from transformers import AutoModelForSequenceClassification, Trainer, TrainingArguments
13
-
14
-
15
- class GeneExpressionDataset(Dataset):
16
- """
17
- Simple dataset for gene expression classification.
18
- In practice, this would load from h5ad or other single-cell formats.
19
- """
20
-
21
- def __init__(self, input_ids, labels, max_length=2048):
22
- self.input_ids = input_ids
23
- self.labels = labels
24
- self.max_length = max_length
25
-
26
- def __len__(self):
27
- return len(self.input_ids)
28
-
29
- def __getitem__(self, idx):
30
- input_id = self.input_ids[idx]
31
- label = self.labels[idx]
32
-
33
- return {
34
- "input_ids": torch.tensor(input_id, dtype=torch.long),
35
- "labels": torch.tensor(label, dtype=torch.long),
36
- }
37
-
38
-
39
- def create_mock_data(n_samples=1000, n_features=2048, n_classes=5):
40
- """Create mock single-cell data for demonstration."""
41
-
42
- print("Creating mock dataset...")
43
-
44
- # Create random ranked gene sequences
45
- input_ids = np.random.randint(2, 25426, (n_samples, n_features))
46
-
47
- # Create random labels (e.g., cell types)
48
- labels = np.random.randint(0, n_classes, n_samples)
49
-
50
- # Split into train/val/test
51
- train_size = int(0.7 * n_samples)
52
- val_size = int(0.15 * n_samples)
53
-
54
- train_ids = input_ids[:train_size]
55
- train_labels = labels[:train_size]
56
-
57
- val_ids = input_ids[train_size:train_size + val_size]
58
- val_labels = labels[train_size:train_size + val_size]
59
-
60
- test_ids = input_ids[train_size + val_size:]
61
- test_labels = labels[train_size + val_size:]
62
-
63
- print(f"✓ Dataset created:")
64
- print(f" - Train: {len(train_ids)} samples")
65
- print(f" - Val: {len(val_ids)} samples")
66
- print(f" - Test: {len(test_ids)} samples")
67
- print(f" - Classes: {n_classes}")
68
-
69
- return (
70
- GeneExpressionDataset(train_ids, train_labels),
71
- GeneExpressionDataset(val_ids, val_labels),
72
- GeneExpressionDataset(test_ids, test_labels),
73
- )
74
-
75
-
76
- def main():
77
- print("=" * 80)
78
- print("GeneMamba Phase 2: Downstream Classification")
79
- print("=" * 80)
80
-
81
- # ============================================================
82
- # Step 1: Load pretrained model with classification head
83
- # ============================================================
84
- print("\n[Step 1] Loading pretrained model with classification head...")
85
-
86
- num_classes = 5
87
-
88
- try:
89
- model = AutoModelForSequenceClassification.from_pretrained(
90
- "GeneMamba-24l-512d",
91
- num_labels=num_classes,
92
- trust_remote_code=True,
93
- local_files_only=True,
94
- )
95
- except Exception as e:
96
- print(f"Note: Could not load from hub ({e})")
97
- print("Using local initialization...")
98
-
99
- # Initialize locally
100
- from configuration_genemamba import GeneMambaConfig
101
- from modeling_genemamba import GeneMambaForSequenceClassification
102
-
103
- config = GeneMambaConfig(
104
- vocab_size=25426,
105
- hidden_size=512,
106
- num_hidden_layers=24,
107
- num_labels=num_classes,
108
- )
109
- model = GeneMambaForSequenceClassification(config)
110
-
111
- print(f"✓ Model loaded")
112
- print(f" - Classification head: input={model.config.hidden_size} → output={num_classes}")
113
-
114
- # ============================================================
115
- # Step 2: Prepare data
116
- # ============================================================
117
- print("\n[Step 2] Preparing dataset...")
118
-
119
- train_dataset, val_dataset, test_dataset = create_mock_data(
120
- n_samples=1000,
121
- n_features=2048,
122
- n_classes=num_classes,
123
- )
124
-
125
- # ============================================================
126
- # Step 3: Set up training arguments
127
- # ============================================================
128
- print("\n[Step 3] Setting up training...")
129
-
130
- output_dir = "./classification_results"
131
-
132
- training_args = TrainingArguments(
133
- output_dir=output_dir,
134
- num_train_epochs=3,
135
- per_device_train_batch_size=16,
136
- per_device_eval_batch_size=16,
137
- learning_rate=2e-5,
138
- weight_decay=0.01,
139
- warmup_steps=100,
140
- logging_steps=50,
141
- eval_strategy="epoch",
142
- save_strategy="epoch",
143
- load_best_model_at_end=True,
144
- metric_for_best_model="accuracy",
145
- report_to="none", # Disable W&B logging
146
- seed=42,
147
- )
148
-
149
- print(f"✓ Training config:")
150
- print(f" - Output dir: {output_dir}")
151
- print(f" - Epochs: {training_args.num_train_epochs}")
152
- print(f" - Batch size: {training_args.per_device_train_batch_size}")
153
- print(f" - Learning rate: {training_args.learning_rate}")
154
-
155
- # ============================================================
156
- # Step 4: Train using Trainer
157
- # ============================================================
158
- print("\n[Step 4] Training model...")
159
-
160
- from sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score
161
-
162
- def compute_metrics(eval_pred):
163
- """Compute evaluation metrics."""
164
- predictions, labels = eval_pred
165
- predictions = np.argmax(predictions, axis=1)
166
-
167
- return {
168
- "accuracy": accuracy_score(labels, predictions),
169
- "f1": f1_score(labels, predictions, average="weighted", zero_division=0),
170
- "precision": precision_score(labels, predictions, average="weighted", zero_division=0),
171
- "recall": recall_score(labels, predictions, average="weighted", zero_division=0),
172
- }
173
-
174
- trainer = Trainer(
175
- model=model,
176
- args=training_args,
177
- train_dataset=train_dataset,
178
- eval_dataset=val_dataset,
179
- compute_metrics=compute_metrics,
180
- )
181
-
182
- train_result = trainer.train()
183
-
184
- print(f"✓ Training complete!")
185
- print(f" - Final training loss: {train_result.training_loss:.4f}")
186
-
187
- # ============================================================
188
- # Step 5: Evaluate on test set
189
- # ============================================================
190
- print("\n[Step 5] Evaluating on test set...")
191
-
192
- test_results = trainer.evaluate(test_dataset)
193
-
194
- print(f"✓ Test Results:")
195
- for metric, value in test_results.items():
196
- if isinstance(value, float):
197
- print(f" - {metric}: {value:.4f}")
198
-
199
- # ============================================================
200
- # Step 6: Make predictions
201
- # ============================================================
202
- print("\n[Step 6] Making predictions...")
203
-
204
- predictions = trainer.predict(test_dataset)
205
- predicted_classes = np.argmax(predictions.predictions, axis=1)
206
-
207
- print(f"✓ Predictions made:")
208
- print(f" - Predicted classes: {len(predicted_classes)} samples")
209
- print(f" - Class distribution: {np.bincount(predicted_classes)}")
210
-
211
- # ============================================================
212
- # Step 7: Save model
213
- # ============================================================
214
- print("\n[Step 7] Saving model...")
215
-
216
- save_dir = "./my_genemamba_classifier"
217
- model.save_pretrained(save_dir)
218
- print(f"✓ Model saved to '{save_dir}'")
219
-
220
- # ============================================================
221
- # Step 8: Load and test saved model
222
- # ============================================================
223
- print("\n[Step 8] Testing model reloading...")
224
-
225
- loaded_model = AutoModelForSequenceClassification.from_pretrained(
226
- save_dir,
227
- trust_remote_code=True,
228
- )
229
- loaded_model.eval()
230
-
231
- # Test on a single batch
232
- with torch.no_grad():
233
- sample_input = torch.randint(2, 25426, (1, 2048))
234
- output = loaded_model(sample_input)
235
- logits = output.logits
236
- prediction = torch.argmax(logits, dim=1)
237
-
238
- print(f"✓ Loaded model test prediction: class {prediction.item()}")
239
-
240
- print("\n" + "=" * 80)
241
- print("Phase 2 Complete! Model ready for deployment.")
242
- print("=" * 80)
243
-
244
- return model, trainer
245
-
246
-
247
- if __name__ == "__main__":
248
- model, trainer = main()