File size: 7,524 Bytes
d442557
53cd911
 
 
 
 
 
 
 
 
 
 
 
 
 
d442557
 
 
 
53cd911
d442557
 
 
 
53cd911
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d442557
 
 
 
 
 
 
 
53cd911
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d442557
 
 
 
 
 
 
 
 
53cd911
d442557
 
 
 
53cd911
 
d442557
 
53cd911
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d442557
53cd911
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d442557
53cd911
d442557
53cd911
 
 
 
 
 
d442557
 
53cd911
d442557
 
 
53cd911
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d442557
 
 
53cd911
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d442557
 
53cd911
 
 
 
 
 
 
 
 
 
 
 
d442557
53cd911
 
 
 
 
 
 
d442557
 
 
 
 
 
53cd911
 
 
d442557
 
53cd911
d442557
53cd911
d442557
53cd911
 
d442557
 
53cd911
 
d442557
 
 
53cd911
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d442557
53cd911
 
 
 
d442557
53cd911
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
#import subprocess, sys
#subprocess.run(
#    [
#        sys.executable,
#        "-m",
#        "pip",
#        "install",
#        "-q",
#        "transformers>=4.43",
#        "accelerate>=0.30",
#        "torch>=2.2",
#        "pandas",
#    ],
#    check=True,
#)

import os
import re
import json

import pandas as pd
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM

from incontext_examples import INCONTEXT_EXAMPLES


# The repository is the working directory at runtime.
# The evaluation sandbox has no internet access.
os.environ["HF_HUB_OFFLINE"] = "1"
os.environ["TRANSFORMERS_OFFLINE"] = "1"

MODEL_ID = "."
TEST_PATH = "/tmp/data/test.csv"
OUTPUT_PATH = "submission.csv"

MAX_NEW_TOKENS = 1536

tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)

if tokenizer.pad_token_id is None:
    tokenizer.pad_token = tokenizer.eos_token


model = AutoModelForCausalLM.from_pretrained(
    MODEL_ID,
    torch_dtype=torch.float16,
    device_map="auto",
).eval()


df = pd.read_csv(
    TEST_PATH,
    dtype=str,
).fillna("")


required_columns = {
    "id",
    "context",
    "query",
    "task_type",
}

missing_columns = required_columns - set(df.columns)

if missing_columns:
    raise ValueError(
        "The test CSV is missing required columns: "
        f"{sorted(missing_columns)}"
    )


SYSTEM = (
    "You solve International Linguistics Olympiad problems by reasoning from the "
    "data you are given. You may meet a task type you have never seen: read the "
    "instruction and the examples, and answer in the same form they use. "
    "Common task types and what to give -- "
    "translation: the translated form only, in the language the task asks for; "
    "fill_blanks: only the missing form for each blank; "
    "match_letters: only the option letter, for example A, B, or C; "
    "text_to_num: the number in digits; "
    "num_to_text: the number written out in words, in the language asked; "
    "any other type: give exactly what the instruction asks, nothing else. "
    "Reason step by step first. Then write a line that says exactly FINAL ANSWERS: "
    "and, below it, one answer per line in the order the items are asked. "
    "Each final answer must be bare: no numbering, no quotes, and no extra text."
)


def normalize_task_type(task_type):
    """
    Normalize task-type names so capitalization, spaces, and hyphens
    do not prevent a match.

    Examples:
        "Num To Text" -> "num_to_text"
        "fill-blanks" -> "fill_blanks"
    """
    task_type = str(task_type).strip().lower()
    task_type = re.sub(r"[\s-]+", "_", task_type)
    return task_type


def parse_answers(text):
    """
    Keep only nonempty lines after the final FINAL ANSWERS marker.

    If the model adds numbering such as:
        1. answer
        2) answer

    the numbering is removed.
    """
    markers = list(
        re.finditer(
            r"(?im)^\s*final answers?\s*:?\s*$",
            text,
        )
    )

    if markers:
        text = text[markers[-1].end():]

    answers = []

    for line in text.splitlines():
        line = re.sub(
            r"^\s*\d+[.)]\s*",
            "",
            line,
        ).strip()

        if line:
            answers.append(line)

    return answers


