Datasets:

DOI:
naturally-intuitive's picture
Upload folder using huggingface_hub
1769068 verified
Raw
History Blame Contribute Delete
6.15 kB
#!/usr/bin/env python3
"""
PENTABRID V14 — LoRA TRAINER (27B, attention-only, ZeRO-2)
==========================================================
Locked config: LoRA r16 / alpha16, attention-only, 1 epoch, LR 1.5e-5 cosine +
3% warmup, MAX_SEQ_LEN 8192, bf16, DeepSpeed ZeRO-2 (NOT ZeRO-3: no NVLink on
these A100s). Loss is masked to the answer only (the prompt is not trained on).
** SMOKE FIRST ** Launch once with SMOKE=1 -> trains ~20 steps on 64 rows to
prove it loads, fits in memory, and steps without crashing. Only then do the full
run. This is the single riskiest step (future transformers/PEFT API + Qwen3.6
chat template), so we validate cheaply before committing hours.
Three things to VERIFY on the smoke (Claude will check the smoke log with you):
1. target_modules names are right for Qwen3.6 (q_proj/k_proj/v_proj/o_proj).
2. the chat template doesn't double-wrap the <think> tags already in `output`.
3. no CUDA OOM at seq 8192 (if OOM: drop MAXLEN to 6144, or set LOAD_4BIT=1).
USAGE (via train_v14.sbatch; do not run by hand on the login node):
SMOKE=1 torchrun --standalone --nproc_per_node=2 train_v14.py # smoke
torchrun --standalone --nproc_per_node=2 train_v14.py # full
"""
import os
import torch
from transformers import (AutoModelForCausalLM, AutoTokenizer,
TrainingArguments, Trainer)
from peft import LoraConfig, get_peft_model
from datasets import load_dataset
MODEL_DIR = os.environ.get("MODEL_DIR", "/home/adnanagha/pentabrid/base_models/Qwen3.6-27B")
DATA = os.environ.get("DATA", "/home/adnanagha/pentabrid/scripts/v14_train_final.jsonl")
OUT = os.environ.get("OUT", "/home/adnanagha/pentabrid/runs/V14_lora")
MAXLEN = int(os.environ.get("MAXLEN", "8192"))
SMOKE = os.environ.get("SMOKE", "") not in ("", "0", "false")
RESUME = bool(os.environ.get("RESUME"))
if os.path.isdir(OUT) and os.listdir(OUT) and not RESUME:
raise SystemExit("REFUSING to overwrite non-empty OUT dir: " + OUT + " (use a new OUT=... or set RESUME=1)")
# DeepSpeed ZeRO-2 (full frozen base kept on each GPU; only optimizer/grads sharded)
DS_CONFIG = {
"bf16": {"enabled": True},
"zero_optimization": {
"stage": 2,
"overlap_comm": True,
"contiguous_gradients": True,
"reduce_bucket_size": 2e8,
"allgather_bucket_size": 2e8,
},
"gradient_accumulation_steps": "auto",
"train_micro_batch_size_per_gpu": "auto",
"gradient_clipping": "auto",
}
tok = AutoTokenizer.from_pretrained(MODEL_DIR)
if tok.pad_token is None:
tok.pad_token = tok.eos_token
def _ids(out):
"""Return a plain list[int] of token ids from apply_chat_template, regardless
of whether this transformers version returns a list, a tensor, or an Encoding/
BatchEncoding (the latter triggers an Arrow OverflowError if passed through)."""
if hasattr(out, "input_ids"): # BatchEncoding / Encoding
out = out.input_ids
if hasattr(out, "ids"): # tokenizers.Encoding
out = out.ids
if hasattr(out, "tolist"): # tensor / numpy
out = out.tolist()
if out and isinstance(out[0], list): # nested [[...]] -> first row
out = out[0]
return [int(t) for t in out]
def to_example(row):
"""Tokenize one row; mask the prompt so loss falls only on the answer."""
user = row["instruction"] + (("\n\n" + row["input"]) if row.get("input") else "")
msgs = [{"role": "user", "content": user}]
prompt_ids = _ids(tok.apply_chat_template(msgs, add_generation_prompt=True, tokenize=True))
full_ids = _ids(tok.apply_chat_template(
msgs + [{"role": "assistant", "content": row["output"]}],
add_generation_prompt=False, tokenize=True))
input_ids = full_ids[:MAXLEN]
labels = list(input_ids)
for i in range(min(len(prompt_ids), len(labels))):
labels[i] = -100
return {"input_ids": input_ids, "labels": labels, "attention_mask": [1] * len(input_ids)}
ds = load_dataset("json", data_files=DATA, split="train")
if SMOKE:
ds = ds.select(range(min(64, len(ds))))
ds = ds.map(to_example, remove_columns=ds.column_names, desc="tokenizing")
def collate(batch):
m = max(len(b["input_ids"]) for b in batch)
pad = lambda s, v: s + [v] * (m - len(s))
return {
"input_ids": torch.tensor([pad(b["input_ids"], tok.pad_token_id) for b in batch]),
"labels": torch.tensor([pad(b["labels"], -100) for b in batch]),
"attention_mask": torch.tensor([pad(b["attention_mask"], 0) for b in batch]),
}
load_kwargs = dict(torch_dtype=torch.bfloat16)
if os.environ.get("LOAD_4BIT"):
from transformers import BitsAndBytesConfig
load_kwargs["quantization_config"] = BitsAndBytesConfig(
load_in_4bit=True, bnb_4bit_compute_dtype=torch.bfloat16, bnb_4bit_quant_type="nf4")
model = AutoModelForCausalLM.from_pretrained(MODEL_DIR, **load_kwargs)
model.config.use_cache = False
model.gradient_checkpointing_enable()
model.enable_input_require_grads() # required for PEFT + gradient checkpointing
lora = LoraConfig(
r=16, lora_alpha=int(os.environ.get("ALPHA", "16")), lora_dropout=0.0, bias="none", task_type="CAUSAL_LM",
target_modules=["q_proj", "k_proj", "v_proj", "o_proj"], # attention-only
)
model = get_peft_model(model, lora)
model.print_trainable_parameters()
args = TrainingArguments(
output_dir=OUT,
num_train_epochs=1,
max_steps=(20 if SMOKE else -1),
per_device_train_batch_size=1,
gradient_accumulation_steps=16,
learning_rate=1.5e-5,
lr_scheduler_type="cosine",
warmup_ratio=0.03,
bf16=True,
logging_steps=5,
save_strategy="steps",
save_steps=200,
save_total_limit=4,
eval_strategy="no",
report_to="none",
gradient_checkpointing=True,
deepspeed=DS_CONFIG,
)
trainer = Trainer(model=model, args=args, train_dataset=ds, data_collator=collate)
trainer.train(resume_from_checkpoint=RESUME)
trainer.save_model(OUT) # saves the LoRA adapter (not the full model)
tok.save_pretrained(OUT)
print(f"DONE -> LoRA adapter saved at {OUT}")