Download train.py from Mashbox41/ChriLLM: direct link, hf CLI and curl.
- Browser
- Download file 4.24 kB
-
https://huggingface.co/spaces/Mashbox41/ChriLLM/resolve/main/train.py
- Command line
-
hf download hf://spaces/Mashbox41/ChriLLM/train.py
-
curl -L -o train.py https://huggingface.co/spaces/Mashbox41/ChriLLM/resolve/main/train.py
4.24 kB
| # train.py — LoRA fine-tune using plain Transformers Trainer (no TRL) | |
| import os | |
| import torch | |
| from datasets import load_dataset | |
| from transformers import ( | |
| AutoModelForCausalLM, | |
| AutoTokenizer, | |
| Trainer, | |
| TrainingArguments, | |
| DataCollatorForLanguageModeling, | |
| ) | |
| from peft import LoraConfig, get_peft_model | |
| from huggingface_hub import HfApi | |
| # --- config you can tweak via Space variables --- | |
| BASE_MODEL = os.getenv("BASE_MODEL", "TinyLlama/TinyLlama-1.1B-Chat-v1.0") | |
| # HF dataset repo + jsonl file | |
| DATASET_ID = os.getenv("DATASET_ID", "Mashbox41/ChriLLM") | |
| JSONL_FILE = os.getenv("JSONL_FILE", "christian_dialogues.jsonl") | |
| OUTPUT_REPO = os.getenv("OUTPUT_REPO", "Mashbox41/ChriLLM-lora") | |
| MAX_LEN = int(os.getenv("MAX_LEN", "256")) | |
| EPOCHS = float(os.getenv("EPOCHS", "1.0")) | |
| LR = float(os.getenv("LR", "2e-4")) | |
| RANK = int(os.getenv("LORA_R", "8")) | |
| DROPOUT = float(os.getenv("LORA_DROPOUT", "0.05")) | |
| ALPHA = int(os.getenv("LORA_ALPHA", "16")) | |
| BATCH_SIZE = int(os.getenv("BATCH_SIZE", "1")) | |
| SAVE_DIR = "/data/ckpts" | |
| LORA_DIR = "/data/lora" | |
| HF_TOKEN = os.getenv("HF_TOKEN") | |
| SEED = int(os.getenv("SEED", "42")) | |
| os.makedirs(SAVE_DIR, exist_ok=True) | |
| os.makedirs(LORA_DIR, exist_ok=True) | |
| def log(msg: str): | |
| print(msg, flush=True) | |
| # --- model/tokenizer on CPU or GPU --- | |
| log(f"[info] Loading base model: {BASE_MODEL}") | |
| tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL, use_fast=True) | |
| if tokenizer.pad_token_id is None: | |
| tokenizer.pad_token = tokenizer.eos_token | |
| device = "cuda" if torch.cuda.is_available() else "cpu" | |
| model = AutoModelForCausalLM.from_pretrained(BASE_MODEL) | |
| model = model.to(device) | |
| peft_cfg = LoraConfig( | |
| r=RANK, | |
| lora_alpha=ALPHA, | |
| lora_dropout=DROPOUT, | |
| target_modules=[ | |
| "q_proj", "k_proj", "v_proj", "o_proj", | |
| "gate_proj", "up_proj", "down_proj" | |
| ], | |
| task_type="CAUSAL_LM", | |
| ) | |
| model = get_peft_model(model, peft_cfg) | |
| # --- dataset: load from HF hub jsonl --- | |
| hf_path = f"hf://datasets/{DATASET_ID}/{JSONL_FILE}" | |
| log(f"[info] Loading dataset from {hf_path}") | |
| raw_ds = load_dataset("json", data_files={"train": hf_path})["train"] | |
| def to_text(ex): | |
| # Accept {"messages":[...]} or {"text":"..."} | |
| if "messages" in ex and ex["messages"]: | |
| lines = [f"{m.get('role','user')}: {m.get('content','')}" for m in ex["messages"]] | |
| return {"text": "\n".join(lines) + "\nassistant:"} | |
| return {"text": ex.get("text", "")} | |
| cols = [c for c in raw_ds.column_names if c not in ("messages", "text")] | |
| ds_text = raw_ds.map(to_text, remove_columns=cols) | |
| def tokenize_batch(batch): | |
| return tokenizer( | |
| batch["text"], | |
| truncation=True, | |
| max_length=MAX_LEN, | |
| padding="max_length", | |
| ) | |
| tokenized = ds_text.map( | |
| tokenize_batch, | |
| batched=True, | |
| remove_columns=["text"], | |
| ) | |
| # For causal LM, labels = input_ids | |
| tokenized = tokenized.map( | |
| lambda b: {"labels": b["input_ids"]}, | |
| batched=True, | |
| ) | |
| data_collator = DataCollatorForLanguageModeling( | |
| tokenizer=tokenizer, | |
| mlm=False, | |
| ) | |
| # --- training --- | |
| torch.manual_seed(SEED) | |
| training_args = TrainingArguments( | |
| output_dir=SAVE_DIR, | |
| per_device_train_batch_size=BATCH_SIZE, | |
| num_train_epochs=EPOCHS, | |
| learning_rate=LR, | |
| logging_steps=10, | |
| save_strategy="no", # we'll save LoRA manually | |
| seed=SEED, | |
| fp16=False, | |
| ) | |
| trainer = Trainer( | |
| model=model, | |
| args=training_args, | |
| train_dataset=tokenized, | |
| data_collator=data_collator, | |
| ) | |
| log("[info] Starting training…") | |
| trainer.train() | |
| log("[info] Saving LoRA adapters…") | |
| model.save_pretrained(LORA_DIR) | |
| # --- push to hub --- | |
| if HF_TOKEN: | |
| api = HfApi() | |
| log(f"[info] Creating/using repo {OUTPUT_REPO}") | |
| api.create_repo( | |
| repo_id=OUTPUT_REPO, | |
| repo_type="model", | |
| private=False, | |
| exist_ok=True, | |
| token=HF_TOKEN, | |
| ) | |
| log(f"[info] Uploading adapters from {LORA_DIR} → {OUTPUT_REPO}") | |
| api.upload_folder( | |
| repo_id=OUTPUT_REPO, | |
| repo_type="model", | |
| folder_path=LORA_DIR, | |
| token=HF_TOKEN, | |
| ) | |
| log(f"✅ uploaded adapters to {OUTPUT_REPO}") | |
| else: | |
| log("[warn] HF_TOKEN not set; skipping upload.") | |
| log("✅ Done.") | |