Create training/train.py
Browse files- training/train.py +135 -0
training/train.py
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os, logging, torch, transformers
|
| 2 |
+
from dataclasses import dataclass, field
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from typing import Optional
|
| 5 |
+
from transformers import TrainingArguments, Trainer, TrainerCallback, set_seed
|
| 6 |
+
import sys
|
| 7 |
+
sys.path.insert(0, str(Path(__file__).parent.parent))
|
| 8 |
+
from model.architecture import CodeLLM, CodeLLMConfig
|
| 9 |
+
from model.tokenizer import get_gpt2_tokenizer_for_code, load_tokenizer
|
| 10 |
+
from data.dataset import TheStackStreamDataset, CodeCollator
|
| 11 |
+
|
| 12 |
+
logging.basicConfig(level=logging.INFO)
|
| 13 |
+
logger = logging.getLogger(__name__)
|
| 14 |
+
|
| 15 |
+
@dataclass
|
| 16 |
+
class TrainConfig:
|
| 17 |
+
model_config: CodeLLMConfig = field(default_factory=CodeLLMConfig)
|
| 18 |
+
tokenizer_path: Optional[str] = None
|
| 19 |
+
languages: list = field(default_factory=lambda: ["python", "javascript", "typescript", "rust"])
|
| 20 |
+
max_length: int = 2048
|
| 21 |
+
fim_rate: float = 0.5
|
| 22 |
+
output_dir: str = "./checkpoints"
|
| 23 |
+
num_train_steps: int = 100_000
|
| 24 |
+
per_device_batch_size: int = 4
|
| 25 |
+
gradient_accumulation_steps: int = 8
|
| 26 |
+
learning_rate: float = 3e-4
|
| 27 |
+
weight_decay: float = 0.1
|
| 28 |
+
max_grad_norm: float = 1.0
|
| 29 |
+
warmup_steps: int = 2000
|
| 30 |
+
lr_scheduler_type: str = "cosine"
|
| 31 |
+
bf16: bool = True
|
| 32 |
+
fp16: bool = False
|
| 33 |
+
gradient_checkpointing: bool = True
|
| 34 |
+
dataloader_num_workers: int = 4
|
| 35 |
+
logging_steps: int = 50
|
| 36 |
+
save_steps: int = 1000
|
| 37 |
+
push_to_hub: bool = True
|
| 38 |
+
hub_model_id: str = "devoppro/codellm-125m" # ← your HF username
|
| 39 |
+
seed: int = 42
|
| 40 |
+
|
| 41 |
+
class CodeLLMForTrainer(torch.nn.Module):
|
| 42 |
+
def __init__(self, model):
|
| 43 |
+
super().__init__()
|
| 44 |
+
self.model = model
|
| 45 |
+
|
| 46 |
+
def forward(self, input_ids=None, labels=None, attention_mask=None, **kwargs):
|
| 47 |
+
out = self.model(input_ids=input_ids, labels=labels, attention_mask=attention_mask)
|
| 48 |
+
return transformers.modeling_outputs.CausalLMOutputWithPast(
|
| 49 |
+
loss=out["loss"], logits=out["logits"],
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
def gradient_checkpointing_enable(self, **kwargs):
|
| 53 |
+
for block in self.model.transformer.h:
|
| 54 |
+
block.use_checkpoint = True
|
| 55 |
+
|
| 56 |
+
@property
|
| 57 |
+
def config(self):
|
| 58 |
+
class FakeConfig:
|
| 59 |
+
is_encoder_decoder = False
|
| 60 |
+
model_type = "codellm"
|
| 61 |
+
return FakeConfig()
|
| 62 |
+
|
| 63 |
+
class GenerateSampleCallback(TrainerCallback):
|
| 64 |
+
def __init__(self, model, tokenizer, prompts):
|
| 65 |
+
self.model = model
|
| 66 |
+
self.tokenizer = tokenizer
|
| 67 |
+
self.prompts = prompts
|
| 68 |
+
|
| 69 |
+
def on_evaluate(self, args, state, control, **kwargs):
|
| 70 |
+
self.model.eval()
|
| 71 |
+
device = next(self.model.parameters()).device
|
| 72 |
+
print("\n" + "="*60)
|
| 73 |
+
for prompt in self.prompts:
|
| 74 |
+
ids = self.tokenizer.encode(prompt, return_tensors="pt").to(device)
|
| 75 |
+
out = self.model.generate(ids, max_new_tokens=128, temperature=0.8)
|
| 76 |
+
text = self.tokenizer.decode(out[0], skip_special_tokens=True)
|
| 77 |
+
print(f"\n[PROMPT] {prompt}\n[OUTPUT] {text[len(prompt):]}")
|
| 78 |
+
print("="*60 + "\n")
|
| 79 |
+
|
| 80 |
+
def train(cfg: TrainConfig):
|
| 81 |
+
set_seed(cfg.seed)
|
| 82 |
+
if cfg.tokenizer_path and Path(cfg.tokenizer_path).exists():
|
| 83 |
+
tokenizer = load_tokenizer(cfg.tokenizer_path)
|
| 84 |
+
else:
|
| 85 |
+
tokenizer = get_gpt2_tokenizer_for_code()
|
| 86 |
+
cfg.model_config.vocab_size = len(tokenizer)
|
| 87 |
+
model_core = CodeLLM(cfg.model_config)
|
| 88 |
+
model = CodeLLMForTrainer(model_core)
|
| 89 |
+
if cfg.gradient_checkpointing:
|
| 90 |
+
model.gradient_checkpointing_enable()
|
| 91 |
+
train_dataset = TheStackStreamDataset(
|
| 92 |
+
tokenizer=tokenizer, max_length=cfg.max_length,
|
| 93 |
+
languages=cfg.languages, fim_rate=cfg.fim_rate,
|
| 94 |
+
)
|
| 95 |
+
collator = CodeCollator(pad_token_id=tokenizer.pad_token_id or 0, max_length=cfg.max_length)
|
| 96 |
+
training_args = TrainingArguments(
|
| 97 |
+
output_dir=cfg.output_dir,
|
| 98 |
+
max_steps=cfg.num_train_steps,
|
| 99 |
+
per_device_train_batch_size=cfg.per_device_batch_size,
|
| 100 |
+
gradient_accumulation_steps=cfg.gradient_accumulation_steps,
|
| 101 |
+
learning_rate=cfg.learning_rate,
|
| 102 |
+
weight_decay=cfg.weight_decay,
|
| 103 |
+
max_grad_norm=cfg.max_grad_norm,
|
| 104 |
+
warmup_steps=cfg.warmup_steps,
|
| 105 |
+
lr_scheduler_type=cfg.lr_scheduler_type,
|
| 106 |
+
bf16=cfg.bf16, fp16=cfg.fp16,
|
| 107 |
+
dataloader_num_workers=cfg.dataloader_num_workers,
|
| 108 |
+
logging_steps=cfg.logging_steps,
|
| 109 |
+
save_steps=cfg.save_steps,
|
| 110 |
+
save_total_limit=3,
|
| 111 |
+
push_to_hub=cfg.push_to_hub,
|
| 112 |
+
hub_model_id=cfg.hub_model_id if cfg.push_to_hub else None,
|
| 113 |
+
report_to=["tensorboard"],
|
| 114 |
+
remove_unused_columns=False,
|
| 115 |
+
prediction_loss_only=True,
|
| 116 |
+
optim="adamw_torch_fused",
|
| 117 |
+
)
|
| 118 |
+
trainer = Trainer(
|
| 119 |
+
model=model, args=training_args,
|
| 120 |
+
train_dataset=train_dataset, data_collator=collator,
|
| 121 |
+
callbacks=[GenerateSampleCallback(model_core, tokenizer, [
|
| 122 |
+
"<|python|>def fibonacci(n):",
|
| 123 |
+
"<|javascript|>async function fetchData(url) {",
|
| 124 |
+
])],
|
| 125 |
+
)
|
| 126 |
+
trainer.train()
|
| 127 |
+
output_path = Path(cfg.output_dir) / "final"
|
| 128 |
+
output_path.mkdir(parents=True, exist_ok=True)
|
| 129 |
+
torch.save(model_core.state_dict(), output_path / "pytorch_model.bin")
|
| 130 |
+
tokenizer.save_pretrained(output_path)
|
| 131 |
+
if cfg.push_to_hub:
|
| 132 |
+
trainer.push_to_hub()
|
| 133 |
+
|
| 134 |
+
if __name__ == "__main__":
|
| 135 |
+
train(TrainConfig())
|