Njap-png commited on
Commit ·
094a4b8
1
Parent(s): 891707a
Add from-scratch training script (configurable size/dataset)
Browse files- train_from_scratch.py +102 -0
train_from_scratch.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Train an Agron base LLM FROM SCRATCH (random initialization).
|
| 3 |
+
|
| 4 |
+
Usage examples:
|
| 5 |
+
python train_from_scratch.py --size small --steps 500
|
| 6 |
+
python train_from_scratch.py --size medium --dataset wikitext --steps 2000
|
| 7 |
+
python train_from_scratch.py --size current --dataset file --file mycorpus.txt --steps 1000
|
| 8 |
+
"""
|
| 9 |
+
import os
|
| 10 |
+
import argparse
|
| 11 |
+
import torch
|
| 12 |
+
from datasets import load_dataset, Dataset
|
| 13 |
+
from transformers import LlamaConfig, LlamaForCausalLM, PreTrainedTokenizerFast, Trainer, TrainingArguments, DataCollatorForLanguageModeling
|
| 14 |
+
|
| 15 |
+
# Base architecture presets
|
| 16 |
+
PRESETS = {
|
| 17 |
+
"small": {"vocab_size": 16384, "hidden_size": 256, "intermediate_size": 1024, "num_hidden_layers": 4, "num_attention_heads": 4, "num_key_value_heads": 4},
|
| 18 |
+
"current": {"vocab_size": 16384, "hidden_size": 512, "intermediate_size": 2048, "num_hidden_layers": 8, "num_attention_heads": 4, "num_key_value_heads": 4},
|
| 19 |
+
"medium": {"vocab_size": 16384, "hidden_size": 768, "intermediate_size": 3072, "num_hidden_layers": 12, "num_attention_heads": 6, "num_key_value_heads": 6},
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
ROOT = os.path.dirname(os.path.abspath(__file__))
|
| 23 |
+
TOKENIZER_FILE = os.path.join(ROOT, "tokenizer.json")
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def tokenize_dataset(tok, text_list, block_size=256):
|
| 27 |
+
tokenized = tok(text_list, truncation=False)["input_ids"]
|
| 28 |
+
chunks = []
|
| 29 |
+
buf = []
|
| 30 |
+
for ids in tokenized:
|
| 31 |
+
buf.extend(ids)
|
| 32 |
+
while len(buf) >= block_size:
|
| 33 |
+
chunks.append(buf[:block_size])
|
| 34 |
+
buf = buf[block_size:]
|
| 35 |
+
if len(buf) >= block_size // 2:
|
| 36 |
+
chunks.append(buf + [tok.pad_token_id] * (block_size - len(buf)))
|
| 37 |
+
if not chunks:
|
| 38 |
+
raise RuntimeError("no training chunks produced")
|
| 39 |
+
return Dataset.from_dict({"input_ids": chunks, "labels": [c[:] for c in chunks]})
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def main():
|
| 43 |
+
ap = argparse.ArgumentParser()
|
| 44 |
+
ap.add_argument("--size", choices=list(PRESETS), default="small")
|
| 45 |
+
ap.add_argument("--steps", type=int, default=500)
|
| 46 |
+
ap.add_argument("--dataset", choices=["wikitext", "file"], default="wikitext")
|
| 47 |
+
ap.add_argument("--file", type=str, default=None, help="text file for --dataset file (one doc per line or paragraph)")
|
| 48 |
+
ap.add_argument("--output", type=str, default=None)
|
| 49 |
+
args = ap.parse_args()
|
| 50 |
+
|
| 51 |
+
tok = PreTrainedTokenizerFast(tokenizer_file=TOKENIZER_FILE)
|
| 52 |
+
tok.pad_token = "<pad>"; tok.bos_token = "<s>"; tok.eos_token = "</s>"; tok.unk_token = "<unk>"
|
| 53 |
+
|
| 54 |
+
cfg = PRESETS[args.size]
|
| 55 |
+
cfg.update({"max_position_embeddings": 512, "bos_token_id": 0, "eos_token_id": 2, "pad_token_id": 1, "tie_word_embeddings": False})
|
| 56 |
+
model = LlamaForCausalLM(LlamaConfig(**cfg))
|
| 57 |
+
print("Initialized from-scratch model:", args.size, "params:", model.num_parameters())
|
| 58 |
+
|
| 59 |
+
# data
|
| 60 |
+
if args.dataset == "wikitext":
|
| 61 |
+
from datasets import load_dataset as ld
|
| 62 |
+
ds = ld("Salesforce/wikitext", "wikitext-2-raw-v1")
|
| 63 |
+
texts = [x["text"] for x in ds["train"] if x["text"].strip()]
|
| 64 |
+
else:
|
| 65 |
+
if not args.file or not os.path.exists(args.file):
|
| 66 |
+
raise RuntimeError("Provide existing --file for --dataset file")
|
| 67 |
+
with open(args.file, "r", encoding="utf-8") as f:
|
| 68 |
+
texts = [ln.strip() for ln in f if ln.strip()]
|
| 69 |
+
|
| 70 |
+
train_ds = tokenize_dataset(tok, texts, block_size=256)
|
| 71 |
+
|
| 72 |
+
out_dir = args.output or os.path.join("/content", f"agron-scratch-{args.size}")
|
| 73 |
+
os.makedirs(out_dir, exist_ok=True)
|
| 74 |
+
|
| 75 |
+
ta = TrainingArguments(
|
| 76 |
+
output_dir=out_dir,
|
| 77 |
+
per_device_train_batch_size=8,
|
| 78 |
+
max_steps=args.steps,
|
| 79 |
+
learning_rate=5e-05,
|
| 80 |
+
optim="adamw_torch_fused",
|
| 81 |
+
fp16=True if torch.cuda.is_available() else False,
|
| 82 |
+
logging_steps=25,
|
| 83 |
+
save_strategy="steps",
|
| 84 |
+
save_steps=max(100, args.steps // 2),
|
| 85 |
+
save_total_limit=2,
|
| 86 |
+
report_to=[],
|
| 87 |
+
remove_unused_columns=True,
|
| 88 |
+
seed=42,
|
| 89 |
+
)
|
| 90 |
+
collator = DataCollatorForLanguageModeling(tokenizer=tok, mlm=False)
|
| 91 |
+
trainer = Trainer(model=model, args=ta, train_dataset=train_ds, data_collator=collator, processing_class=tok)
|
| 92 |
+
trainer.train()
|
| 93 |
+
|
| 94 |
+
final = os.path.join(out_dir, "final")
|
| 95 |
+
os.makedirs(final, exist_ok=True)
|
| 96 |
+
model.save_pretrained(final)
|
| 97 |
+
tok.save_pretrained(final)
|
| 98 |
+
print("From-scratch training complete:", final)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
if __name__ == "__main__":
|
| 102 |
+
main()
|