def format_example_assistant_response(example):
    """
    Format the stored reasoning trace and answers as an assistant message.
    """
    reasoning = str(
        example.get("reasoning", "")
    ).strip()

    answers = example.get("answers", [])

    if isinstance(answers, str):
        answers = [
            line.strip()
            for line in answers.splitlines()
            if line.strip()
        ]

    formatted_answers = "\n".join(
        str(answer).strip()
        for answer in answers
    )

    if reasoning:
        return (
            f"{reasoning}\n\n"
            f"FINAL ANSWERS:\n"
            f"{formatted_answers}"
        )

    return (
        f"FINAL ANSWERS:\n"
        f"{formatted_answers}"
    )


def get_incontext_example(task_type):
    """
    Retrieve the demonstration matching the current problem's task type.

    Returns None when no demonstration exists for that task type.
    """
    normalized_type = normalize_task_type(task_type)

    # Normalize the dictionary keys as well, so keys such as
    # "num-to-text" and "num_to_text" are treated equivalently.
    normalized_examples = {
        normalize_task_type(key): value
        for key, value in INCONTEXT_EXAMPLES.items()
    }

    return normalized_examples.get(normalized_type)


def build_messages(row):
    """
    Construct the conversation for one test problem.

    The conversation contains:
      1. the system prompt;
      2. a solved demonstration of the same task type, when available;
      3. the actual test problem.
    """
    task_type = normalize_task_type(
        row["task_type"]
    )

    example = get_incontext_example(
        task_type
    )

    messages = [
        {
            "role": "system",
            "content": SYSTEM,
        }
    ]

    if example is not None:
        example_context = str(
            example.get("context", "")
        ).strip()

        example_query = str(
            example.get("query", "")
        ).strip()

        messages.extend(
            [
                {
                    "role": "user",
                    "content": (
                        f"Task type: {task_type}\n\n"
                        f"{example_context}\n\n"
                        f"{example_query}"
                    ),
                },
                {
                    "role": "assistant",
                    "content": format_example_assistant_response(
                        example
                    ),
                },
            ]
        )
    else:
        print(
            "Warning: no in-context example found for "
            f"task_type={task_type!r}, id={row['id']!r}. "
            "Running the problem without a demonstration."
        )

    problem_context = str(
        row["context"]
    ).strip()

    problem_query = str(
        row["query"]
    ).strip()

    messages.append(
        {
            "role": "user",
            "content": (
                f"Task type: {task_type}\n\n"
                f"{problem_context}\n\n"
                f"{problem_query}"
            ),
        }
    )

    return messages


rows = []


for _, row in df.iterrows():
    messages = build_messages(
        row
    )

    inputs = tokenizer.apply_chat_template(
        messages,
        add_generation_prompt=True,
        return_tensors="pt",
        return_dict=True,
    ).to(model.device)

    input_length = inputs[
        "input_ids"
    ].shape[-1]

    with torch.no_grad():
        output = model.generate(
            **inputs,
            max_new_tokens=MAX_NEW_TOKENS,
            do_sample=False,
            pad_token_id=tokenizer.pad_token_id,
            eos_token_id=tokenizer.eos_token_id,
        )

    generated_text = tokenizer.decode(
        output[0][input_length:],
        skip_special_tokens=True,
    ).strip()

    answers = parse_answers(
        generated_text
    )

    rows.append(
        {
            "id": row["id"],
            "pred": json.dumps(
                answers,
                ensure_ascii=False,
            ),
        }
    )


submission_df = pd.DataFrame(
    rows
)

submission_df.to_csv(
    OUTPUT_PATH,
    index=False,
)

print(
    f"Saved {len(submission_df)} predictions to {OUTPUT_PATH}"
)