| import os |
| import math |
| import glob |
| from typing import Dict, List, Any |
|
|
| import torch |
| from datasets import load_dataset, DatasetDict |
| from transformers import ( |
| AutoTokenizer, |
| AutoModelForCausalLM, |
| Trainer, |
| TrainingArguments, |
| DataCollatorForLanguageModeling, |
| ) |
|
|
| MODEL_NAME = os.environ.get("MODEL_NAME", "meta-llama/Meta-Llama-3-8B") |
| TEXT_COL = os.environ.get("TEXT_COL", "text") |
|
|
| DATASET_ID = os.environ.get("DATASET_ID", "") |
| LOCAL_SHARDS_GLOB = os.environ.get("LOCAL_SHARDS_GLOB", "data/raw/train_shards_clean/train_*.jsonl") |
|
|
| TRAIN_SPLIT = os.environ.get("TRAIN_SPLIT", "train") |
| EVAL_SPLIT = os.environ.get("EVAL_SPLIT", "validation") |
|
|
| OUT_DIR = os.environ.get("OUT_DIR", "/workspace/outputs_cpt_llama3_8b") |
|
|
| MAX_LEN = int(os.environ.get("MAX_LEN", "2048")) |
|
|
| BATCH = int(os.environ.get("BATCH", "1")) |
| EVAL_BATCH = int(os.environ.get("EVAL_BATCH", "1")) |
| GAS = int(os.environ.get("GAS", "16")) |
| LR = float(os.environ.get("LR", "1e-5")) |
|
|
| STREAMING = os.environ.get("STREAMING", "1") == "1" |
| MAX_STEPS = int(os.environ.get("MAX_STEPS", "1000")) |
| EPOCHS = float(os.environ.get("EPOCHS", "1")) |
|
|
| LOGGING_STEPS = int(os.environ.get("LOGGING_STEPS", "10")) |
| SAVE_STEPS = int(os.environ.get("SAVE_STEPS", "500")) |
| EVAL_STEPS = int(os.environ.get("EVAL_STEPS", "500")) |
|
|
| FP16 = os.environ.get("FP16", "0") == "1" |
| BF16 = os.environ.get("BF16", "0") == "1" |
|
|
| PUSH_TO_HUB = os.environ.get("PUSH_TO_HUB", "0") == "1" |
| HF_MODEL_REPO = os.environ.get("HF_MODEL_REPO", "") |
|
|
| def load_train_eval() -> DatasetDict: |
| files = sorted(glob.glob(LOCAL_SHARDS_GLOB)) |
|
|
| if files: |
| print("LOCAL_SHARDS_GLOB:", LOCAL_SHARDS_GLOB) |
| print("Loading local shards:", len(files), "files") |
|
|
| data_files = {"train": files} |
|
|
| val_file = os.environ.get("VAL_FILE", "") |
| if val_file and os.path.exists(val_file): |
| data_files["validation"] = val_file |
|
|
| ds_train = load_dataset("json", data_files=data_files, split="train", streaming=STREAMING) |
|
|
| if "validation" in data_files: |
| ds_val = load_dataset("json", data_files=data_files, split="validation", streaming=STREAMING) |
| else: |
| take_n = int(os.environ.get("STREAM_EVAL_TAKE", "2000")) |
| ds_val = ds_train.take(take_n) |
|
|
| return DatasetDict({"train": ds_train, "validation": ds_val}) |
|
|
| if not DATASET_ID: |
| raise ValueError("No local shards found and DATASET_ID is empty. Set DATASET_ID or LOCAL_SHARDS_GLOB.") |
|
|
| print("DATASET_ID:", DATASET_ID) |
| ds = load_dataset(DATASET_ID) |
|
|
| if TRAIN_SPLIT not in ds: |
| raise ValueError(f"Train split '{TRAIN_SPLIT}' not found. Available: {list(ds.keys())}") |
| if EVAL_SPLIT not in ds: |
| raise ValueError(f"Eval split '{EVAL_SPLIT}' not found. Available: {list(ds.keys())}") |
|
|
| return DatasetDict({"train": ds[TRAIN_SPLIT], "validation": ds[EVAL_SPLIT]}) |
|
|
| def infer_remove_columns(ds_split): |
| |
| ex = next(iter(ds_split)) |
| cols = list(ex.keys()) |
| if TEXT_COL not in cols: |
| raise ValueError(f"TEXT_COL='{TEXT_COL}' not found. Columns: {cols}") |
| return cols |
|
|
| def normalize_text(x: Any) -> str: |
| |
| if x is None: |
| return "" |
| if isinstance(x, str): |
| return x |
| if isinstance(x, list): |
| |
| return " ".join([str(t) for t in x if t is not None]) |
| return str(x) |
|
|
| def main(): |
| print("MODEL_NAME:", MODEL_NAME) |
| print("OUT_DIR:", OUT_DIR) |
| print("STREAMING:", STREAMING) |
| print("FP16:", FP16, "BF16:", BF16) |
| if STREAMING: |
| print("MAX_STEPS:", MAX_STEPS) |
| else: |
| print("EPOCHS:", EPOCHS) |
|
|
| ds = load_train_eval() |
|
|
| try: |
| print("Train rows:", len(ds["train"])) |
| except Exception: |
| print("Train rows: (streaming, unknown)") |
| try: |
| print("Val rows:", len(ds["validation"])) |
| except Exception: |
| print("Val rows: (streaming, unknown)") |
|
|
| remove_cols_train = infer_remove_columns(ds["train"]) |
| remove_cols_val = infer_remove_columns(ds["validation"]) |
| print("Removing columns (train):", remove_cols_train) |
| print("Removing columns (val):", remove_cols_val) |
|
|
| tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, use_fast=True) |
| if tokenizer.pad_token is None: |
| tokenizer.pad_token = tokenizer.eos_token |
|
|
| def tokenize(batch: Dict[str, List]): |
| raw_texts = batch.get(TEXT_COL) |
| if raw_texts is None: |
| raise ValueError(f"Column '{TEXT_COL}' not found. Got: {list(batch.keys())}") |
|
|
| texts = [normalize_text(t) for t in raw_texts] |
| |
| texts = [t if t.strip() else tokenizer.eos_token for t in texts] |
|
|
| return tokenizer( |
| texts, |
| truncation=True, |
| max_length=MAX_LEN, |
| padding=False, |
| ) |
|
|
| |
| train_tok = ds["train"].map(tokenize, batched=True, remove_columns=remove_cols_train) |
| eval_tok = ds["validation"].map(tokenize, batched=True, remove_columns=remove_cols_val) |
|
|
| dtype = (torch.bfloat16 if BF16 else None) |
|
|
| model = AutoModelForCausalLM.from_pretrained( |
| MODEL_NAME, |
| dtype=dtype, |
| device_map="auto", |
| ) |
| model.resize_token_embeddings(len(tokenizer)) |
|
|
| collator = DataCollatorForLanguageModeling(tokenizer=tokenizer, mlm=False) |
|
|
| train_args = dict( |
| output_dir=OUT_DIR, |
| per_device_train_batch_size=BATCH, |
| per_device_eval_batch_size=EVAL_BATCH, |
| gradient_accumulation_steps=GAS, |
| learning_rate=LR, |
| logging_steps=LOGGING_STEPS, |
| save_steps=SAVE_STEPS, |
| eval_steps=EVAL_STEPS, |
| do_eval=True, |
| eval_strategy="steps", |
| save_strategy="steps", |
| report_to="none", |
| fp16=FP16, |
| bf16=BF16, |
| gradient_checkpointing=True, |
| save_total_limit=int(os.environ.get("SAVE_TOTAL_LIMIT", "2")), |
| dataloader_num_workers=int(os.environ.get("NUM_WORKERS", "2")), |
| remove_unused_columns=False, |
| ) |
|
|
| if STREAMING: |
| train_args["max_steps"] = MAX_STEPS |
| else: |
| train_args["num_train_epochs"] = EPOCHS |
|
|
| args = TrainingArguments(**train_args) |
|
|
| trainer = Trainer( |
| model=model, |
| args=args, |
| train_dataset=train_tok, |
| eval_dataset=eval_tok, |
| data_collator=collator, |
| tokenizer=tokenizer, |
| ) |
|
|
| print("\nStarting CPT training...") |
| trainer.train() |
|
|
| metrics = trainer.evaluate() |
| print("\nEval metrics:", metrics) |
| if "eval_loss" in metrics: |
| print("Perplexity:", math.exp(metrics["eval_loss"])) |
|
|
| trainer.save_model(OUT_DIR) |
| tokenizer.save_pretrained(OUT_DIR) |
| print("\nSaved to:", OUT_DIR) |
|
|
| if PUSH_TO_HUB: |
| if not HF_MODEL_REPO: |
| raise ValueError("PUSH_TO_HUB=1 but HF_MODEL_REPO is empty.") |
| print("\nPushing to HF model repo:", HF_MODEL_REPO) |
| trainer.model.push_to_hub(HF_MODEL_REPO) |
| tokenizer.push_to_hub(HF_MODEL_REPO) |
| print("✅ Pushed to:", HF_MODEL_REPO) |
|
|
| if __name__ == "__main__": |
| main() |
|
|