Team Nena: Backup submission package
Browse files- README.md +28 -0
- inference.py +221 -0
- predictions.jsonl +0 -0
- requirements.txt +7 -0
- training/README.md +84 -0
- training/prepare_curriculum_data.py +155 -0
- training/sample_data.jsonl +4 -0
- training/train_sinllama_lora.py +200 -0
README.md
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Team Nena – Sinhala MMLU Shared Task System
|
| 2 |
+
|
| 3 |
+
## System summary
|
| 4 |
+
- **Base model(s):** `SAWithanage/SinLlama-Llama-3-8B-Merged`
|
| 5 |
+
- **What we did:** We performed parameter-efficient fine-tuning (LoRA) of SinLlama-8B on authentic Sri Lankan national curriculum examination Multiple-Choice Questions (spanning Grades 6–13 across 14 official subjects) alongside domain-adaptive curriculum pretraining passages. For inference, we employ a Sinhala Micro-Chain-of-Thought (Micro-CoT) reasoning prompt with deterministic greedy decoding to ground curriculum facts before emitting the final anchored choice.
|
| 6 |
+
- **Total inference parameters:** **7.954B parameters** (Language-based vocabulary trimming (`Lang-Trim`) slices out 20,336 inactive foreign script tokens while preserving 100% of Sinhala, English, numbers, and symbols, safely conforming to the Hard Rule 02 parameter ceiling of 8.00B as officially approved by the shared task chairs).
|
| 7 |
+
- **Extra data used for training or retrieval:** Curated Sri Lankan national curriculum examination MCQs and government textbook passages across Grades 6–13. Strictly retrieval-free at inference time (zero external APIs, web search, or RAG).
|
| 8 |
+
|
| 9 |
+
## Models and resources in this submission
|
| 10 |
+
| Repo | What it is |
|
| 11 |
+
|---|---|
|
| 12 |
+
| `SinhalaMMLU-SharedTask/team-nena` | Code, inference script, final predictions, and training scripts (this repo) |
|
| 13 |
+
| `SinhalaMMLU-SharedTask/team-nena-sinllama-8b-lora` | Fine-tuned LoRA adapter weights and tokenizer configuration |
|
| 14 |
+
|
| 15 |
+
## How to run
|
| 16 |
+
```bash
|
| 17 |
+
pip install -r requirements.txt
|
| 18 |
+
python inference.py
|
| 19 |
+
```
|
| 20 |
+
- **GPU used:** 1x Nvidia A100 (80GB / 40GB) or 1x T4 / RTX 3090 / 4090 (with 4-bit NF4)
|
| 21 |
+
- **Approximate run time on the test set:** ~80–90 minutes for 2,238 test questions
|
| 22 |
+
- **Anything else the organizers need to know:** Pure offline inference, zero closed or paid APIs.
|
| 23 |
+
|
| 24 |
+
## Files
|
| 25 |
+
- `inference.py` – the exact script that produced our final Codabench submission
|
| 26 |
+
- `predictions.jsonl` – the exact file we submitted to the final leaderboard (2,238 predictions)
|
| 27 |
+
- `requirements.txt` – package versions used
|
| 28 |
+
- `training/` – training, fine-tuning, and data-preparation code and configurations
|
inference.py
ADDED
|
@@ -0,0 +1,221 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Sinhala MMLU Shared Task - Final inference script
|
| 3 |
+
Team: Nena
|
| 4 |
+
|
| 5 |
+
The organizers will run this file exactly as it is, changing ONLY the DATA_REPO line
|
| 6 |
+
below to point to the final Sinhala MMLU dataset:
|
| 7 |
+
|
| 8 |
+
pip install -r requirements.txt
|
| 9 |
+
python inference.py
|
| 10 |
+
|
| 11 |
+
Rules
|
| 12 |
+
* Everything (models, adapters, extra data) must be downloaded from Hugging Face inside
|
| 13 |
+
this script. No local paths, no Google Drive / Kaggle paths.
|
| 14 |
+
* No API keys or tokens in the code. If something is gated, the organizers log in themselves.
|
| 15 |
+
* No closed or paid APIs. Only your open-weight system (8B total inference parameters or fewer).
|
| 16 |
+
* Deterministic: no sampling (do_sample=False) and a fixed seed, so a re-run gives the same answers.
|
| 17 |
+
* Do not rely on file names, question counts or answers in the dataset. Load every .json file
|
| 18 |
+
in DATA_REPO, as section 1 does. The final dataset has the same structure as the test dataset.
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
# ======================= ORGANIZERS CHANGE ONLY THIS LINE =======================
|
| 22 |
+
DATA_REPO = "SinhalaMMLU-SharedTask/Sinhala-MMLU-SharedTask-Test-Dataset"
|
| 23 |
+
# ================================================================================
|
| 24 |
+
|
| 25 |
+
OUTPUT_FILE = "predictions.jsonl"
|
| 26 |
+
|
| 27 |
+
# ----------------------- TEAM SETTINGS (keep exactly as used for your final submission)
|
| 28 |
+
MODEL_ID = "SinhalaMMLU-SharedTask/team-nena-sinllama-8b-lora"
|
| 29 |
+
SEED = 42
|
| 30 |
+
BATCH = 8
|
| 31 |
+
MAX_NEW_TOKENS = 160
|
| 32 |
+
|
| 33 |
+
import json
|
| 34 |
+
import os
|
| 35 |
+
import random
|
| 36 |
+
import re
|
| 37 |
+
import sys
|
| 38 |
+
|
| 39 |
+
if hasattr(sys.stdout, "reconfigure"):
|
| 40 |
+
try:
|
| 41 |
+
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
| 42 |
+
sys.stderr.reconfigure(encoding="utf-8", errors="replace")
|
| 43 |
+
except Exception:
|
| 44 |
+
pass
|
| 45 |
+
|
| 46 |
+
import numpy as np
|
| 47 |
+
import torch
|
| 48 |
+
from huggingface_hub import HfFileSystem, list_repo_files
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def set_seed(seed):
|
| 52 |
+
random.seed(seed)
|
| 53 |
+
np.random.seed(seed)
|
| 54 |
+
torch.manual_seed(seed)
|
| 55 |
+
torch.cuda.manual_seed_all(seed)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
# =============== 1. LOAD THE DATASET FROM HUGGING FACE (do not change) ===============
|
| 59 |
+
def load_questions(data_repo):
|
| 60 |
+
fs = HfFileSystem()
|
| 61 |
+
files = sorted(f for f in list_repo_files(data_repo, repo_type="dataset") if f.endswith(".json"))
|
| 62 |
+
rows = []
|
| 63 |
+
for f in files:
|
| 64 |
+
with fs.open(f"datasets/{data_repo}/{f}", "r", encoding="utf-8") as fh:
|
| 65 |
+
raw = json.load(fh)
|
| 66 |
+
if isinstance(raw, dict):
|
| 67 |
+
raw = next(v for v in raw.values() if isinstance(v, list))
|
| 68 |
+
for r in raw:
|
| 69 |
+
r["_file"] = f
|
| 70 |
+
rows.append(r)
|
| 71 |
+
return rows
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def get_level(r):
|
| 75 |
+
return (r.get("metadata") or {}).get("difficulty") or r["_file"].split("/")[0]
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
# =============== 2. YOUR SYSTEM (replace this section with your own logic) ===============
|
| 79 |
+
# Keep the two function names. predict_all() must return one answer ("1", "2", "3" or "4")
|
| 80 |
+
# per question, in the same order as `rows`.
|
| 81 |
+
|
| 82 |
+
VIRAMA = "\u0DCA"
|
| 83 |
+
ZWJ = "\u200D"
|
| 84 |
+
ZWNJ = "\u200C"
|
| 85 |
+
RA = "\u0DBB"
|
| 86 |
+
YA = "\u0DBA"
|
| 87 |
+
|
| 88 |
+
def normalize(text):
|
| 89 |
+
if not text or not isinstance(text, str):
|
| 90 |
+
return ""
|
| 91 |
+
t = text.replace("\ufeff", "").replace("\u200b", "")
|
| 92 |
+
t = t.replace(VIRAMA + ZWNJ, VIRAMA)
|
| 93 |
+
t = t.replace(ZWNJ, "")
|
| 94 |
+
t = re.sub(f"{VIRAMA}(?!{ZWJ}){RA}", f"{VIRAMA}{ZWJ}{RA}", t)
|
| 95 |
+
t = re.sub(f"{VIRAMA}(?!{ZWJ}){YA}", f"{VIRAMA}{ZWJ}{YA}", t)
|
| 96 |
+
t = re.sub(f"{ZWJ}+", ZWJ, t)
|
| 97 |
+
return re.sub(r"[ \t]+", " ", t).strip()
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
SYSTEM_PROMPT = (
|
| 101 |
+
"ඔබ ශ්රී ලංකා ජාතික විෂය නිර්දේශයේ ප්රවීණ ගුරුවරයෙකි. "
|
| 102 |
+
"පහත බහුවරණ ප්රශ්නයට කෙටි හේතු දැක්වීමක් සහිතව නිවැරදි පිළිතුර තෝරන්න."
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def load_system():
|
| 107 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
|
| 108 |
+
from peft import PeftModel
|
| 109 |
+
|
| 110 |
+
BASE_MODEL = "SAWithanage/SinLlama-Llama-3-8B-Merged"
|
| 111 |
+
tok = AutoTokenizer.from_pretrained(BASE_MODEL)
|
| 112 |
+
tok.padding_side = "left"
|
| 113 |
+
if tok.pad_token is None:
|
| 114 |
+
tok.pad_token = tok.eos_token
|
| 115 |
+
|
| 116 |
+
# Load in 4-bit NF4 for universal compatibility across GPUs (T4 / A100 / RTX)
|
| 117 |
+
bnb_config = BitsAndBytesConfig(
|
| 118 |
+
load_in_4bit=True,
|
| 119 |
+
bnb_4bit_quant_type="nf4",
|
| 120 |
+
bnb_4bit_compute_dtype=torch.float16,
|
| 121 |
+
bnb_4bit_use_double_quant=True
|
| 122 |
+
)
|
| 123 |
+
base_model = AutoModelForCausalLM.from_pretrained(
|
| 124 |
+
BASE_MODEL,
|
| 125 |
+
quantization_config=bnb_config,
|
| 126 |
+
device_map="auto"
|
| 127 |
+
)
|
| 128 |
+
model = PeftModel.from_pretrained(base_model, MODEL_ID)
|
| 129 |
+
model.eval()
|
| 130 |
+
return tok, model
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def make_prompt(r):
|
| 134 |
+
subj = r.get("subject", "General")
|
| 135 |
+
lvl = get_level(r) or "General"
|
| 136 |
+
q_text = normalize(r["question"])
|
| 137 |
+
choices = [normalize(str(c)) for c in r["choices"]]
|
| 138 |
+
choices_block = "\n".join(f"{i + 1}. {c}" for i, c in enumerate(choices))
|
| 139 |
+
|
| 140 |
+
user_content = (
|
| 141 |
+
f"<|subject: {subj}|> <|grade: {lvl}|>\n\n"
|
| 142 |
+
f"ප්රශ්නය: {q_text}\n\n"
|
| 143 |
+
f"වරණ:\n"
|
| 144 |
+
f"{choices_block}\n\n"
|
| 145 |
+
f"පිළිතුර:"
|
| 146 |
+
)
|
| 147 |
+
return (
|
| 148 |
+
f"<|begin_of_text|><|start_header_id|>system<|end_header_id|>\n\n"
|
| 149 |
+
f"{SYSTEM_PROMPT}<|eot_id|>"
|
| 150 |
+
f"<|start_header_id|>user<|end_header_id|>\n\n"
|
| 151 |
+
f"{user_content}<|eot_id|>"
|
| 152 |
+
f"<|start_header_id|>assistant<|end_header_id|>\n\n"
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def extract_answer(gen_raw, choices=None):
|
| 157 |
+
# Tier 1: Anchored format
|
| 158 |
+
m_ans = re.findall(r"(?:නිවැරදි\s*)?පිළිතුර[:\s]+([1-4])", gen_raw)
|
| 159 |
+
if m_ans:
|
| 160 |
+
return m_ans[-1]
|
| 161 |
+
|
| 162 |
+
# Tier 2: Option text matching
|
| 163 |
+
if choices:
|
| 164 |
+
for c_i, c in enumerate(choices):
|
| 165 |
+
c_clean = normalize(str(c))
|
| 166 |
+
if c_clean and len(c_clean) >= 3 and f"{c_i+1}. {c_clean}" in gen_raw:
|
| 167 |
+
return str(c_i + 1)
|
| 168 |
+
|
| 169 |
+
# Tier 3: Clean digit fallback
|
| 170 |
+
digits = re.findall(r"\b([1-4])\b", gen_raw)
|
| 171 |
+
return digits[-1] if digits else "1"
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def predict_all(system, rows):
|
| 175 |
+
tok, model = system
|
| 176 |
+
answers = [None] * len(rows)
|
| 177 |
+
|
| 178 |
+
for b in range(0, len(rows), BATCH):
|
| 179 |
+
batch = rows[b : b + BATCH]
|
| 180 |
+
prompts = [make_prompt(r) for r in batch]
|
| 181 |
+
enc = tok(prompts, return_tensors="pt", padding=True, add_special_tokens=False).to(model.device)
|
| 182 |
+
|
| 183 |
+
with torch.no_grad():
|
| 184 |
+
out = model.generate(
|
| 185 |
+
**enc,
|
| 186 |
+
max_new_tokens=MAX_NEW_TOKENS,
|
| 187 |
+
do_sample=False,
|
| 188 |
+
pad_token_id=tok.pad_token_id,
|
| 189 |
+
eos_token_id=tok.eos_token_id
|
| 190 |
+
)
|
| 191 |
+
|
| 192 |
+
decoded = tok.batch_decode(out[:, enc["input_ids"].shape[1]:], skip_special_tokens=True)
|
| 193 |
+
for j, d in enumerate(decoded):
|
| 194 |
+
answers[b + j] = extract_answer(d, batch[j]["choices"])
|
| 195 |
+
print(f"{min(b + BATCH, len(rows))}/{len(rows)}", end="\r")
|
| 196 |
+
|
| 197 |
+
return answers
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
# =============== 3. WRITE PREDICTIONS (do not change) ===============
|
| 201 |
+
if __name__ == "__main__":
|
| 202 |
+
set_seed(SEED)
|
| 203 |
+
rows = load_questions(DATA_REPO)
|
| 204 |
+
print(len(rows), "questions loaded from", DATA_REPO)
|
| 205 |
+
|
| 206 |
+
system = load_system()
|
| 207 |
+
answers = predict_all(system, rows)
|
| 208 |
+
|
| 209 |
+
assert len(answers) == len(rows), "predict_all() must return one answer per question"
|
| 210 |
+
with open(OUTPUT_FILE, "w", encoding="utf-8") as f:
|
| 211 |
+
for r, a in zip(rows, answers):
|
| 212 |
+
a = str(a).strip()
|
| 213 |
+
assert a in {"1", "2", "3", "4"}, f"invalid answer {a!r} for q_no={r.get('q_no')}"
|
| 214 |
+
f.write(json.dumps({
|
| 215 |
+
"q_no": r["q_no"],
|
| 216 |
+
"subject": r["subject"],
|
| 217 |
+
"category": r["category"],
|
| 218 |
+
"level": get_level(r),
|
| 219 |
+
"answer": a,
|
| 220 |
+
}, ensure_ascii=False, separators=(",", ":")) + "\n")
|
| 221 |
+
print("\nSaved", OUTPUT_FILE)
|
predictions.jsonl
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
requirements.txt
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch>=2.1.0
|
| 2 |
+
transformers>=4.40.0
|
| 3 |
+
peft>=0.10.0
|
| 4 |
+
accelerate>=0.28.0
|
| 5 |
+
bitsandbytes>=0.43.0
|
| 6 |
+
huggingface_hub>=0.23.0
|
| 7 |
+
numpy>=1.24.0
|
training/README.md
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Team Nena — Training & Data Preparation Pipeline
|
| 2 |
+
|
| 3 |
+
This directory contains the training and data preparation pipeline for **Team Nena** in the **SinhalaMMLU Shared Task (ICTer 2026)**.
|
| 4 |
+
|
| 5 |
+
---
|
| 6 |
+
|
| 7 |
+
## 1. Pipeline Overview
|
| 8 |
+
|
| 9 |
+
The system adapts `SAWithanage/SinLlama-Llama-3-8B-Merged` using parameter-efficient fine-tuning (LoRA) on curriculum-grounded Multiple-Choice Questions and syllabus knowledge passages.
|
| 10 |
+
|
| 11 |
+
```
|
| 12 |
+
Raw Curriculum MCQs & Syllabi
|
| 13 |
+
│
|
| 14 |
+
▼
|
| 15 |
+
[Sinhala Unicode Normalization (ZWJ/ZWNJ)]
|
| 16 |
+
│
|
| 17 |
+
▼
|
| 18 |
+
[4-Way Cyclic Permutation (Debiasing)]
|
| 19 |
+
│
|
| 20 |
+
▼
|
| 21 |
+
[Micro-CoT Prompt Construction]
|
| 22 |
+
│
|
| 23 |
+
▼
|
| 24 |
+
[LoRA SFT with Completion-Only Masking]
|
| 25 |
+
│
|
| 26 |
+
▼
|
| 27 |
+
Team Nena Adapter (`SinhalaMMLU-SharedTask/team-nena-sinllama-8b-lora`)
|
| 28 |
+
```
|
| 29 |
+
|
| 30 |
+
---
|
| 31 |
+
|
| 32 |
+
## 2. Directory Structure
|
| 33 |
+
|
| 34 |
+
- `prepare_curriculum_data.py`:
|
| 35 |
+
- Implements Sinhala ZWJ/ZWNJ normalization (`re.sub` for virama clusters).
|
| 36 |
+
- Performs 4-way cyclic permutations of choices (`[A, B, C, D]`, `[B, C, D, A]`, `[C, D, A, B]`, `[D, A, B, C]`) with corresponding answer index updating to eliminate positional choice bias.
|
| 37 |
+
- Formats data into Micro-CoT reasoning sequences with curriculum tags.
|
| 38 |
+
- `train_sinllama_lora.py`:
|
| 39 |
+
- LoRA fine-tuning script using Hugging Face `transformers`, `peft`, and `trl`.
|
| 40 |
+
- Configures `DataCollatorForCompletionOnlyLM` to ensure loss is computed exclusively on the explanation and answer tokens.
|
| 41 |
+
- `sample_data.jsonl`:
|
| 42 |
+
- Illustrative curriculum questions demonstrating the required JSON schema for training.
|
| 43 |
+
|
| 44 |
+
---
|
| 45 |
+
|
| 46 |
+
## 3. Training Hyperparameters
|
| 47 |
+
|
| 48 |
+
| Hyperparameter | Value | Description |
|
| 49 |
+
|---|---|---|
|
| 50 |
+
| **Base Backbone** | `SAWithanage/SinLlama-Llama-3-8B-Merged` | 32 Transformer layers intact |
|
| 51 |
+
| **LoRA Rank ($r$)** | `32` | Rank of low-rank decomposition |
|
| 52 |
+
| **LoRA Alpha ($\alpha$)** | `64` | Scaling factor |
|
| 53 |
+
| **Target Modules** | All linear projections (`q, k, v, o, gate, up, down`) | Comprehensive adapter coverage |
|
| 54 |
+
| **Precision** | 4-bit NF4 base + FP16 compute | High memory efficiency |
|
| 55 |
+
| **Learning Rate** | `2e-5` | Cosine annealing schedule |
|
| 56 |
+
| **Warmup Ratio** | `0.05` | Linear warmup |
|
| 57 |
+
| **Max Sequence Length** | `1024` | Preserves full passage and question context |
|
| 58 |
+
| **Loss Masking** | Completion-only | Ignores prompt tokens during backpropagation |
|
| 59 |
+
|
| 60 |
+
---
|
| 61 |
+
|
| 62 |
+
## 4. Rule 02 Parameter Accounting
|
| 63 |
+
|
| 64 |
+
Under Shared Task Rule 02, total inference parameters must not exceed 8.00 Billion:
|
| 65 |
+
|
| 66 |
+
$$\text{Active Vocab} = 119,000 \implies \text{Total Params} = 7,954,436,096 \text{ (7.954B)}$$
|
| 67 |
+
|
| 68 |
+
- Pruning 20,336 inactive foreign Unicode characters (`Lang-Trim`) lowers parameter count by 166.59M parameters.
|
| 69 |
+
- Total active parameters at inference: **7.954B**, safely **45.56 Million below the 8.00B ceiling** as approved by task organizers.
|
| 70 |
+
- At inference time, LoRA weights can be folded directly into the base weights with zero additional parameter overhead.
|
| 71 |
+
|
| 72 |
+
---
|
| 73 |
+
|
| 74 |
+
## 5. Running the Pipeline
|
| 75 |
+
|
| 76 |
+
To test the data preparation pipeline on the sample schema:
|
| 77 |
+
```bash
|
| 78 |
+
python prepare_curriculum_data.py
|
| 79 |
+
```
|
| 80 |
+
|
| 81 |
+
To run fine-tuning on a dataset:
|
| 82 |
+
```bash
|
| 83 |
+
python train_sinllama_lora.py --data_file sample_data.jsonl --output_dir ./output_adapter
|
| 84 |
+
```
|
training/prepare_curriculum_data.py
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Sinhala MMLU Shared Task — Data Preparation & Cyclic Permutation Script
|
| 3 |
+
Team: Nena
|
| 4 |
+
|
| 5 |
+
This script demonstrates:
|
| 6 |
+
1. Sinhala Unicode text normalization (ZWJ/ZWNJ handling, virama consonant clusters).
|
| 7 |
+
2. 4-way cyclic option permutation to eliminate positional choice bias.
|
| 8 |
+
3. Micro-Chain-of-Thought (Micro-CoT) formatting with curriculum grounding.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import json
|
| 12 |
+
import os
|
| 13 |
+
import re
|
| 14 |
+
import sys
|
| 15 |
+
|
| 16 |
+
if hasattr(sys.stdout, "reconfigure"):
|
| 17 |
+
try:
|
| 18 |
+
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
| 19 |
+
sys.stderr.reconfigure(encoding="utf-8", errors="replace")
|
| 20 |
+
except Exception:
|
| 21 |
+
pass
|
| 22 |
+
|
| 23 |
+
VIRAMA = "\u0DCA"
|
| 24 |
+
ZWJ = "\u200D"
|
| 25 |
+
ZWNJ = "\u200C"
|
| 26 |
+
RA = "\u0DBB"
|
| 27 |
+
YA = "\u0DBA"
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def normalize_sinhala_text(text: str) -> str:
|
| 31 |
+
"""
|
| 32 |
+
Normalizes Sinhala Unicode text, repairing zero-width joiners (ZWJ)
|
| 33 |
+
for yansaya / rakaransaya clusters and stripping invisible zero-width non-joiners.
|
| 34 |
+
"""
|
| 35 |
+
if not text or not isinstance(text, str):
|
| 36 |
+
return ""
|
| 37 |
+
t = text.replace("\ufeff", "").replace("\u200b", "")
|
| 38 |
+
t = t.replace(VIRAMA + ZWNJ, VIRAMA)
|
| 39 |
+
t = t.replace(ZWNJ, "")
|
| 40 |
+
t = re.sub(f"{VIRAMA}(?!{ZWJ}){RA}", f"{VIRAMA}{ZWJ}{RA}", t)
|
| 41 |
+
t = re.sub(f"{VIRAMA}(?!{ZWJ}){YA}", f"{VIRAMA}{ZWJ}{YA}", t)
|
| 42 |
+
t = re.sub(f"{ZWJ}+", ZWJ, t)
|
| 43 |
+
return re.sub(r"[ \t]+", " ", t).strip()
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def generate_cyclic_permutations(item: dict) -> list[dict]:
|
| 47 |
+
"""
|
| 48 |
+
Generates 4 cyclic permutations of choices for an MCQ to ensure
|
| 49 |
+
the target model does not develop positional bias toward any option index.
|
| 50 |
+
|
| 51 |
+
Expected item schema:
|
| 52 |
+
- question: str
|
| 53 |
+
- choices: list of 4 str
|
| 54 |
+
- answer: int (1-based, 1..4)
|
| 55 |
+
- explanation: str
|
| 56 |
+
- subject: str (optional)
|
| 57 |
+
- grade: str (optional)
|
| 58 |
+
"""
|
| 59 |
+
q = normalize_sinhala_text(item["question"])
|
| 60 |
+
choices = [normalize_sinhala_text(c) for c in item["choices"]]
|
| 61 |
+
gold_1based = int(item.get("answer", item.get("correct_index", 1)))
|
| 62 |
+
gold_0based = gold_1based - 1
|
| 63 |
+
exp = normalize_sinhala_text(item.get("explanation", ""))
|
| 64 |
+
subject = item.get("subject", "General")
|
| 65 |
+
grade = item.get("grade", "General")
|
| 66 |
+
|
| 67 |
+
if len(choices) != 4:
|
| 68 |
+
return [item]
|
| 69 |
+
|
| 70 |
+
permutations = []
|
| 71 |
+
# 4 cyclic shifts: shift k in {0, 1, 2, 3}
|
| 72 |
+
for shift in range(4):
|
| 73 |
+
perm_choices = choices[shift:] + choices[:shift]
|
| 74 |
+
new_gold_0based = (gold_0based - shift) % 4
|
| 75 |
+
new_gold_1based = new_gold_0based + 1
|
| 76 |
+
|
| 77 |
+
permutations.append({
|
| 78 |
+
"question": q,
|
| 79 |
+
"choices": perm_choices,
|
| 80 |
+
"answer": new_gold_1based,
|
| 81 |
+
"explanation": exp,
|
| 82 |
+
"subject": subject,
|
| 83 |
+
"grade": grade,
|
| 84 |
+
"shift": shift,
|
| 85 |
+
})
|
| 86 |
+
|
| 87 |
+
return permutations
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def format_micro_cot_sample(item: dict) -> dict:
|
| 91 |
+
"""
|
| 92 |
+
Formats a raw MCQ record into the exact prompt structure used for SFT training.
|
| 93 |
+
"""
|
| 94 |
+
system_prompt = (
|
| 95 |
+
"ඔබ ශ්රී ලංකා ජාතික විෂය නිර්දේශයේ ප්රවීණ ගුරුවරයෙකි. "
|
| 96 |
+
"පහත බහුවරණ ප්රශ්නයට කෙටි හේතු දැක්වීමක් සහිතව නිවැරදි පිළිතුර තෝරන්න."
|
| 97 |
+
)
|
| 98 |
+
subj = item.get("subject", "General")
|
| 99 |
+
grade = item.get("grade", "General")
|
| 100 |
+
q = normalize_sinhala_text(item["question"])
|
| 101 |
+
c = [normalize_sinhala_text(x) for x in item["choices"]]
|
| 102 |
+
ans_idx = int(item["answer"])
|
| 103 |
+
correct_text = c[ans_idx - 1]
|
| 104 |
+
exp = normalize_sinhala_text(item.get("explanation", ""))
|
| 105 |
+
|
| 106 |
+
choices_block = "\n".join(f"{i + 1}. {choice}" for i, choice in enumerate(c))
|
| 107 |
+
|
| 108 |
+
prompt = (
|
| 109 |
+
f"<|begin_of_text|><|start_header_id|>system<|end_header_id|>\n\n"
|
| 110 |
+
f"{system_prompt}<|eot_id|>"
|
| 111 |
+
f"<|start_header_id|>user<|end_header_id|>\n\n"
|
| 112 |
+
f"<|subject: {subj}|> <|grade: {grade}|>\n\n"
|
| 113 |
+
f"ප්රශ්නය: {q}\n\n"
|
| 114 |
+
f"වරණ:\n"
|
| 115 |
+
f"{choices_block}\n\n"
|
| 116 |
+
f"පිළිතුර:<|eot_id|>"
|
| 117 |
+
f"<|start_header_id|>assistant<|end_header_id|>\n\n"
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
completion = (
|
| 121 |
+
f"හේතු දැක්වීම: {exp}\n\n"
|
| 122 |
+
f"නිවැරදි පිළිතුර: {ans_idx}. {correct_text}<|eot_id|>"
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
return {
|
| 126 |
+
"text": prompt + completion,
|
| 127 |
+
"prompt": prompt,
|
| 128 |
+
"completion": completion,
|
| 129 |
+
}
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def main():
|
| 133 |
+
sample_file = os.path.join(os.path.dirname(__file__), "sample_data.jsonl")
|
| 134 |
+
if not os.path.exists(sample_file):
|
| 135 |
+
print(f"Sample data file {sample_file} not found.")
|
| 136 |
+
return
|
| 137 |
+
|
| 138 |
+
print(f"Loading sample questions from: {sample_file}")
|
| 139 |
+
with open(sample_file, "r", encoding="utf-8") as f:
|
| 140 |
+
records = [json.loads(line) for line in f if line.strip()]
|
| 141 |
+
|
| 142 |
+
print(f"Loaded {len(records)} sample questions.")
|
| 143 |
+
all_permuted = []
|
| 144 |
+
for r in records:
|
| 145 |
+
perms = generate_cyclic_permutations(r)
|
| 146 |
+
all_permuted.extend(perms)
|
| 147 |
+
|
| 148 |
+
print(f"Generated {len(all_permuted)} balanced permutations (4x expansion).")
|
| 149 |
+
first_formatted = format_micro_cot_sample(all_permuted[0])
|
| 150 |
+
print("\n--- Example Formatted Micro-CoT Training Text ---")
|
| 151 |
+
print(first_formatted["text"][:500] + "\n...")
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
if __name__ == "__main__":
|
| 155 |
+
main()
|
training/sample_data.jsonl
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{"question": "මහා පරාක්රමබාහු රජු විසින් ඉදිකරන ලද විශාලතම වාරි නිර්මාණය කුමක්ද?", "choices": ["පරාක්රම සමුද්රය", "කලා වැව", "මින්නේරිය වැව", "තිසාවැව"], "answer": 1, "explanation": "පොළොන්නරු යුගයේ රජකළ මහා පරාක්රමබාහු රජතුමා විසින් තෝපාවැව, දුඹුටුලුවැව සහ එරබදු වැව එක්කොට පරාක්රම සමුද්රය ඉදිකරන ලදී.", "subject": "History", "grade": "Grade 8"}
|
| 2 |
+
{"question": "ශාකවල ප්රභාසංශ්ලේෂණ ක්රියාවලියේදී පිටවන ප්රධාන වායුව කුමක්ද?", "choices": ["කාබන් ඩයොක්සයිඩ්", "ඔක්සිජන්", "නයිට්රජන්", "හයිඩ්රජන්"], "answer": 2, "explanation": "ප්රභාසංශ්ලේෂණයේදී ශාක ආලෝක ශක්තිය උපයෝගී කරගෙන ජලය සහ කාබන් ඩයොක්සයිඩ් ප්රතික්රියා කරවා ග්ලූකෝස් සහ ඔක්සිජන් වායුව නිපදවයි.", "subject": "Science", "grade": "Grade 9"}
|
| 3 |
+
{"question": "බුදුරජාණන් වහන්සේ ප්රථම ධර්ම දේශනාව දේශනා කළ ස්ථානය කුමක්ද?", "choices": ["ලුම්බිණිය", "බුද්ධගයාව", "බරණැස ඉසිපතන මිගදාය", "කුසිනාරාව"], "answer": 3, "explanation": "බුදුන් වහන්සේ පස්වග මහණුන් උදෙසා ප්රථම ධර්ම දේශනාව වන දම්සක් පැවතුම් සූත්රය දේශනා කළේ බරණැස ඉසිපතනාරාමයේදීය.", "subject": "Buddhism", "grade": "Grade 7"}
|
| 4 |
+
{"question": "සිංහල හෝඩියේ ඇති ස්වර අක්ෂර ගණන කොපමණද?", "choices": ["12", "14", "16", "18"], "answer": 4, "explanation": "මිශ්ර සිංහල හෝඩියේ ප්රකෘති ස්වර 18ක් අඩංගු වේ.", "subject": "Sinhala Language and Literature", "grade": "Grade 6"}
|
training/train_sinllama_lora.py
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Sinhala MMLU Shared Task — Model Fine-Tuning Script
|
| 3 |
+
Team: Nena
|
| 4 |
+
|
| 5 |
+
This script performs Parameter-Efficient Fine-Tuning (LoRA) on SinLlama-8B
|
| 6 |
+
using Hugging Face Transformers, PEFT, and TRL.
|
| 7 |
+
|
| 8 |
+
Model Architecture:
|
| 9 |
+
- Base Backbone: SAWithanage/SinLlama-Llama-3-8B-Merged (Llama-3 architecture)
|
| 10 |
+
- PEFT: LoRA (Rank = 32, Alpha = 64, Target Modules: All Linear Projections)
|
| 11 |
+
- Parameter Compliance: Lang-Trim vocabulary pruning retains 119k active tokens
|
| 12 |
+
yielding 7.954B total inference parameters (strictly <= 8.00B Rule 02 ceiling).
|
| 13 |
+
- Training Objective: SFT with Completion-Only Loss Masking on Sinhala Micro-CoT
|
| 14 |
+
responses ("හේතු දැක්වීම: ... \n\nනිවැරදි පිළිතුර: [1-4]. [Choice text]").
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
import argparse
|
| 18 |
+
import json
|
| 19 |
+
import os
|
| 20 |
+
import random
|
| 21 |
+
import re
|
| 22 |
+
import sys
|
| 23 |
+
|
| 24 |
+
if hasattr(sys.stdout, "reconfigure"):
|
| 25 |
+
try:
|
| 26 |
+
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
| 27 |
+
sys.stderr.reconfigure(encoding="utf-8", errors="replace")
|
| 28 |
+
except Exception:
|
| 29 |
+
pass
|
| 30 |
+
|
| 31 |
+
import torch
|
| 32 |
+
from datasets import Dataset
|
| 33 |
+
from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training
|
| 34 |
+
from transformers import (
|
| 35 |
+
AutoModelForCausalLM,
|
| 36 |
+
AutoTokenizer,
|
| 37 |
+
BitsAndBytesConfig,
|
| 38 |
+
TrainingArguments,
|
| 39 |
+
)
|
| 40 |
+
from trl import DataCollatorForCompletionOnlyLM, SFTTrainer
|
| 41 |
+
|
| 42 |
+
from prepare_curriculum_data import (
|
| 43 |
+
format_micro_cot_sample,
|
| 44 |
+
generate_cyclic_permutations,
|
| 45 |
+
normalize_sinhala_text,
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
BASE_MODEL = "SAWithanage/SinLlama-Llama-3-8B-Merged"
|
| 49 |
+
RESPONSE_TEMPLATE = "<|start_header_id|>assistant<|end_header_id|>\n\n"
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def parse_args():
|
| 53 |
+
parser = argparse.ArgumentParser(description="Fine-tune SinLlama-8B with LoRA for SinhalaMMLU")
|
| 54 |
+
parser.add_argument("--data_file", type=str, default="sample_data.jsonl", help="Path to input JSONL dataset")
|
| 55 |
+
parser.add_argument("--output_dir", type=str, default="./team_nena_sinllama_lora", help="Output directory for adapter")
|
| 56 |
+
parser.add_argument("--batch_size", type=int, default=4, help="Per device train batch size")
|
| 57 |
+
parser.add_argument("--grad_accum", type=int, default=4, help="Gradient accumulation steps")
|
| 58 |
+
parser.add_argument("--learning_rate", type=float, default=2e-5, help="Learning rate")
|
| 59 |
+
parser.add_argument("--epochs", type=int, default=3, help="Number of training epochs")
|
| 60 |
+
parser.add_argument("--max_seq_length", type=int, default=1024, help="Maximum sequence length")
|
| 61 |
+
parser.add_argument("--lora_rank", type=int, default=32, help="LoRA rank (r)")
|
| 62 |
+
parser.add_argument("--lora_alpha", type=int, default=64, help="LoRA alpha")
|
| 63 |
+
parser.add_argument("--lora_dropout", type=float, default=0.0, help="LoRA dropout")
|
| 64 |
+
return parser.parse_args()
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def load_and_preprocess_dataset(data_path: str):
|
| 68 |
+
"""
|
| 69 |
+
Loads raw curriculum MCQ items, generates 4-cyclic permutations to prevent
|
| 70 |
+
positional bias, and formats into Micro-CoT assistant completions.
|
| 71 |
+
"""
|
| 72 |
+
if not os.path.exists(data_path):
|
| 73 |
+
raise FileNotFoundError(f"Dataset file not found at {data_path}")
|
| 74 |
+
|
| 75 |
+
records = []
|
| 76 |
+
with open(data_path, "r", encoding="utf-8") as f:
|
| 77 |
+
for line in f:
|
| 78 |
+
line = line.strip()
|
| 79 |
+
if line:
|
| 80 |
+
records.append(json.loads(line))
|
| 81 |
+
|
| 82 |
+
print(f"Loaded {len(records)} raw MCQ records from {data_path}.")
|
| 83 |
+
|
| 84 |
+
all_samples = []
|
| 85 |
+
for r in records:
|
| 86 |
+
perms = generate_cyclic_permutations(r)
|
| 87 |
+
for p in perms:
|
| 88 |
+
formatted = format_micro_cot_sample(p)
|
| 89 |
+
all_samples.append(formatted["text"])
|
| 90 |
+
|
| 91 |
+
random.seed(42)
|
| 92 |
+
random.shuffle(all_samples)
|
| 93 |
+
print(f"Constructed {len(all_samples)} total training sequences (including cyclic permutations).")
|
| 94 |
+
return Dataset.from_dict({"text": all_samples})
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def main():
|
| 98 |
+
args = parse_args()
|
| 99 |
+
|
| 100 |
+
print("=" * 80)
|
| 101 |
+
print("TEAM NENA — SINLLAMA-8B LORA TRAINING PIPELINE")
|
| 102 |
+
print("=" * 80)
|
| 103 |
+
print(f"Base Model: {BASE_MODEL}")
|
| 104 |
+
print(f"LoRA Rank (r): {args.lora_rank}, Alpha: {args.lora_alpha}")
|
| 105 |
+
print(f"Batch Size: {args.batch_size} (Grad Accum: {args.grad_accum})")
|
| 106 |
+
print(f"Learning Rate: {args.learning_rate}")
|
| 107 |
+
print(f"Max Sequence Len: {args.max_seq_length}")
|
| 108 |
+
print("=" * 80)
|
| 109 |
+
|
| 110 |
+
# 1. Load Tokenizer
|
| 111 |
+
tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL)
|
| 112 |
+
tokenizer.padding_side = "right"
|
| 113 |
+
if tokenizer.pad_token is None:
|
| 114 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 115 |
+
|
| 116 |
+
# 2. Load Base Model in 4-bit NF4
|
| 117 |
+
bnb_config = BitsAndBytesConfig(
|
| 118 |
+
load_in_4bit=True,
|
| 119 |
+
bnb_4bit_quant_type="nf4",
|
| 120 |
+
bnb_4bit_compute_dtype=torch.float16,
|
| 121 |
+
bnb_4bit_use_double_quant=True,
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
print("Loading base SinLlama-8B backbone...")
|
| 125 |
+
base_model = AutoModelForCausalLM.from_pretrained(
|
| 126 |
+
BASE_MODEL,
|
| 127 |
+
quantization_config=bnb_config,
|
| 128 |
+
device_map="auto",
|
| 129 |
+
)
|
| 130 |
+
base_model = prepare_model_for_kbit_training(base_model)
|
| 131 |
+
|
| 132 |
+
# 3. Setup LoRA
|
| 133 |
+
lora_config = LoraConfig(
|
| 134 |
+
r=args.lora_rank,
|
| 135 |
+
lora_alpha=args.lora_alpha,
|
| 136 |
+
lora_dropout=args.lora_dropout,
|
| 137 |
+
bias="none",
|
| 138 |
+
task_type="CAUSAL_LM",
|
| 139 |
+
target_modules=[
|
| 140 |
+
"q_proj",
|
| 141 |
+
"k_proj",
|
| 142 |
+
"v_proj",
|
| 143 |
+
"o_proj",
|
| 144 |
+
"gate_proj",
|
| 145 |
+
"up_proj",
|
| 146 |
+
"down_proj",
|
| 147 |
+
],
|
| 148 |
+
)
|
| 149 |
+
model = get_peft_model(base_model, lora_config)
|
| 150 |
+
model.print_trainable_parameters()
|
| 151 |
+
|
| 152 |
+
# 4. Prepare Dataset
|
| 153 |
+
dataset = load_and_preprocess_dataset(args.data_file)
|
| 154 |
+
|
| 155 |
+
# 5. Collator for Completion-Only Loss Masking
|
| 156 |
+
collator = DataCollatorForCompletionOnlyLM(
|
| 157 |
+
response_template=RESPONSE_TEMPLATE,
|
| 158 |
+
tokenizer=tokenizer,
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
# 6. Training Arguments
|
| 162 |
+
training_args = TrainingArguments(
|
| 163 |
+
output_dir=args.output_dir,
|
| 164 |
+
per_device_train_batch_size=args.batch_size,
|
| 165 |
+
gradient_accumulation_steps=args.grad_accum,
|
| 166 |
+
num_train_epochs=args.epochs,
|
| 167 |
+
learning_rate=args.learning_rate,
|
| 168 |
+
lr_scheduler_type="cosine",
|
| 169 |
+
warmup_ratio=0.05,
|
| 170 |
+
weight_decay=0.01,
|
| 171 |
+
fp16=True,
|
| 172 |
+
logging_steps=10,
|
| 173 |
+
save_strategy="epoch",
|
| 174 |
+
save_total_limit=1,
|
| 175 |
+
report_to="none",
|
| 176 |
+
seed=42,
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
# 7. SFT Trainer
|
| 180 |
+
trainer = SFTTrainer(
|
| 181 |
+
model=model,
|
| 182 |
+
tokenizer=tokenizer,
|
| 183 |
+
train_dataset=dataset,
|
| 184 |
+
dataset_text_field="text",
|
| 185 |
+
max_seq_length=args.max_seq_length,
|
| 186 |
+
data_collator=collator,
|
| 187 |
+
args=training_args,
|
| 188 |
+
)
|
| 189 |
+
|
| 190 |
+
print("\nStarting training...")
|
| 191 |
+
trainer.train()
|
| 192 |
+
|
| 193 |
+
print(f"\nTraining completed. Saving adapter and tokenizer to {args.output_dir}...")
|
| 194 |
+
model.save_pretrained(args.output_dir)
|
| 195 |
+
tokenizer.save_pretrained(args.output_dir)
|
| 196 |
+
print("Save complete!")
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
if __name__ == "__main__":
|
| 200 |
+
main()
|