Papajams commited on
Commit
90bfc30
·
verified ·
1 Parent(s): 97542f0

Upload script.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. script.py +119 -0
script.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Competition submission script — copy this into your HF repo as script.py.
3
+
4
+ The eval sandbox:
5
+ - mounts the test set at /tmp/data/test.csv
6
+ - has no internet
7
+ - runs on a T4 (16GB)
8
+ - has 30 minutes
9
+ - has bitsandbytes and autoawq pre-installed
10
+
11
+ Ship your fine-tuned model weights in the same HF repo and load from ".".
12
+ """
13
+
14
+ import json
15
+ import os
16
+ import re
17
+
18
+ os.environ["HF_HUB_OFFLINE"] = "1"
19
+ os.environ["TRANSFORMERS_OFFLINE"] = "1"
20
+ MODEL_ID = "."
21
+
22
+ import pandas as pd
23
+ import torch
24
+ from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
25
+
26
+ from prompts import get_system_prompt, USER_TEMPLATE, parse_answers, count_query_items
27
+
28
+
29
+ def load_model():
30
+ """Load the fine-tuned model with 4-bit quantization."""
31
+ bnb_config = BitsAndBytesConfig(
32
+ load_in_4bit=True,
33
+ bnb_4bit_compute_dtype=torch.float16,
34
+ bnb_4bit_quant_type="nf4",
35
+ bnb_4bit_use_double_quant=True,
36
+ )
37
+
38
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
39
+ model = AutoModelForCausalLM.from_pretrained(
40
+ MODEL_ID,
41
+ quantization_config=bnb_config,
42
+ device_map="auto",
43
+ torch_dtype=torch.float16,
44
+ )
45
+ model.eval()
46
+
47
+ return tokenizer, model
48
+
49
+
50
+ def solve_problem(
51
+ tokenizer,
52
+ model,
53
+ context: str,
54
+ query: str,
55
+ task_type: str = "",
56
+ max_new_tokens: int = 1024,
57
+ ) -> list[str]:
58
+ """Generate answers for one IOL problem with task-specific prompting."""
59
+ n_items = count_query_items(query)
60
+ system_prompt = get_system_prompt(task_type)
61
+
62
+ messages = [
63
+ {"role": "system", "content": system_prompt},
64
+ {"role": "user", "content": USER_TEMPLATE.format(
65
+ context=context.strip(), query=query.strip()
66
+ )},
67
+ ]
68
+
69
+ ids = tokenizer.apply_chat_template(
70
+ messages, add_generation_prompt=True, return_tensors="pt"
71
+ ).to(model.device)
72
+
73
+ with torch.no_grad():
74
+ out = model.generate(
75
+ ids,
76
+ max_new_tokens=max_new_tokens,
77
+ do_sample=False, # greedy decoding for reproducibility
78
+ temperature=1.0, # ignored with do_sample=False but avoids warnings
79
+ pad_token_id=tokenizer.eos_token_id,
80
+ )
81
+
82
+ text = tokenizer.decode(out[0][ids.shape[-1] :], skip_special_tokens=True).strip()
83
+ answers = parse_answers(text, n_expected=n_items, task_type=task_type)
84
+
85
+ return answers
86
+
87
+
88
+ def main():
89
+ print("[submit] Loading model...", flush=True)
90
+ tokenizer, model = load_model()
91
+
92
+ print("[submit] Reading test set...", flush=True)
93
+ df = pd.read_csv("/tmp/data/test.csv", dtype=str).fillna("")
94
+ print(f"[submit] Loaded {len(df)} problems", flush=True)
95
+
96
+ rows = []
97
+ for idx, row in df.iterrows():
98
+ answers = solve_problem(
99
+ tokenizer,
100
+ model,
101
+ context=row["context"],
102
+ query=row["query"],
103
+ task_type=row.get("task_type", ""),
104
+ )
105
+ rows.append({
106
+ "id": row["id"],
107
+ "pred": json.dumps(answers, ensure_ascii=False),
108
+ })
109
+
110
+ if (idx + 1) % 5 == 0 or idx == 0:
111
+ print(f"[submit] {idx + 1}/{len(df)} done", flush=True)
112
+
113
+ output = pd.DataFrame(rows)
114
+ output.to_csv("submission.csv", index=False)
115
+ print(f"[submit] wrote submission.csv ({len(rows)} problems)", flush=True)
116
+
117
+
118
+ if __name__ == "__main__":
119
+ main()