Taficritus commited on
Commit
e458d49
·
verified ·
1 Parent(s): 3dd70a9

Delete inference.py

Browse files
Files changed (1) hide show
  1. inference.py +0 -211
inference.py DELETED
@@ -1,211 +0,0 @@
1
- """
2
- Sinhala MMLU Shared Task - Final inference script
3
- Team: hakuru labs
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 -----------------------
28
- MODEL_RQ_BASE = "iCIIT/redqueenprotocol-sin-llama3.2-3B-model"
29
- MODEL_RQ_ADAPTER = "SinhalaMMLU-SharedTask/team-hakuru-labs-redqueen"
30
- MODEL_HL_BASE = "Jainamshahhh/helalm-4b"
31
- MODEL_HL_ADAPTER = "SinhalaMMLU-SharedTask/team-hakuru-labs-helalm"
32
-
33
- SEED = 3407
34
- BATCH = 1
35
- MAX_NEW_TOKENS = 16
36
- # -------------------------------------------------------------
37
-
38
- import json
39
- import os
40
- import random
41
- import re
42
- import numpy as np
43
- import torch
44
- from huggingface_hub import HfFileSystem, list_repo_files
45
- from collections import Counter
46
-
47
- LETTERS = ["A", "B", "C", "D"]
48
- ABSOLUTE_WORDS = ["සියල්ල", "කිසිවිටෙක", "සෑම", "හැමවිටම", "කිසිදා"]
49
- PENALTY = 2.0
50
- INSTRUCTION = "පහත බහුවරණ ප්‍රශ්නයට නිවැරදි පිළිතුර තෝරන්න. පළමුව සෑම විකල්පයක් ගැන පියවරෙන් පියවර සිතන්න, පසුව පිළිතුර ලෙස A, B, C, හෝ D පමණක් ලියන්න."
51
-
52
- def set_seed(seed):
53
- random.seed(seed)
54
- np.random.seed(seed)
55
- torch.manual_seed(seed)
56
- torch.cuda.manual_seed_all(seed)
57
-
58
- def check_parameters(model, name):
59
- total_params = sum(p.numel() for p in model.parameters())
60
- print(f"[{name}] Logical Parameters: {total_params:,} ({total_params/1e9:.3f} B)")
61
- return total_params
62
-
63
- def get_lexical_overlap(question, option):
64
- q_words = {w for w in re.findall(r'\b\w+\b', question) if len(w) > 3}
65
- o_words = {w for w in re.findall(r'\b\w+\b', option) if len(w) > 3}
66
- return len(q_words.intersection(o_words))
67
-
68
- # =============== 1. LOAD THE DATASET FROM HUGGING FACE (do not change) ===============
69
- def load_questions(data_repo):
70
- fs = HfFileSystem()
71
- files = sorted(f for f in list_repo_files(data_repo, repo_type="dataset") if f.endswith(".json"))
72
- rows = []
73
- for f in files:
74
- with fs.open(f"datasets/{data_repo}/{f}", "r", encoding="utf-8") as fh:
75
- raw = json.load(fh)
76
- if isinstance(raw, dict):
77
- raw = next(v for v in raw.values() if isinstance(v, list))
78
- for r in raw:
79
- r["_file"] = f
80
- rows.append(r)
81
- return rows
82
-
83
- def get_level(r):
84
- return (r.get("metadata") or {}).get("difficulty") or r["_file"].split("/")[0]
85
-
86
- # =============== 2. YOUR SYSTEM ===============
87
- def load_system():
88
- from unsloth import FastLanguageModel
89
- from peft import PeftModel
90
-
91
- print("Loading RedQueen v7...")
92
- model_rq, tokenizer_rq = FastLanguageModel.from_pretrained(
93
- model_name=MODEL_RQ_BASE, max_seq_length=2048, load_in_4bit=True, device_map="auto"
94
- )
95
- model_rq = PeftModel.from_pretrained(model_rq, MODEL_RQ_ADAPTER)
96
- model_rq = model_rq.to(torch.float16)
97
- FastLanguageModel.for_inference(model_rq)
98
- rq_params = check_parameters(model_rq, "RedQueen v7")
99
-
100
- print("Loading HelaLM v2...")
101
- model_hl, tokenizer_hl = FastLanguageModel.from_pretrained(
102
- model_name=MODEL_HL_BASE, max_seq_length=2048, load_in_4bit=True, device_map="auto"
103
- )
104
- model_hl = PeftModel.from_pretrained(model_hl, MODEL_HL_ADAPTER)
105
- model_hl = model_hl.to(torch.float16)
106
- FastLanguageModel.for_inference(model_hl)
107
- hl_params = check_parameters(model_hl, "HelaLM v2")
108
-
109
- total_ensemble_params = rq_params + hl_params
110
- print(f"\n=======================================================")
111
- print(f"TOTAL ENSEMBLE PARAMETERS: {total_ensemble_params:,} ({total_ensemble_params/1e9:.3f} B)")
112
- if total_ensemble_params <= 8_000_000_000:
113
- print("✅ COMPLIANT: Total parameters are under the 8B limit.")
114
- else:
115
- print("❌ WARNING: Total parameters exceed the 8B limit!")
116
- print(f"=======================================================\n")
117
-
118
- return (model_rq, tokenizer_rq, model_hl, tokenizer_hl)
119
-
120
- @torch.no_grad()
121
- def predict_all(system, rows):
122
- model_rq, tokenizer_rq, model_hl, tokenizer_hl = system
123
-
124
- def build_rq_prompt(q, opts):
125
- block = "\n".join(f"{LETTERS[i]}) {opts[i].strip()}" for i in range(4))
126
- return f"### Instruction:\n{INSTRUCTION}\n\n### Input:\n{q.strip()}\n{block}\n\n### Response:\nපිළිතුර:"
127
-
128
- def build_hl_prompt(q, opts):
129
- block = "\n".join(f"{LETTERS[i]}) {opts[i].strip()}" for i in range(4))
130
- return (f"<start_of_turn>user\n{q.strip()}\n{block}<end_of_turn>\n"
131
- f"<start_of_turn>model\nපිළිතුර:")
132
-
133
- ids_rq = {L: list(set(tokenizer_rq(f" {L}", add_special_tokens=False).input_ids + tokenizer_rq(L, add_special_tokens=False).input_ids)) for L in LETTERS}
134
- ids_hl = {L: list(set(tokenizer_hl(f" {L}", add_special_tokens=False).input_ids + tokenizer_hl(L, add_special_tokens=False).input_ids)) for L in LETTERS}
135
-
136
- @torch.no_grad()
137
- def get_consistent_logits(model, tok, q, opts, ids_map, prompt_builder, n_runs=5):
138
- rng = random.Random(SEED)
139
- avg_logits = {L: 0.0 for L in LETTERS}
140
- for _ in range(n_runs):
141
- order = list(range(4))
142
- rng.shuffle(order)
143
- shuffled_opts = [opts[i] for i in order]
144
- prompt = prompt_builder(q, shuffled_opts)
145
- inputs = tok(prompt, return_tensors="pt").to("cuda")
146
- logits = model(**inputs).logits[0, -1, :]
147
- run_scores = {L: max(logits[t].item() for t in ids_map[L]) for L in LETTERS}
148
- for i, original_idx in enumerate(order):
149
- avg_logits[LETTERS[original_idx]] += run_scores[LETTERS[i]]
150
- return {L: avg_logits[L] / n_runs for L in LETTERS}
151
-
152
- answers = []
153
- for i, rec in enumerate(rows):
154
- q = rec["question"]
155
- opts = rec["choices"]
156
- level = str(get_level(rec)).lower()
157
-
158
- if level == "hard":
159
- # Route ONLY to HelaLM for Hard questions
160
- final_scores = get_consistent_logits(model_hl, tokenizer_hl, q, opts, ids_hl, build_hl_prompt)
161
- else:
162
- # Use Ensemble for Easy/Medium
163
- rq_avg = get_consistent_logits(model_rq, tokenizer_rq, q, opts, ids_rq, build_rq_prompt)
164
- hl_avg = get_consistent_logits(model_hl, tokenizer_hl, q, opts, ids_hl, build_hl_prompt)
165
- final_scores = {L: (rq_avg[L] + hl_avg[L]) / 2.0 for L in LETTERS}
166
-
167
- for j, opt in enumerate(opts):
168
- if any(word in opt for word in ABSOLUTE_WORDS):
169
- final_scores[LETTERS[j]] -= PENALTY
170
-
171
- sorted_scores = sorted(final_scores.items(), key=lambda x: x[1], reverse=True)
172
- top_letter, top_score = sorted_scores[0]
173
- second_letter, second_score = sorted_scores[1]
174
-
175
- pred_idx = LETTERS.index(top_letter)
176
- if (top_score - second_score) < 1.5:
177
- top_idx = LETTERS.index(top_letter)
178
- second_idx = LETTERS.index(second_letter)
179
- if get_lexical_overlap(q, opts[second_idx]) > get_lexical_overlap(q, opts[top_idx]):
180
- pred_idx = second_idx
181
-
182
- answers.append(str(pred_idx + 1))
183
-
184
- if (i+1) % 100 == 0:
185
- print(f"Processed {i+1}/{len(rows)}", end="\r")
186
-
187
- return answers
188
-
189
-
190
- # =============== 3. WRITE PREDICTIONS (do not change) ===============
191
- if __name__ == "__main__":
192
- set_seed(SEED)
193
- rows = load_questions(DATA_REPO)
194
- print(len(rows), "questions loaded from", DATA_REPO)
195
-
196
- system = load_system()
197
- answers = predict_all(system, rows)
198
-
199
- assert len(answers) == len(rows), "predict_all() must return one answer per question"
200
- with open(OUTPUT_FILE, "w", encoding="utf-8") as f:
201
- for r, a in zip(rows, answers):
202
- a = str(a).strip()
203
- assert a in {"1", "2", "3", "4"}, f"invalid answer {a!r} for q_no={r.get('q_no')}"
204
- f.write(json.dumps({
205
- "q_no": r["q_no"],
206
- "subject": r["subject"],
207
- "category": r["category"],
208
- "level": get_level(r),
209
- "answer": a,
210
- }, ensure_ascii=False, separators=(",", ":")) + "\n")
211
- print("\nSaved", OUTPUT_FILE)