EjZhou Santhoshini commited on
Commit
7f0fd63
·
0 Parent(s):

Duplicate from Santhoshini/iol-solver-14b

Browse files

Co-authored-by: Pranathi <Santhoshini@users.noreply.huggingface.co>

.gitattributes ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ base_model: Qwen/Qwen2.5-14B-Instruct
3
+ language:
4
+ - zho
5
+ - eng
6
+ - fra
7
+ - spa
8
+ - por
9
+ - deu
10
+ - ita
11
+ - rus
12
+ - jpn
13
+ - kor
14
+ - vie
15
+ - tha
16
+ - ara
17
+ library_name: transformers
18
+ license: apache-2.0
19
+ tags:
20
+ - unsloth
21
+ - transformers
22
+ ---
23
+
24
+ # Finetune Llama 3.1, Gemma 2, Mistral 2-5x faster with 70% less memory via Unsloth!
25
+
26
+ We have a Qwen 2.5 (all model sizes) [free Google Colab Tesla T4 notebook](https://colab.research.google.com/drive/1Kose-ucXO1IBaZq5BvbwWieuubP7hxvQ?usp=sharing).
27
+ Also a [Qwen 2.5 conversational style notebook](https://colab.research.google.com/drive/1qN1CEalC70EO1wGKhNxs1go1W9So61R5?usp=sharing).
28
+
29
+ [<img src="https://raw.githubusercontent.com/unslothai/unsloth/main/images/Discord%20button.png" width="200"/>](https://discord.gg/unsloth)
30
+ [<img src="https://raw.githubusercontent.com/unslothai/unsloth/main/images/unsloth%20made%20with%20love.png" width="200"/>](https://github.com/unslothai/unsloth)
31
+
32
+ ## ✨ Finetune for Free
33
+
34
+ All notebooks are **beginner friendly**! Add your dataset, click "Run All", and you'll get a 2x faster finetuned model which can be exported to GGUF, vLLM or uploaded to Hugging Face.
35
+
36
+ | Unsloth supports | Free Notebooks | Performance | Memory use |
37
+ |-----------------|--------------------------------------------------------------------------------------------------------------------------|-------------|----------|
38
+ | **Llama-3.1 8b** | [▶️ Start on Colab](https://colab.research.google.com/drive/1Ys44kVvmeZtnICzWz0xgpRnrIOjZAuxp?usp=sharing) | 2.4x faster | 58% less |
39
+ | **Phi-3.5 (mini)** | [▶️ Start on Colab](https://colab.research.google.com/drive/1lN6hPQveB_mHSnTOYifygFcrO8C1bxq4?usp=sharing) | 2x faster | 50% less |
40
+ | **Gemma-2 9b** | [▶️ Start on Colab](https://colab.research.google.com/drive/1vIrqH5uYDQwsJ4-OO3DErvuv4pBgVwk4?usp=sharing) | 2.4x faster | 58% less |
41
+ | **Mistral 7b** | [▶️ Start on Colab](https://colab.research.google.com/drive/1Dyauq4kTZoLewQ1cApceUQVNcnnNTzg_?usp=sharing) | 2.2x faster | 62% less |
42
+ | **TinyLlama** | [▶️ Start on Colab](https://colab.research.google.com/drive/1AZghoNBQaMDgWJpi4RbffGM1h6raLUj9?usp=sharing) | 3.9x faster | 74% less |
43
+ | **DPO - Zephyr** | [▶️ Start on Colab](https://colab.research.google.com/drive/15vttTpzzVXv_tJwEk-hIcQ0S9FcEWvwP?usp=sharing) | 1.9x faster | 19% less |
44
+
45
+ - This [conversational notebook](https://colab.research.google.com/drive/1Aau3lgPzeZKQ-98h69CCu1UJcvIBLmy2?usp=sharing) is useful for ShareGPT ChatML / Vicuna templates.
46
+ - This [text completion notebook](https://colab.research.google.com/drive/1ef-tab5bhkvWmBOObepl1WgJvfvSzn5Q?usp=sharing) is for raw text. This [DPO notebook](https://colab.research.google.com/drive/15vttTpzzVXv_tJwEk-hIcQ0S9FcEWvwP?usp=sharing) replicates Zephyr.
47
+ - \* Kaggle has 2x T4s, but we use 1. Due to overhead, 1x T4 is 5x faster.
48
+
49
+ # Qwen2.5-14B-Instruct
50
+
51
+ ## Introduction
52
+
53
+ Qwen2.5 is the latest series of Qwen large language models. For Qwen2.5, we release a number of base language models and instruction-tuned language models ranging from 0.5 to 72 billion parameters. Qwen2.5 brings the following improvements upon Qwen2:
54
+
55
+ - Significantly **more knowledge** and has greatly improved capabilities in **coding** and **mathematics**, thanks to our specialized expert models in these domains.
56
+ - Significant improvements in **instruction following**, **generating long texts** (over 8K tokens), **understanding structured data** (e.g, tables), and **generating structured outputs** especially JSON. **More resilient to the diversity of system prompts**, enhancing role-play implementation and condition-setting for chatbots.
57
+ - **Long-context Support** up to 128K tokens and can generate up to 8K tokens.
58
+ - **Multilingual support** for over 29 languages, including Chinese, English, French, Spanish, Portuguese, German, Italian, Russian, Japanese, Korean, Vietnamese, Thai, Arabic, and more.
59
+
60
+ **This repo contains the instruction-tuned 14B Qwen2.5 model**, which has the following features:
61
+ - Type: Causal Language Models
62
+ - Training Stage: Pretraining & Post-training
63
+ - Architecture: transformers with RoPE, SwiGLU, RMSNorm, and Attention QKV bias
64
+ - Number of Parameters: 14.7B
65
+ - Number of Paramaters (Non-Embedding): 13.1B
66
+ - Number of Layers: 48
67
+ - Number of Attention Heads (GQA): 40 for Q and 8 for KV
68
+ - Context Length: Full 131,072 tokens and generation 8192 tokens
69
+ - Please refer to [this section](#processing-long-texts) for detailed instructions on how to deploy Qwen2.5 for handling long texts.
70
+
71
+ For more details, please refer to our [blog](https://qwenlm.github.io/blog/qwen2.5/), [GitHub](https://github.com/QwenLM/Qwen2.5), and [Documentation](https://qwen.readthedocs.io/en/latest/).
72
+
73
+ ## Requirements
74
+
75
+ The code of Qwen2.5 has been in the latest Hugging face `transformers` and we advise you to use the latest version of `transformers`.
76
+
77
+ With `transformers<4.37.0`, you will encounter the following error:
78
+ ```
79
+ KeyError: 'qwen2'
80
+ ```
81
+
82
+ ## Quickstart
83
+
84
+ Here provides a code snippet with `apply_chat_template` to show you how to load the tokenizer and model and how to generate contents.
85
+
86
+ ```python
87
+ from transformers import AutoModelForCausalLM, AutoTokenizer
88
+
89
+ model_name = "Qwen/Qwen2.5-14B-Instruct"
90
+
91
+ model = AutoModelForCausalLM.from_pretrained(
92
+ model_name,
93
+ torch_dtype="auto",
94
+ device_map="auto"
95
+ )
96
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
97
+
98
+ prompt = "Give me a short introduction to large language model."
99
+ messages = [
100
+ {"role": "system", "content": "You are Qwen, created by Alibaba Cloud. You are a helpful assistant."},
101
+ {"role": "user", "content": prompt}
102
+ ]
103
+ text = tokenizer.apply_chat_template(
104
+ messages,
105
+ tokenize=False,
106
+ add_generation_prompt=True
107
+ )
108
+ model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
109
+
110
+ generated_ids = model.generate(
111
+ **model_inputs,
112
+ max_new_tokens=512
113
+ )
114
+ generated_ids = [
115
+ output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
116
+ ]
117
+
118
+ response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
119
+ ```
120
+
121
+ ### Processing Long Texts
122
+
123
+ The current `config.json` is set for context length up to 32,768 tokens.
124
+ To handle extensive inputs exceeding 32,768 tokens, we utilize [YaRN](https://arxiv.org/abs/2309.00071), a technique for enhancing model length extrapolation, ensuring optimal performance on lengthy texts.
125
+
126
+ For supported frameworks, you could add the following to `config.json` to enable YaRN:
127
+ ```json
128
+ {
129
+ ...,
130
+ "rope_scaling": {
131
+ "factor": 4.0,
132
+ "original_max_position_embeddings": 32768,
133
+ "type": "yarn"
134
+ }
135
+ }
136
+ ```
137
+
138
+ For deployment, we recommend using vLLM.
139
+ Please refer to our [Documentation](https://qwen.readthedocs.io/en/latest/deployment/vllm.html) for usage if you are not familar with vLLM.
140
+ Presently, vLLM only supports static YARN, which means the scaling factor remains constant regardless of input length, **potentially impacting performance on shorter texts**.
141
+ We advise adding the `rope_scaling` configuration only when processing long contexts is required.
142
+
143
+ ## Evaluation & Performance
144
+
145
+ Detailed evaluation results are reported in this [📑 blog](https://qwenlm.github.io/blog/qwen2.5/).
146
+
147
+ For requirements on GPU memory and the respective throughput, see results [here](https://qwen.readthedocs.io/en/latest/benchmark/speed_benchmark.html).
148
+
149
+ ## Citation
150
+
151
+ If you find our work helpful, feel free to give us a cite.
152
+
153
+ ```
154
+ @misc{qwen2.5,
155
+ title = {Qwen2.5: A Party of Foundation Models},
156
+ url = {https://qwenlm.github.io/blog/qwen2.5/},
157
+ author = {Qwen Team},
158
+ month = {September},
159
+ year = {2024}
160
+ }
161
+
162
+ @article{qwen2,
163
+ title={Qwen2 Technical Report},
164
+ author={An Yang and Baosong Yang and Binyuan Hui and Bo Zheng and Bowen Yu and Chang Zhou and Chengpeng Li and Chengyuan Li and Dayiheng Liu and Fei Huang and Guanting Dong and Haoran Wei and Huan Lin and Jialong Tang and Jialin Wang and Jian Yang and Jianhong Tu and Jianwei Zhang and Jianxin Ma and Jin Xu and Jingren Zhou and Jinze Bai and Jinzheng He and Junyang Lin and Kai Dang and Keming Lu and Keqin Chen and Kexin Yang and Mei Li and Mingfeng Xue and Na Ni and Pei Zhang and Peng Wang and Ru Peng and Rui Men and Ruize Gao and Runji Lin and Shijie Wang and Shuai Bai and Sinan Tan and Tianhang Zhu and Tianhao Li and Tianyu Liu and Wenbin Ge and Xiaodong Deng and Xiaohuan Zhou and Xingzhang Ren and Xinyu Zhang and Xipin Wei and Xuancheng Ren and Yang Fan and Yang Yao and Yichang Zhang and Yu Wan and Yunfei Chu and Yuqiong Liu and Zeyu Cui and Zhenru Zhang and Zhihao Fan},
165
+ journal={arXiv preprint arXiv:2407.10671},
166
+ year={2024}
167
+ }
168
+ ```
added_tokens.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "</tool_call>": 151658,
3
+ "<tool_call>": 151657,
4
+ "<|box_end|>": 151649,
5
+ "<|box_start|>": 151648,
6
+ "<|endoftext|>": 151643,
7
+ "<|file_sep|>": 151664,
8
+ "<|fim_middle|>": 151660,
9
+ "<|fim_pad|>": 151662,
10
+ "<|fim_prefix|>": 151659,
11
+ "<|fim_suffix|>": 151661,
12
+ "<|im_end|>": 151645,
13
+ "<|im_start|>": 151644,
14
+ "<|image_pad|>": 151655,
15
+ "<|object_ref_end|>": 151647,
16
+ "<|object_ref_start|>": 151646,
17
+ "<|quad_end|>": 151651,
18
+ "<|quad_start|>": 151650,
19
+ "<|repo_name|>": 151663,
20
+ "<|video_pad|>": 151656,
21
+ "<|vision_end|>": 151653,
22
+ "<|vision_pad|>": 151654,
23
+ "<|vision_start|>": 151652
24
+ }
config.json ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "Qwen/Qwen2.5-14B-Instruct",
3
+ "architectures": [
4
+ "Qwen2ForCausalLM"
5
+ ],
6
+ "attention_dropout": 0.0,
7
+ "eos_token_id": 151645,
8
+ "hidden_act": "silu",
9
+ "hidden_size": 5120,
10
+ "initializer_range": 0.02,
11
+ "intermediate_size": 13824,
12
+ "max_position_embeddings": 32768,
13
+ "max_window_layers": 70,
14
+ "model_type": "qwen2",
15
+ "num_attention_heads": 40,
16
+ "num_hidden_layers": 48,
17
+ "num_key_value_heads": 8,
18
+ "pad_token_id": 151654,
19
+ "quantization_config": {
20
+ "_load_in_4bit": true,
21
+ "_load_in_8bit": false,
22
+ "bnb_4bit_compute_dtype": "bfloat16",
23
+ "bnb_4bit_quant_storage": "uint8",
24
+ "bnb_4bit_quant_type": "nf4",
25
+ "bnb_4bit_use_double_quant": true,
26
+ "llm_int8_enable_fp32_cpu_offload": false,
27
+ "llm_int8_has_fp16_weight": false,
28
+ "llm_int8_skip_modules": [
29
+ "lm_head",
30
+ "multi_modal_projector",
31
+ "merger",
32
+ "modality_projection"
33
+ ],
34
+ "llm_int8_threshold": 6.0,
35
+ "load_in_4bit": true,
36
+ "load_in_8bit": false,
37
+ "quant_method": "bitsandbytes"
38
+ },
39
+ "rms_norm_eps": 1e-06,
40
+ "rope_scaling": null,
41
+ "rope_theta": 1000000.0,
42
+ "sliding_window": null,
43
+ "tie_word_embeddings": false,
44
+ "torch_dtype": "bfloat16",
45
+ "transformers_version": "4.49.0.dev0",
46
+ "unsloth_fixed": true,
47
+ "use_cache": true,
48
+ "use_sliding_window": false,
49
+ "vocab_size": 152064
50
+ }
generation_config.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token_id": 151643,
3
+ "do_sample": true,
4
+ "eos_token_id": [
5
+ 151645,
6
+ 151643
7
+ ],
8
+ "max_length": 32768,
9
+ "pad_token_id": 151654,
10
+ "repetition_penalty": 1.05,
11
+ "temperature": 0.7,
12
+ "top_k": 20,
13
+ "top_p": 0.8,
14
+ "transformers_version": "4.49.0.dev0"
15
+ }
merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
model-00001-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1f89ef40e93d53cb7f41c0b731b1becb1cfa34ae0c918f3262d4f5778d6b290a
3
+ size 4998641596
model-00002-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f3d1de5ed64b7987c2e559791d1c43d0e6cdac067cde3aec2bd5f4538738e7c4
3
+ size 4933695780
model.safetensors.index.json ADDED
The diff for this file is too large to render. See raw diff
 
script.py ADDED
@@ -0,0 +1,570 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # script.py — TIME-SAFE single shot on the proven 0.104 pipeline.
2
+ # Qwen2.5-14B-Instruct-bnb-4bit. Install only bitsandbytes --no-deps.
3
+ # =============================================================================
4
+ # Design principle after the collapses: every failed submission ADDED model
5
+ # generations per row and pushed toward a 30-min timeout. This file REMOVES a
6
+ # wasted generation and adds only ZERO-COST (no model call) improvements, so it
7
+ # runs FASTER than the 0.104 baseline while targeting exact_match.
8
+ #
9
+ # CHANGES vs 0.104 (all deterministic, none add a generation):
10
+ # 1. clean_answer: NFC unicode normalization (canonical only).
11
+ # 2. match_letters: deterministic pure-Python BIJECTION REPAIR of the greedy
12
+ # answer when #letters == #items -- keeps the letters the model committed
13
+ # to, fills duplicates/missing with the leftover letters, guaranteeing a
14
+ # valid permutation. No model call. Untouched if already valid.
15
+ # 3. explanation: use the model's own reasoning snippet (truncated) instead
16
+ # of a SECOND per-row generation. The explanation column is NOT scored
17
+ # automatically, so this costs no score but ~halves per-row time -> more
18
+ # rows finish, answers get more headroom, timeout risk drops.
19
+ # NO sampling, NO MBR, NO model swap, NO extra generations.
20
+ # =============================================================================
21
+ import os
22
+ import atexit
23
+ import unicodedata
24
+ _ORIGINAL_HF_HUB_OFFLINE = os.environ.get("HF_HUB_OFFLINE")
25
+ _ORIGINAL_TRANSFORMERS_OFFLINE = os.environ.get("TRANSFORMERS_OFFLINE")
26
+ def _restore_offline_env_vars():
27
+ for key, original in (("HF_HUB_OFFLINE", _ORIGINAL_HF_HUB_OFFLINE),
28
+ ("TRANSFORMERS_OFFLINE", _ORIGINAL_TRANSFORMERS_OFFLINE)):
29
+ if original is None:
30
+ os.environ.pop(key, None)
31
+ else:
32
+ os.environ[key] = original
33
+ atexit.register(_restore_offline_env_vars)
34
+ os.environ["HF_HUB_OFFLINE"] = "1"
35
+ os.environ["TRANSFORMERS_OFFLINE"] = "1"
36
+ import subprocess, sys
37
+ def emergency_submission_csv(reason, rows_so_far=None):
38
+ try:
39
+ import pandas as pd
40
+ if rows_so_far:
41
+ pd.DataFrame(rows_so_far).to_csv("submission.csv", index=False)
42
+ return
43
+ try:
44
+ df = pd.read_csv("/tmp/data/test.csv", dtype=str).fillna("")
45
+ ids = df["id"].tolist()
46
+ except Exception:
47
+ ids = []
48
+ import json as _json
49
+ rows = [{"id": i, "pred": _json.dumps([""]),
50
+ "explanation": f"EMERGENCY FALLBACK: {str(reason)[:150]}"} for i in ids]
51
+ pd.DataFrame(rows, columns=["id", "pred", "explanation"]).to_csv("submission.csv", index=False)
52
+ except Exception:
53
+ try:
54
+ with open("submission.csv", "w") as f:
55
+ f.write("id,pred,explanation\n")
56
+ except Exception:
57
+ pass
58
+ def write_submission_csv(rows_list):
59
+ import csv as _csv
60
+ tmp_path = "submission.csv.tmp"
61
+ with open(tmp_path, "w", newline="", encoding="utf-8") as f:
62
+ w = _csv.DictWriter(f, fieldnames=["id", "pred", "explanation"])
63
+ w.writeheader()
64
+ for row in rows_list:
65
+ w.writerow(row)
66
+ os.replace(tmp_path, "submission.csv")
67
+ try:
68
+ subprocess.run([sys.executable, "-m", "pip", "install", "-q",
69
+ "--no-deps", "bitsandbytes"], check=True)
70
+ except Exception as e:
71
+ emergency_submission_csv(f"pip install failed: {e}")
72
+ raise
73
+ import re, json, time, ast as pyast
74
+ import pandas as pd
75
+ import torch
76
+ from transformers import AutoTokenizer, AutoModelForCausalLM
77
+ MODEL_ID = "."
78
+ TIME_LIMIT_S = 30 * 60
79
+ SETUP_BUFFER_S = 420
80
+ start_time = time.time()
81
+ try:
82
+ df = pd.read_csv("/tmp/data/test.csv", dtype=str).fillna("")
83
+ placeholder_rows = [{"id": rid, "pred": json.dumps([""]),
84
+ "explanation": "Placeholder written before model load."}
85
+ for rid in df["id"].tolist()]
86
+ write_submission_csv(placeholder_rows)
87
+ print(f"Pre-load checkpoint written for {len(placeholder_rows)} rows.", flush=True)
88
+ try:
89
+ tok = AutoTokenizer.from_pretrained(MODEL_ID)
90
+ print("Tokenizer loaded (fast).", flush=True)
91
+ except Exception as e:
92
+ print(f"Fast tokenizer failed ({e}); falling back to use_fast=False.", flush=True)
93
+ tok = AutoTokenizer.from_pretrained(MODEL_ID, use_fast=False)
94
+ print("Tokenizer loaded (slow fallback).", flush=True)
95
+ model = AutoModelForCausalLM.from_pretrained(
96
+ MODEL_ID, torch_dtype=torch.float16, device_map="auto",
97
+ ).eval()
98
+ print("RUN MARKER: time-safe-v1", flush=True)
99
+ print(f"Model loaded | memory footprint: {round(model.get_memory_footprint()/1e9, 1)} GB | "
100
+ f"quantized: {getattr(model.config, 'quantization_config', None) is not None}", flush=True)
101
+ except Exception as e:
102
+ emergency_submission_csv(f"tokenizer/model load or test.csv read failed: {e}")
103
+ raise
104
+ n_rows = len(df)
105
+ actual_setup_elapsed = time.time() - start_time
106
+ per_row_budget = max(20, (TIME_LIMIT_S - actual_setup_elapsed) / max(n_rows, 1))
107
+ print(f"Setup took {actual_setup_elapsed:.0f}s | per_row_budget={per_row_budget:.0f}s "
108
+ f"for {n_rows} rows", flush=True)
109
+ def parse_items(query: str):
110
+ item_pat = re.compile(r"(?m)^\s*(\d+)\s*[.\)]\s*(.*)$")
111
+ matches = list(item_pat.finditer(query))
112
+ if matches:
113
+ preamble = query[:matches[0].start()].strip()
114
+ items = []
115
+ for i, m in enumerate(matches):
116
+ end = matches[i + 1].start() if i + 1 < len(matches) else len(query)
117
+ text = re.sub(r"^\s*\d+\s*[.\)]\s*", "", query[m.start():end].strip())
118
+ items.append(text)
119
+ return preamble, items, True
120
+ rng = re.search(r"[\(\[]?\s*(\d+)\s*(?:[-–—:]|to)\s*(\d+)\s*[\)\]]?", query, flags=re.IGNORECASE)
121
+ if rng:
122
+ lo, hi = int(rng.group(1)), int(rng.group(2))
123
+ if 0 < hi - lo < 100:
124
+ items = []
125
+ for k in range(lo, hi + 1):
126
+ line_match = re.search(rf"(?m)^.*\(\s*{k}\s*\).*$", query)
127
+ if line_match:
128
+ clue = re.sub(rf"\(\s*{k}\s*\)", "", line_match.group(0)).strip()
129
+ clue = re.sub(r"\|\s*\|", "|", clue)
130
+ clue = re.sub(r"\s{2,}", " ", clue).strip(" |")
131
+ items.append(clue if clue else f"the numbered item {k} from the examples above")
132
+ else:
133
+ items.append(f"the numbered item {k} from the examples above")
134
+ return query.strip(), items, True
135
+ csv_nums = re.findall(r"(?m)^\s*(\d+)\s*,\s*(\d+(?:\s*,\s*\d+)*)\s*$", query)
136
+ if csv_nums:
137
+ all_nums = re.findall(r"\d+", " ".join(csv_nums[0]))
138
+ return query.strip(), [f"the numbered item {n}" for n in all_nums], True
139
+ return query.strip(), [], False
140
+ TASK_GUIDANCE = {
141
+ "translation": "give the translated form only, in the language asked.",
142
+ "fill_blanks": "give only the missing form for each blank.",
143
+ "match_letters": "give only the option letter (for example A, B, C). Each item "
144
+ "matches exactly one distinct letter; when there are as many letters "
145
+ "as items, each letter is used exactly once.",
146
+ "text_to_num": "give the number in digits.",
147
+ "num_to_text": "give the number written out in words, in the language asked.",
148
+ }
149
+ DEFAULT_GUIDANCE = "give exactly what the instruction asks, nothing else."
150
+ from difflib import SequenceMatcher
151
+ from collections import defaultdict
152
+ def extract_forms_from_context(context: str):
153
+ forms = []
154
+ for line in context.splitlines():
155
+ line = line.strip()
156
+ if not line:
157
+ continue
158
+ pipe_count = line.count("|")
159
+ if 0 < pipe_count <= 3:
160
+ first_field = re.sub(r"^\s*\d+\s*[.\)]\s*", "", line.split("|")[0].strip()).strip()
161
+ if first_field:
162
+ forms.append(first_field)
163
+ elif pipe_count == 0:
164
+ for t in line.split():
165
+ t_clean = re.sub(r"^\s*\d+\s*[.\)]\s*", "", t).strip(".,;:")
166
+ if t_clean and len(t_clean) > 1:
167
+ forms.append(t_clean)
168
+ seen, unique_forms = set(), []
169
+ for f in forms:
170
+ if f not in seen:
171
+ seen.add(f)
172
+ unique_forms.append(f)
173
+ return unique_forms
174
+ def extract_explicit_pairs(context: str):
175
+ pairs = []
176
+ for line in context.splitlines():
177
+ line = line.strip()
178
+ if not (0 < line.count("|") <= 3):
179
+ continue
180
+ fields = [re.sub(r"^\s*\d+\s*[.\)]\s*", "", f.strip()).strip() for f in line.split("|")]
181
+ fields = [f for f in fields if f]
182
+ if len(fields) >= 2:
183
+ pairs.append((fields[0], fields[1]))
184
+ return pairs
185
+ def edit_signature(a: str, b: str):
186
+ sm = SequenceMatcher(None, a, b, autojunk=False)
187
+ all_ops = sm.get_opcodes()
188
+ ops = [op for op in all_ops if op[0] != "equal"]
189
+ if not ops or len(ops) > 2:
190
+ return None
191
+ equal_len = sum((i2 - i1) for tag, i1, i2, j1, j2 in all_ops if tag == "equal")
192
+ if equal_len < 2:
193
+ return None
194
+ tag, i1, i2, j1, j2 = ops[0]
195
+ removed, inserted = a[i1:i2], b[j1:j2]
196
+ if i1 == 0:
197
+ pos = "prefix"
198
+ elif i2 == len(a):
199
+ pos = "suffix"
200
+ else:
201
+ pos = "infix"
202
+ return (pos, removed, inserted)
203
+ def find_transformation_families(pairs):
204
+ groups = defaultdict(list)
205
+ for a, b in pairs:
206
+ if not a or not b or a == b:
207
+ continue
208
+ sig = edit_signature(a, b)
209
+ if sig:
210
+ groups[sig].append((a, b))
211
+ families = []
212
+ for sig, grp in groups.items():
213
+ unique_pairs = list(dict.fromkeys(grp))
214
+ if len(unique_pairs) >= 2:
215
+ pos, removed, inserted = sig
216
+ removed_disp = removed if removed else "(nothing)"
217
+ inserted_disp = inserted if inserted else "(nothing)"
218
+ examples = "; ".join(f"{a}->{b}" for a, b in unique_pairs[:4])
219
+ families.append((len(unique_pairs),
220
+ f"{pos} change: '{removed_disp}' -> '{inserted_disp}' (seen in: {examples})"))
221
+ families.sort(key=lambda x: -x[0])
222
+ return [f for _, f in families]
223
+ def detect_reduplication(forms):
224
+ findings = []
225
+ for w in forms:
226
+ n = len(w)
227
+ found = False
228
+ for length in range(2, n // 2 + 1):
229
+ for start in range(0, n - 2 * length + 1):
230
+ chunk = w[start:start + length]
231
+ nxt = w[start + length:start + 2 * length]
232
+ if chunk == nxt:
233
+ findings.append(f"reduplication in '{w}': '{chunk}' repeated")
234
+ found = True
235
+ break
236
+ if found:
237
+ break
238
+ return findings
239
+ def build_symbolic_evidence(context: str) -> str:
240
+ forms = extract_forms_from_context(context)
241
+ pairs = extract_explicit_pairs(context)
242
+ families = find_transformation_families(pairs) if pairs else []
243
+ redup = detect_reduplication(forms) if forms else []
244
+ lines = []
245
+ if families:
246
+ lines.append("Transformation families found (patterns supported by multiple examples):")
247
+ for f in families[:3]:
248
+ lines.append(f"- {f}")
249
+ if redup:
250
+ lines.append("Reduplication detected:")
251
+ for r in redup[:2]:
252
+ lines.append(f"- {r}")
253
+ if not lines:
254
+ return ""
255
+ return ("\n\nSYMBOLIC EVIDENCE (deterministically computed from the examples above; "
256
+ "may be incomplete -- verify against the examples, do not trust blindly):\n"
257
+ + "\n".join(lines))
258
+ def direction_note(query, task_type):
259
+ """Generalizable IOL answer-formatting rules learned from the gold data:
260
+ - Translation INTO English: the reference reproduces the exact glossing
261
+ conventions from the examples, especially person/number markers written
262
+ like you_{sg}, you_{pl}. Models that write plain 'you' lose exact match
263
+ on many items even when the translation is correct.
264
+ - Any answer in the TARGET language (translate-into-X, fill_blanks,
265
+ num_to_text): the reference uses the exact special characters/symbols
266
+ from the examples (e.g. ʼ ɡ ɨ ʂ ʦ). Look-alike ASCII substitutions lose
267
+ exact match. We instruct fidelity rather than substituting characters
268
+ ourselves (which would risk corrupting correct answers)."""
269
+ q = (query or "").lower()
270
+ into_english = "into english" in q
271
+ if task_type == "translation":
272
+ if into_english:
273
+ return ("\nMatch the English style of the examples EXACTLY: keep person/number "
274
+ "markers written as you_{sg}, you_{pl} (and he, she, it, we, they), and "
275
+ "reproduce every such annotation verbatim as it appears in the examples.")
276
+ return ("\nWrite the answer using ONLY the exact characters and symbols that appear "
277
+ "in the examples (including special letters and diacritics); never replace "
278
+ "them with similar-looking ordinary letters.")
279
+ if task_type in ("fill_blanks", "num_to_text"):
280
+ return ("\nWrite the answer using ONLY the exact characters and symbols that appear "
281
+ "in the examples (including special letters and diacritics); never replace "
282
+ "them with similar-looking ordinary letters.")
283
+ return ""
284
+ def build_messages(context, query, task_type):
285
+ preamble, items, count_known = parse_items(query)
286
+ guidance = TASK_GUIDANCE.get(task_type, DEFAULT_GUIDANCE)
287
+ guidance = guidance + direction_note(query, task_type)
288
+ symbolic_evidence = build_symbolic_evidence(context)
289
+ system = (
290
+ "You solve puzzles about a language you have never seen. Everything you "
291
+ "need is in the examples below. Use only the examples, not outside "
292
+ "knowledge of any language. You may meet a task type you have never "
293
+ "seen -- read the instruction and examples, and answer in the same "
294
+ "form they use."
295
+ )
296
+ number_note = ""
297
+ if task_type == "text_to_num":
298
+ number_note = (
299
+ "\n\nAlso add one more line after your answers, exactly like this:\n"
300
+ "COMPUTE: expr1 | expr2\n"
301
+ "where each expr is a plain arithmetic expression (digits, +, -, *, "
302
+ "parentheses only) for that item's value, one per answer, matching "
303
+ "the rule you found."
304
+ )
305
+ options_note = ""
306
+ if task_type == "match_letters":
307
+ options = extract_match_letter_options(context)
308
+ if options:
309
+ options_note = (
310
+ f"\n\nThe only valid answers are: {', '.join(options)}. "
311
+ f"Do not use any other letter."
312
+ )
313
+ if count_known:
314
+ n_items = len(items)
315
+ slots = "\n\n".join(f"Question {i+1}: {it}\nAnswer {i+1}:" for i, it in enumerate(items))
316
+ user = (
317
+ f"EXAMPLES:\n{context.strip()}"
318
+ f"{symbolic_evidence}\n\n"
319
+ f"--- The examples end here. The questions begin below. ---\n\n"
320
+ f"For each question: find the rule that explains ALL the examples above "
321
+ f"(not just one). Check it against every example before answering. "
322
+ f"For this task type, {guidance}\n\n"
323
+ f"{preamble}\n\n{slots}\n\n"
324
+ f"After answering all {n_items} questions, finish with exactly one line, "
325
+ f"all {n_items} answers in order separated by ' | ':\n"
326
+ f"FINAL ANSWERS: answer1 | answer2"
327
+ f"{number_note}"
328
+ f"{options_note}"
329
+ )
330
+ else:
331
+ n_items = None
332
+ user = (
333
+ f"EXAMPLES:\n{context.strip()}"
334
+ f"{symbolic_evidence}\n\n"
335
+ f"--- The examples end here. The question begins below. ---\n\n"
336
+ f"Find the rule that explains ALL the examples above (not just one). "
337
+ f"Check it against every example before answering. "
338
+ f"For this task type, {guidance}\n\n"
339
+ f"{preamble}\n\n"
340
+ f"Answer every item asked above, in order, one per answer. Finish "
341
+ f"with exactly one line, all your answers in order separated by ' | ':\n"
342
+ f"FINAL ANSWERS: answer1 | answer2"
343
+ f"{number_note}"
344
+ f"{options_note}"
345
+ )
346
+ return [{"role": "system", "content": system}, {"role": "user", "content": user}], n_items
347
+ def build_repair_messages(query, n_items, bad_text):
348
+ n_desc = f"exactly {n_items}" if n_items is not None else "one per item asked"
349
+ system = "You reformat answers. Output nothing except the requested line."
350
+ user = (
351
+ f"Question:\n{query.strip()}\n\n"
352
+ f"A previous attempt produced:\n{bad_text[:600]}\n\n"
353
+ f"Extract or restate {n_desc} final answers, in order, as ONE line:\n"
354
+ f"FINAL ANSWERS: answer1 | answer2"
355
+ )
356
+ return [{"role": "system", "content": system}, {"role": "user", "content": user}]
357
+ _ALLOWED_BINOPS = (pyast.Add, pyast.Sub, pyast.Mult)
358
+ def safe_arithmetic(expr: str):
359
+ try:
360
+ tree = pyast.parse(expr.strip(), mode="eval")
361
+ except Exception:
362
+ return None
363
+ def _eval(node):
364
+ if isinstance(node, pyast.Expression):
365
+ return _eval(node.body)
366
+ if isinstance(node, pyast.Constant) and isinstance(node.value, (int, float)):
367
+ return node.value
368
+ if isinstance(node, pyast.BinOp) and isinstance(node.op, _ALLOWED_BINOPS):
369
+ left, right = _eval(node.left), _eval(node.right)
370
+ if left is None or right is None:
371
+ return None
372
+ if isinstance(node.op, pyast.Add): return left + right
373
+ if isinstance(node.op, pyast.Sub): return left - right
374
+ if isinstance(node.op, pyast.Mult): return left * right
375
+ if isinstance(node, pyast.UnaryOp) and isinstance(node.op, pyast.USub):
376
+ v = _eval(node.operand)
377
+ return -v if v is not None else None
378
+ return None
379
+ return _eval(tree)
380
+ def clean_answer(a: str) -> str:
381
+ a = unicodedata.normalize("NFC", a)
382
+ a = re.sub(r"(?i)^\s*(the\s+)?(final\s+)?answer\s*\d*\s*(is)?\s*:\s*", "", a).strip()
383
+ a = re.sub(r"(?i)^\s*is\s*:\s*", "", a).strip()
384
+ a = a.strip("* ")
385
+ return a.strip(" .\"'“”‘’")
386
+ def extract(text):
387
+ m = list(re.finditer(r"final answers?\s*:?\s*\**", text, flags=re.IGNORECASE))
388
+ if m:
389
+ tail = text[m[-1].end():]
390
+ stop = re.search(r"(?i)compute\s*:", tail)
391
+ if stop:
392
+ tail = tail[:stop.start()]
393
+ tail = tail.replace("**", " ").strip()
394
+ candidate = " ".join(tail.splitlines())
395
+ parts = [clean_answer(p) for p in candidate.split("|") if p.strip()]
396
+ if parts:
397
+ return parts, m[-1].start()
398
+ lines = [ln.strip() for ln in text.splitlines() if ln.strip()]
399
+ fallback = []
400
+ for ln in lines:
401
+ ln_clean = re.sub(r"^\s*\d+\s*[.\)]\s*", "", ln)
402
+ if "|" in ln_clean:
403
+ fallback.extend(clean_answer(p) for p in ln_clean.split("|") if p.strip())
404
+ else:
405
+ fallback.append(clean_answer(ln_clean))
406
+ return fallback, None
407
+ def extract_compute_overrides(text, n_answers):
408
+ m = re.search(r"compute\s*:\s*(.+)", text, flags=re.IGNORECASE)
409
+ if not m:
410
+ return {}
411
+ exprs = [e.strip() for e in m.group(1).split("|")]
412
+ overrides = {}
413
+ for i, e in enumerate(exprs[:n_answers]):
414
+ val = safe_arithmetic(e)
415
+ if val is not None:
416
+ overrides[i] = str(int(val)) if float(val).is_integer() else str(val)
417
+ return overrides
418
+ def generate(messages, max_new_tokens, constraint_fn=None):
419
+ def _try_generate(gen_kwargs):
420
+ try:
421
+ enc = tok.apply_chat_template(
422
+ messages, add_generation_prompt=True, return_tensors="pt", return_dict=True,
423
+ ).to(model.device)
424
+ input_len = enc["input_ids"].shape[-1]
425
+ with torch.no_grad():
426
+ out = model.generate(**enc, **gen_kwargs)
427
+ except Exception:
428
+ ids = tok.apply_chat_template(
429
+ messages, add_generation_prompt=True, return_tensors="pt",
430
+ ).to(model.device)
431
+ input_len = ids.shape[-1]
432
+ with torch.no_grad():
433
+ out = model.generate(ids, **gen_kwargs)
434
+ return out, input_len
435
+ base_kwargs = {"max_new_tokens": max_new_tokens, "do_sample": False}
436
+ if constraint_fn is not None:
437
+ try:
438
+ out, input_len = _try_generate({**base_kwargs, "prefix_allowed_tokens_fn": constraint_fn})
439
+ except Exception:
440
+ out, input_len = _try_generate(base_kwargs)
441
+ else:
442
+ out, input_len = _try_generate(base_kwargs)
443
+ return tok.decode(out[0][input_len:], skip_special_tokens=True).strip()
444
+ EXPLANATION_FALLBACK = "Answer derived from patterns found in the examples above."
445
+ def extract_match_letter_options(context: str):
446
+ found = set()
447
+ for line in context.splitlines():
448
+ for m in re.finditer(r"(?:^|\s)([A-Z])[.\)]\s+\S", line):
449
+ found.add(m.group(1))
450
+ if not found:
451
+ return None
452
+ letters = sorted(found)
453
+ expected = [chr(ord("A") + i) for i in range(len(letters))]
454
+ if letters != expected:
455
+ return None
456
+ if not (2 <= len(letters) <= 26):
457
+ return None
458
+ return letters
459
+ def repair_bijection(answers, labels, n_items):
460
+ """Deterministic, no model call. Keep the letters the model committed to
461
+ (first occurrence wins); fill duplicate/invalid/missing slots with the
462
+ leftover letters in order. Guarantees a valid permutation. If the answer
463
+ is already a valid permutation it is returned unchanged."""
464
+ labels_sorted = sorted(labels)
465
+ picks = []
466
+ for i in range(n_items):
467
+ a = answers[i] if i < len(answers) else ""
468
+ found = re.findall(r"[A-Za-z]", a or "")
469
+ c = found[0].upper() if found else ""
470
+ picks.append(c if c in labels else "")
471
+ result = [None] * n_items
472
+ used = set()
473
+ for i in range(n_items):
474
+ c = picks[i]
475
+ if c and c not in used:
476
+ result[i] = c
477
+ used.add(c)
478
+ missing = [l for l in labels_sorted if l not in used]
479
+ mi = 0
480
+ for i in range(n_items):
481
+ if result[i] is None:
482
+ result[i] = missing[mi] if mi < len(missing) else labels_sorted[0]
483
+ mi += 1
484
+ return result
485
+ rows = []
486
+ processed_ids = set()
487
+ try:
488
+ for _, r in df.iterrows():
489
+ try:
490
+ elapsed = time.time() - start_time
491
+ remaining = TIME_LIMIT_S - elapsed
492
+ budget_left_rows = max(n_rows - len(rows), 1)
493
+ row_budget = remaining / budget_left_rows
494
+ time_based_cap = 1280 if row_budget > per_row_budget else 640
495
+ task_type = r.get("task_type", "")
496
+ messages, n_items = build_messages(r["context"], r["query"], task_type)
497
+ if n_items:
498
+ item_based_cap = max(640, min(1536, n_items * 48 + 256))
499
+ tokens_cap = min(time_based_cap, item_based_cap)
500
+ else:
501
+ tokens_cap = time_based_cap
502
+ text = generate(messages, tokens_cap)
503
+ answers, marker_pos = extract(text)
504
+ if task_type == "text_to_num":
505
+ overrides = extract_compute_overrides(text, len(answers))
506
+ for idx, val in overrides.items():
507
+ if idx < len(answers):
508
+ answers[idx] = val
509
+ if (marker_pos is None or not answers) and remaining > SETUP_BUFFER_S:
510
+ repair_constraint = None
511
+ repair_text = generate(build_repair_messages(r["query"], n_items, text), 128,
512
+ constraint_fn=repair_constraint)
513
+ rep, rep_pos = extract(repair_text)
514
+ if rep:
515
+ answers, marker_pos = rep, rep_pos
516
+ if n_items is not None:
517
+ if len(answers) < n_items:
518
+ answers = answers + [answers[-1] if answers else ""] * (n_items - len(answers))
519
+ elif len(answers) > n_items and marker_pos is None:
520
+ answers = answers[:n_items]
521
+ if not answers:
522
+ answers = [""]
523
+ # ---- match_letters: deterministic bijection repair (no model call) ----
524
+ # For matching, the numbered items live in the CONTEXT, not the query,
525
+ # so n_items (from the query) is None here. Derive the expected count
526
+ # from the context's numbered lines, and only repair in the clean
527
+ # bijection case (context item count == number of option letters).
528
+ if task_type == "match_letters":
529
+ labels = extract_match_letter_options(r["context"])
530
+ if labels and len(labels) >= 2:
531
+ ctx_item_count = len(re.findall(r"(?m)^\s*\d+\s*[.\)]", r["context"]))
532
+ if ctx_item_count == len(labels):
533
+ answers = repair_bijection(answers, set(labels), len(labels))
534
+ # ---- explanation: cheap reasoning snippet, NO second generation ----
535
+ snippet = re.sub(r"\s{2,}", " ", text[:300]).strip()
536
+ explanation = snippet if snippet else EXPLANATION_FALLBACK
537
+ rows.append({"id": r["id"], "pred": json.dumps(answers, ensure_ascii=False),
538
+ "explanation": explanation})
539
+ processed_ids.add(r["id"])
540
+ write_submission_csv(rows)
541
+ print(f"{len(rows)}/{n_rows} answers={len(answers)} elapsed={time.time()-start_time:.0f}s", flush=True)
542
+ except Exception as e:
543
+ try:
544
+ _, fallback_items, fk = parse_items(r["query"])
545
+ n_fallback = len(fallback_items) if fk else 1
546
+ except Exception:
547
+ n_fallback = 1
548
+ rows.append({"id": r["id"], "pred": json.dumps([""] * n_fallback, ensure_ascii=False),
549
+ "explanation": EXPLANATION_FALLBACK})
550
+ processed_ids.add(r["id"])
551
+ write_submission_csv(rows)
552
+ print(f"ROW ERROR on {r['id']}: {e}", flush=True)
553
+ if time.time() - start_time > TIME_LIMIT_S - 60:
554
+ print("Time budget nearly exhausted, stopping early.", flush=True)
555
+ break
556
+ for _, r in df.iterrows():
557
+ if r["id"] in processed_ids:
558
+ continue
559
+ try:
560
+ _, fallback_items, fk = parse_items(r["query"])
561
+ n_fallback = len(fallback_items) if fk else 1
562
+ except Exception:
563
+ n_fallback = 1
564
+ rows.append({"id": r["id"], "pred": json.dumps([""] * n_fallback, ensure_ascii=False),
565
+ "explanation": EXPLANATION_FALLBACK})
566
+ write_submission_csv(rows)
567
+ print("DONE.", flush=True)
568
+ except Exception as e:
569
+ emergency_submission_csv(f"main loop failed: {e}", rows_so_far=rows if rows else None)
570
+ print(f"FATAL, but submission.csv was written with {len(rows)} rows. Error: {e}", flush=True)
special_tokens_map.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<|im_start|>",
4
+ "<|im_end|>",
5
+ "<|object_ref_start|>",
6
+ "<|object_ref_end|>",
7
+ "<|box_start|>",
8
+ "<|box_end|>",
9
+ "<|quad_start|>",
10
+ "<|quad_end|>",
11
+ "<|vision_start|>",
12
+ "<|vision_end|>",
13
+ "<|vision_pad|>",
14
+ "<|image_pad|>",
15
+ "<|video_pad|>"
16
+ ],
17
+ "eos_token": {
18
+ "content": "<|im_end|>",
19
+ "lstrip": false,
20
+ "normalized": false,
21
+ "rstrip": false,
22
+ "single_word": false
23
+ },
24
+ "pad_token": {
25
+ "content": "<|vision_pad|>",
26
+ "lstrip": false,
27
+ "normalized": false,
28
+ "rstrip": false,
29
+ "single_word": false
30
+ }
31
+ }
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9c5ae00e602b8860cbd784ba82a8aa14e8feecec692e7076590d014d7b7fdafa
3
+ size 11421896
tokenizer_config.json ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_prefix_space": false,
4
+ "added_tokens_decoder": {
5
+ "151643": {
6
+ "content": "<|endoftext|>",
7
+ "lstrip": false,
8
+ "normalized": false,
9
+ "rstrip": false,
10
+ "single_word": false,
11
+ "special": true
12
+ },
13
+ "151644": {
14
+ "content": "<|im_start|>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false,
19
+ "special": true
20
+ },
21
+ "151645": {
22
+ "content": "<|im_end|>",
23
+ "lstrip": false,
24
+ "normalized": false,
25
+ "rstrip": false,
26
+ "single_word": false,
27
+ "special": true
28
+ },
29
+ "151646": {
30
+ "content": "<|object_ref_start|>",
31
+ "lstrip": false,
32
+ "normalized": false,
33
+ "rstrip": false,
34
+ "single_word": false,
35
+ "special": true
36
+ },
37
+ "151647": {
38
+ "content": "<|object_ref_end|>",
39
+ "lstrip": false,
40
+ "normalized": false,
41
+ "rstrip": false,
42
+ "single_word": false,
43
+ "special": true
44
+ },
45
+ "151648": {
46
+ "content": "<|box_start|>",
47
+ "lstrip": false,
48
+ "normalized": false,
49
+ "rstrip": false,
50
+ "single_word": false,
51
+ "special": true
52
+ },
53
+ "151649": {
54
+ "content": "<|box_end|>",
55
+ "lstrip": false,
56
+ "normalized": false,
57
+ "rstrip": false,
58
+ "single_word": false,
59
+ "special": true
60
+ },
61
+ "151650": {
62
+ "content": "<|quad_start|>",
63
+ "lstrip": false,
64
+ "normalized": false,
65
+ "rstrip": false,
66
+ "single_word": false,
67
+ "special": true
68
+ },
69
+ "151651": {
70
+ "content": "<|quad_end|>",
71
+ "lstrip": false,
72
+ "normalized": false,
73
+ "rstrip": false,
74
+ "single_word": false,
75
+ "special": true
76
+ },
77
+ "151652": {
78
+ "content": "<|vision_start|>",
79
+ "lstrip": false,
80
+ "normalized": false,
81
+ "rstrip": false,
82
+ "single_word": false,
83
+ "special": true
84
+ },
85
+ "151653": {
86
+ "content": "<|vision_end|>",
87
+ "lstrip": false,
88
+ "normalized": false,
89
+ "rstrip": false,
90
+ "single_word": false,
91
+ "special": true
92
+ },
93
+ "151654": {
94
+ "content": "<|vision_pad|>",
95
+ "lstrip": false,
96
+ "normalized": false,
97
+ "rstrip": false,
98
+ "single_word": false,
99
+ "special": true
100
+ },
101
+ "151655": {
102
+ "content": "<|image_pad|>",
103
+ "lstrip": false,
104
+ "normalized": false,
105
+ "rstrip": false,
106
+ "single_word": false,
107
+ "special": true
108
+ },
109
+ "151656": {
110
+ "content": "<|video_pad|>",
111
+ "lstrip": false,
112
+ "normalized": false,
113
+ "rstrip": false,
114
+ "single_word": false,
115
+ "special": true
116
+ },
117
+ "151657": {
118
+ "content": "<tool_call>",
119
+ "lstrip": false,
120
+ "normalized": false,
121
+ "rstrip": false,
122
+ "single_word": false,
123
+ "special": false
124
+ },
125
+ "151658": {
126
+ "content": "</tool_call>",
127
+ "lstrip": false,
128
+ "normalized": false,
129
+ "rstrip": false,
130
+ "single_word": false,
131
+ "special": false
132
+ },
133
+ "151659": {
134
+ "content": "<|fim_prefix|>",
135
+ "lstrip": false,
136
+ "normalized": false,
137
+ "rstrip": false,
138
+ "single_word": false,
139
+ "special": false
140
+ },
141
+ "151660": {
142
+ "content": "<|fim_middle|>",
143
+ "lstrip": false,
144
+ "normalized": false,
145
+ "rstrip": false,
146
+ "single_word": false,
147
+ "special": false
148
+ },
149
+ "151661": {
150
+ "content": "<|fim_suffix|>",
151
+ "lstrip": false,
152
+ "normalized": false,
153
+ "rstrip": false,
154
+ "single_word": false,
155
+ "special": false
156
+ },
157
+ "151662": {
158
+ "content": "<|fim_pad|>",
159
+ "lstrip": false,
160
+ "normalized": false,
161
+ "rstrip": false,
162
+ "single_word": false,
163
+ "special": false
164
+ },
165
+ "151663": {
166
+ "content": "<|repo_name|>",
167
+ "lstrip": false,
168
+ "normalized": false,
169
+ "rstrip": false,
170
+ "single_word": false,
171
+ "special": false
172
+ },
173
+ "151664": {
174
+ "content": "<|file_sep|>",
175
+ "lstrip": false,
176
+ "normalized": false,
177
+ "rstrip": false,
178
+ "single_word": false,
179
+ "special": false
180
+ }
181
+ },
182
+ "additional_special_tokens": [
183
+ "<|im_start|>",
184
+ "<|im_end|>",
185
+ "<|object_ref_start|>",
186
+ "<|object_ref_end|>",
187
+ "<|box_start|>",
188
+ "<|box_end|>",
189
+ "<|quad_start|>",
190
+ "<|quad_end|>",
191
+ "<|vision_start|>",
192
+ "<|vision_end|>",
193
+ "<|vision_pad|>",
194
+ "<|image_pad|>",
195
+ "<|video_pad|>"
196
+ ],
197
+ "bos_token": null,
198
+ "chat_template": "{%- if tools %}\n {{- '<|im_start|>system\\n' }}\n {%- if messages[0]['role'] == 'system' %}\n {{- messages[0]['content'] }}\n {%- else %}\n {{- 'You are Qwen, created by Alibaba Cloud. You are a helpful assistant.' }}\n {%- endif %}\n {{- \"\\n\\n# Tools\\n\\nYou may call one or more functions to assist with the user query.\\n\\nYou are provided with function signatures within <tools></tools> XML tags:\\n<tools>\" }}\n {%- for tool in tools %}\n {{- \"\\n\" }}\n {{- tool | tojson }}\n {%- endfor %}\n {{- \"\\n</tools>\\n\\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\\n<tool_call>\\n{\\\"name\\\": <function-name>, \\\"arguments\\\": <args-json-object>}\\n</tool_call><|im_end|>\\n\" }}\n{%- else %}\n {%- if messages[0]['role'] == 'system' %}\n {{- '<|im_start|>system\\n' + messages[0]['content'] + '<|im_end|>\\n' }}\n {%- else %}\n {{- '<|im_start|>system\\nYou are Qwen, created by Alibaba Cloud. You are a helpful assistant.<|im_end|>\\n' }}\n {%- endif %}\n{%- endif %}\n{%- for message in messages %}\n {%- if (message.role == \"user\") or (message.role == \"system\" and not loop.first) or (message.role == \"assistant\" and not message.tool_calls) %}\n {{- '<|im_start|>' + message.role + '\\n' + message.content + '<|im_end|>' + '\\n' }}\n {%- elif message.role == \"assistant\" %}\n {{- '<|im_start|>' + message.role }}\n {%- if message.content %}\n {{- '\\n' + message.content }}\n {%- endif %}\n {%- for tool_call in message.tool_calls %}\n {%- if tool_call.function is defined %}\n {%- set tool_call = tool_call.function %}\n {%- endif %}\n {{- '\\n<tool_call>\\n{\"name\": \"' }}\n {{- tool_call.name }}\n {{- '\", \"arguments\": ' }}\n {{- tool_call.arguments | tojson }}\n {{- '}\\n</tool_call>' }}\n {%- endfor %}\n {{- '<|im_end|>\\n' }}\n {%- elif message.role == \"tool\" %}\n {%- if (loop.index0 == 0) or (messages[loop.index0 - 1].role != \"tool\") %}\n {{- '<|im_start|>user' }}\n {%- endif %}\n {{- '\\n<tool_response>\\n' }}\n {{- message.content }}\n {{- '\\n</tool_response>' }}\n {%- if loop.last or (messages[loop.index0 + 1].role != \"tool\") %}\n {{- '<|im_end|>\\n' }}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<|im_start|>assistant\\n' }}\n{%- endif %}\n",
199
+ "clean_up_tokenization_spaces": false,
200
+ "eos_token": "<|im_end|>",
201
+ "errors": "replace",
202
+ "extra_special_tokens": {},
203
+ "model_max_length": 32768,
204
+ "pad_token": "<|vision_pad|>",
205
+ "padding_side": "left",
206
+ "split_special_tokens": false,
207
+ "tokenizer_class": "Qwen2Tokenizer",
208
+ "unk_token": null
209
+ }
vocab.json ADDED
The diff for this file is too large to render. See raw diff