Instructions to use mineself2016/GeneMamba with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use mineself2016/GeneMamba with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("feature-extraction", model="mineself2016/GeneMamba", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("mineself2016/GeneMamba", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
Use next-token training and checkpoint resume in train-from-scratch
Browse files
examples/4_pretrain_from_scratch.py
CHANGED
|
@@ -1,6 +1,7 @@
|
|
| 1 |
"""
|
| 2 |
-
Phase
|
| 3 |
-
Demonstrates how to initialize and train
|
|
|
|
| 4 |
|
| 5 |
Usage:
|
| 6 |
python examples/4_pretrain_from_scratch.py
|
|
@@ -9,11 +10,12 @@ Usage:
|
|
| 9 |
import torch
|
| 10 |
import numpy as np
|
| 11 |
from torch.utils.data import Dataset
|
|
|
|
| 12 |
from transformers import (
|
| 13 |
-
|
|
|
|
| 14 |
Trainer,
|
| 15 |
TrainingArguments,
|
| 16 |
-
DataCollatorForLanguageModeling,
|
| 17 |
)
|
| 18 |
|
| 19 |
|
|
@@ -45,6 +47,34 @@ class PretrainingDataset(Dataset):
|
|
| 45 |
}
|
| 46 |
|
| 47 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
def create_mock_pretraining_data(n_sequences=5000, seq_len=2048):
|
| 49 |
"""Create mock pretraining data."""
|
| 50 |
|
|
@@ -62,43 +92,59 @@ def create_mock_pretraining_data(n_sequences=5000, seq_len=2048):
|
|
| 62 |
|
| 63 |
def main():
|
| 64 |
print("=" * 80)
|
| 65 |
-
print("GeneMamba Phase
|
| 66 |
print("=" * 80)
|
|
|
|
|
|
|
|
|
|
| 67 |
|
| 68 |
# ============================================================
|
| 69 |
-
# Step 1:
|
| 70 |
# ============================================================
|
| 71 |
-
print("\n[Step 1]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
from configuration_genemamba import GeneMambaConfig
|
| 74 |
from modeling_genemamba import GeneMambaForMaskedLM
|
| 75 |
|
| 76 |
-
|
| 77 |
vocab_size=25426,
|
| 78 |
hidden_size=256, # Smaller for faster demo
|
| 79 |
num_hidden_layers=12, # Reduced for demo
|
| 80 |
intermediate_size=1024,
|
| 81 |
max_position_embeddings=2048,
|
| 82 |
-
mamba_mode="
|
| 83 |
embedding_pooling="mean",
|
| 84 |
num_labels=2,
|
| 85 |
hidden_dropout_prob=0.1,
|
| 86 |
initializer_range=0.02,
|
| 87 |
)
|
| 88 |
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
model = GeneMambaForMaskedLM(config)
|
| 102 |
|
| 103 |
# Count parameters
|
| 104 |
total_params = sum(p.numel() for p in model.parameters())
|
|
@@ -128,29 +174,11 @@ def main():
|
|
| 128 |
print(f" - Eval: {len(eval_dataset)}")
|
| 129 |
|
| 130 |
# ============================================================
|
| 131 |
-
# Step 4: Data collator for
|
| 132 |
# ============================================================
|
| 133 |
print("\n[Step 4] Setting up data collator...")
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
"""Custom collator for MLM without tokenizer."""
|
| 137 |
-
|
| 138 |
-
def __call__(self, batch):
|
| 139 |
-
input_ids = torch.stack([item["input_ids"] for item in batch])
|
| 140 |
-
|
| 141 |
-
# Create labels for MLM
|
| 142 |
-
labels = input_ids.clone()
|
| 143 |
-
|
| 144 |
-
# Mask 15% of tokens
|
| 145 |
-
mask = torch.rand(input_ids.shape) < 0.15
|
| 146 |
-
input_ids[mask] = 0 # [MASK] token
|
| 147 |
-
|
| 148 |
-
# Don't compute loss on non-masked tokens
|
| 149 |
-
labels[~mask] = -100
|
| 150 |
-
|
| 151 |
-
return {"input_ids": input_ids, "labels": labels}
|
| 152 |
-
|
| 153 |
-
data_collator = CustomDataCollator()
|
| 154 |
print(f"✓ Data collator ready")
|
| 155 |
|
| 156 |
# ============================================================
|
|
@@ -189,18 +217,18 @@ def main():
|
|
| 189 |
# ============================================================
|
| 190 |
# Step 6: Train
|
| 191 |
# ============================================================
|
| 192 |
-
print("\n[Step 6] Starting training
|
| 193 |
print("(This may take a while. In practice, use more GPUs/data for real pretraining)")
|
| 194 |
|
| 195 |
-
trainer =
|
| 196 |
model=model,
|
| 197 |
args=training_args,
|
| 198 |
train_dataset=train_dataset,
|
| 199 |
eval_dataset=eval_dataset,
|
| 200 |
data_collator=data_collator,
|
| 201 |
)
|
| 202 |
-
|
| 203 |
-
train_result = trainer.train()
|
| 204 |
|
| 205 |
print(f"✓ Training complete!")
|
| 206 |
print(f" - Final training loss: {train_result.training_loss:.4f}")
|
|
@@ -224,7 +252,7 @@ def main():
|
|
| 224 |
|
| 225 |
save_dir = "./my_genemamba_from_scratch"
|
| 226 |
model.save_pretrained(save_dir)
|
| 227 |
-
|
| 228 |
|
| 229 |
print(f"✓ Model and config saved to '{save_dir}'")
|
| 230 |
print(f" Files created:")
|
|
@@ -236,8 +264,6 @@ def main():
|
|
| 236 |
# ============================================================
|
| 237 |
print("\n[Step 9] Reloading model from checkpoint...")
|
| 238 |
|
| 239 |
-
from transformers import AutoModelForMaskedLM
|
| 240 |
-
|
| 241 |
loaded_model = AutoModelForMaskedLM.from_pretrained(
|
| 242 |
save_dir,
|
| 243 |
trust_remote_code=True,
|
|
@@ -248,8 +274,6 @@ def main():
|
|
| 248 |
# Test inference
|
| 249 |
with torch.no_grad():
|
| 250 |
sample_input = torch.randint(2, 25426, (2, 2048))
|
| 251 |
-
sample_input[:, :10] = 0 # Mask first 10 tokens
|
| 252 |
-
|
| 253 |
outputs = loaded_model(sample_input)
|
| 254 |
logits = outputs.logits
|
| 255 |
|
|
@@ -270,7 +294,7 @@ def main():
|
|
| 270 |
print(f" AutoModel.from_pretrained('{save_dir}')")
|
| 271 |
|
| 272 |
print("\n" + "=" * 80)
|
| 273 |
-
print("Phase
|
| 274 |
print("=" * 80)
|
| 275 |
|
| 276 |
return model, trainer, config
|
|
|
|
| 1 |
"""
|
| 2 |
+
Phase 3: Train from Scratch (Next-Token Objective)
|
| 3 |
+
Demonstrates how to initialize and train GeneMamba with next-token prediction.
|
| 4 |
+
If a checkpoint exists, training resumes from checkpoint automatically.
|
| 5 |
|
| 6 |
Usage:
|
| 7 |
python examples/4_pretrain_from_scratch.py
|
|
|
|
| 10 |
import torch
|
| 11 |
import numpy as np
|
| 12 |
from torch.utils.data import Dataset
|
| 13 |
+
from pathlib import Path
|
| 14 |
from transformers import (
|
| 15 |
+
AutoTokenizer,
|
| 16 |
+
AutoModelForMaskedLM,
|
| 17 |
Trainer,
|
| 18 |
TrainingArguments,
|
|
|
|
| 19 |
)
|
| 20 |
|
| 21 |
|
|
|
|
| 47 |
}
|
| 48 |
|
| 49 |
|
| 50 |
+
class NextTokenTrainer(Trainer):
|
| 51 |
+
"""Use next-token prediction loss: logits[:, :-1] vs labels[:, 1:]."""
|
| 52 |
+
|
| 53 |
+
def compute_loss(self, model, inputs, return_outputs=False):
|
| 54 |
+
input_ids = inputs["input_ids"]
|
| 55 |
+
outputs = model(input_ids=input_ids)
|
| 56 |
+
logits = outputs.logits
|
| 57 |
+
|
| 58 |
+
shift_logits = logits[:, :-1, :].contiguous()
|
| 59 |
+
shift_labels = input_ids[:, 1:].contiguous().to(shift_logits.device)
|
| 60 |
+
|
| 61 |
+
loss_fct = torch.nn.CrossEntropyLoss()
|
| 62 |
+
loss = loss_fct(
|
| 63 |
+
shift_logits.view(-1, shift_logits.size(-1)),
|
| 64 |
+
shift_labels.view(-1),
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
return (loss, outputs) if return_outputs else loss
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
class NextTokenDataCollator:
|
| 71 |
+
"""Simple collator for pre-tokenized input_ids (no MLM masking)."""
|
| 72 |
+
|
| 73 |
+
def __call__(self, batch):
|
| 74 |
+
input_ids = torch.stack([item["input_ids"] for item in batch])
|
| 75 |
+
return {"input_ids": input_ids}
|
| 76 |
+
|
| 77 |
+
|
| 78 |
def create_mock_pretraining_data(n_sequences=5000, seq_len=2048):
|
| 79 |
"""Create mock pretraining data."""
|
| 80 |
|
|
|
|
| 92 |
|
| 93 |
def main():
|
| 94 |
print("=" * 80)
|
| 95 |
+
print("GeneMamba Phase 3: Train from Scratch (Next-Token)")
|
| 96 |
print("=" * 80)
|
| 97 |
+
|
| 98 |
+
model_id = "mineself2016/GeneMamba"
|
| 99 |
+
checkpoint_dir = Path("./from_scratch_pretrain/checkpoint-last")
|
| 100 |
|
| 101 |
# ============================================================
|
| 102 |
+
# Step 1: Load tokenizer spec
|
| 103 |
# ============================================================
|
| 104 |
+
print("\n[Step 1] Loading tokenizer...")
|
| 105 |
+
|
| 106 |
+
tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
|
| 107 |
+
|
| 108 |
+
print("✓ Tokenizer loaded:")
|
| 109 |
+
print(f" - vocab_size: {tokenizer.vocab_size}")
|
| 110 |
+
print(f" - [UNK] token/id: {tokenizer.unk_token}/{tokenizer.unk_token_id}")
|
| 111 |
+
print(f" - [PAD] token/id: {tokenizer.pad_token}/{tokenizer.pad_token_id}")
|
| 112 |
+
print(f" - [CLS] token/id: {tokenizer.cls_token}/{tokenizer.cls_token_id}")
|
| 113 |
+
print(f" - [MASK] token/id: {tokenizer.mask_token}/{tokenizer.mask_token_id}")
|
| 114 |
|
| 115 |
+
# ============================================================
|
| 116 |
+
# Step 2: Build config and initialize/resume model
|
| 117 |
+
# ============================================================
|
| 118 |
+
print("\n[Step 2] Building model (resume if checkpoint exists)...")
|
| 119 |
+
|
| 120 |
from configuration_genemamba import GeneMambaConfig
|
| 121 |
from modeling_genemamba import GeneMambaForMaskedLM
|
| 122 |
|
| 123 |
+
model_config = GeneMambaConfig(
|
| 124 |
vocab_size=25426,
|
| 125 |
hidden_size=256, # Smaller for faster demo
|
| 126 |
num_hidden_layers=12, # Reduced for demo
|
| 127 |
intermediate_size=1024,
|
| 128 |
max_position_embeddings=2048,
|
| 129 |
+
mamba_mode="mean",
|
| 130 |
embedding_pooling="mean",
|
| 131 |
num_labels=2,
|
| 132 |
hidden_dropout_prob=0.1,
|
| 133 |
initializer_range=0.02,
|
| 134 |
)
|
| 135 |
|
| 136 |
+
if checkpoint_dir.exists():
|
| 137 |
+
model = AutoModelForMaskedLM.from_pretrained(
|
| 138 |
+
str(checkpoint_dir),
|
| 139 |
+
trust_remote_code=True,
|
| 140 |
+
local_files_only=True,
|
| 141 |
+
)
|
| 142 |
+
resume_from_checkpoint = str(checkpoint_dir)
|
| 143 |
+
print(f"✓ Found checkpoint, resume from: {checkpoint_dir}")
|
| 144 |
+
else:
|
| 145 |
+
model = GeneMambaForMaskedLM(model_config)
|
| 146 |
+
resume_from_checkpoint = None
|
| 147 |
+
print("✓ No checkpoint found, start from scratch")
|
|
|
|
| 148 |
|
| 149 |
# Count parameters
|
| 150 |
total_params = sum(p.numel() for p in model.parameters())
|
|
|
|
| 174 |
print(f" - Eval: {len(eval_dataset)}")
|
| 175 |
|
| 176 |
# ============================================================
|
| 177 |
+
# Step 4: Data collator for next-token training
|
| 178 |
# ============================================================
|
| 179 |
print("\n[Step 4] Setting up data collator...")
|
| 180 |
+
|
| 181 |
+
data_collator = NextTokenDataCollator()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 182 |
print(f"✓ Data collator ready")
|
| 183 |
|
| 184 |
# ============================================================
|
|
|
|
| 217 |
# ============================================================
|
| 218 |
# Step 6: Train
|
| 219 |
# ============================================================
|
| 220 |
+
print("\n[Step 6] Starting training...")
|
| 221 |
print("(This may take a while. In practice, use more GPUs/data for real pretraining)")
|
| 222 |
|
| 223 |
+
trainer = NextTokenTrainer(
|
| 224 |
model=model,
|
| 225 |
args=training_args,
|
| 226 |
train_dataset=train_dataset,
|
| 227 |
eval_dataset=eval_dataset,
|
| 228 |
data_collator=data_collator,
|
| 229 |
)
|
| 230 |
+
|
| 231 |
+
train_result = trainer.train(resume_from_checkpoint=resume_from_checkpoint)
|
| 232 |
|
| 233 |
print(f"✓ Training complete!")
|
| 234 |
print(f" - Final training loss: {train_result.training_loss:.4f}")
|
|
|
|
| 252 |
|
| 253 |
save_dir = "./my_genemamba_from_scratch"
|
| 254 |
model.save_pretrained(save_dir)
|
| 255 |
+
model_config.save_pretrained(save_dir)
|
| 256 |
|
| 257 |
print(f"✓ Model and config saved to '{save_dir}'")
|
| 258 |
print(f" Files created:")
|
|
|
|
| 264 |
# ============================================================
|
| 265 |
print("\n[Step 9] Reloading model from checkpoint...")
|
| 266 |
|
|
|
|
|
|
|
| 267 |
loaded_model = AutoModelForMaskedLM.from_pretrained(
|
| 268 |
save_dir,
|
| 269 |
trust_remote_code=True,
|
|
|
|
| 274 |
# Test inference
|
| 275 |
with torch.no_grad():
|
| 276 |
sample_input = torch.randint(2, 25426, (2, 2048))
|
|
|
|
|
|
|
| 277 |
outputs = loaded_model(sample_input)
|
| 278 |
logits = outputs.logits
|
| 279 |
|
|
|
|
| 294 |
print(f" AutoModel.from_pretrained('{save_dir}')")
|
| 295 |
|
| 296 |
print("\n" + "=" * 80)
|
| 297 |
+
print("Phase 3 Complete! Model trained from scratch and ready to use.")
|
| 298 |
print("=" * 80)
|
| 299 |
|
| 300 |
return model, trainer, config
|