初始化项目,由ModelHub XC社区提供模型
Model: pei39/iol-qwen2.5-14b-sft-awq Source: Original Platform
This commit is contained in:
36
.gitattributes
vendored
Normal file
36
.gitattributes
vendored
Normal file
@@ -0,0 +1,36 @@
|
||||
*.7z filter=lfs diff=lfs merge=lfs -text
|
||||
*.arrow filter=lfs diff=lfs merge=lfs -text
|
||||
*.bin filter=lfs diff=lfs merge=lfs -text
|
||||
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
||||
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
||||
*.ftz filter=lfs diff=lfs merge=lfs -text
|
||||
*.gz filter=lfs diff=lfs merge=lfs -text
|
||||
*.h5 filter=lfs diff=lfs merge=lfs -text
|
||||
*.joblib filter=lfs diff=lfs merge=lfs -text
|
||||
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
||||
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
||||
*.model filter=lfs diff=lfs merge=lfs -text
|
||||
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
||||
*.npy filter=lfs diff=lfs merge=lfs -text
|
||||
*.npz filter=lfs diff=lfs merge=lfs -text
|
||||
*.onnx filter=lfs diff=lfs merge=lfs -text
|
||||
*.ot filter=lfs diff=lfs merge=lfs -text
|
||||
*.parquet filter=lfs diff=lfs merge=lfs -text
|
||||
*.pb filter=lfs diff=lfs merge=lfs -text
|
||||
*.pickle filter=lfs diff=lfs merge=lfs -text
|
||||
*.pkl filter=lfs diff=lfs merge=lfs -text
|
||||
*.pt filter=lfs diff=lfs merge=lfs -text
|
||||
*.pth filter=lfs diff=lfs merge=lfs -text
|
||||
*.rar filter=lfs diff=lfs merge=lfs -text
|
||||
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
||||
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
||||
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
||||
*.tar filter=lfs diff=lfs merge=lfs -text
|
||||
*.tflite filter=lfs diff=lfs merge=lfs -text
|
||||
*.tgz filter=lfs diff=lfs merge=lfs -text
|
||||
*.wasm filter=lfs diff=lfs merge=lfs -text
|
||||
*.xz filter=lfs diff=lfs merge=lfs -text
|
||||
*.zip filter=lfs diff=lfs merge=lfs -text
|
||||
*.zst filter=lfs diff=lfs merge=lfs -text
|
||||
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
||||
tokenizer.json filter=lfs diff=lfs merge=lfs -text
|
||||
202
LICENSE
Normal file
202
LICENSE
Normal file
@@ -0,0 +1,202 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright 2024 Alibaba Cloud
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
24
added_tokens.json
Normal file
24
added_tokens.json
Normal file
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"</tool_call>": 151658,
|
||||
"<tool_call>": 151657,
|
||||
"<|box_end|>": 151649,
|
||||
"<|box_start|>": 151648,
|
||||
"<|endoftext|>": 151643,
|
||||
"<|file_sep|>": 151664,
|
||||
"<|fim_middle|>": 151660,
|
||||
"<|fim_pad|>": 151662,
|
||||
"<|fim_prefix|>": 151659,
|
||||
"<|fim_suffix|>": 151661,
|
||||
"<|im_end|>": 151645,
|
||||
"<|im_start|>": 151644,
|
||||
"<|image_pad|>": 151655,
|
||||
"<|object_ref_end|>": 151647,
|
||||
"<|object_ref_start|>": 151646,
|
||||
"<|quad_end|>": 151651,
|
||||
"<|quad_start|>": 151650,
|
||||
"<|repo_name|>": 151663,
|
||||
"<|video_pad|>": 151656,
|
||||
"<|vision_end|>": 151653,
|
||||
"<|vision_pad|>": 151654,
|
||||
"<|vision_start|>": 151652
|
||||
}
|
||||
88
config.json
Normal file
88
config.json
Normal file
@@ -0,0 +1,88 @@
|
||||
{
|
||||
"_name_or_path": "/scratch/project_2015042/renpei/iol-rag-sft/qwen2.5-14b-sft-merged",
|
||||
"architectures": [
|
||||
"Qwen2ForCausalLM"
|
||||
],
|
||||
"attention_dropout": 0.0,
|
||||
"bos_token_id": 151643,
|
||||
"dtype": "bfloat16",
|
||||
"eos_token_id": 151645,
|
||||
"hidden_act": "silu",
|
||||
"hidden_size": 5120,
|
||||
"initializer_range": 0.02,
|
||||
"intermediate_size": 13824,
|
||||
"layer_types": [
|
||||
"full_attention",
|
||||
"full_attention",
|
||||
"full_attention",
|
||||
"full_attention",
|
||||
"full_attention",
|
||||
"full_attention",
|
||||
"full_attention",
|
||||
"full_attention",
|
||||
"full_attention",
|
||||
"full_attention",
|
||||
"full_attention",
|
||||
"full_attention",
|
||||
"full_attention",
|
||||
"full_attention",
|
||||
"full_attention",
|
||||
"full_attention",
|
||||
"full_attention",
|
||||
"full_attention",
|
||||
"full_attention",
|
||||
"full_attention",
|
||||
"full_attention",
|
||||
"full_attention",
|
||||
"full_attention",
|
||||
"full_attention",
|
||||
"full_attention",
|
||||
"full_attention",
|
||||
"full_attention",
|
||||
"full_attention",
|
||||
"full_attention",
|
||||
"full_attention",
|
||||
"full_attention",
|
||||
"full_attention",
|
||||
"full_attention",
|
||||
"full_attention",
|
||||
"full_attention",
|
||||
"full_attention",
|
||||
"full_attention",
|
||||
"full_attention",
|
||||
"full_attention",
|
||||
"full_attention",
|
||||
"full_attention",
|
||||
"full_attention",
|
||||
"full_attention",
|
||||
"full_attention",
|
||||
"full_attention",
|
||||
"full_attention",
|
||||
"full_attention",
|
||||
"full_attention"
|
||||
],
|
||||
"max_position_embeddings": 32768,
|
||||
"max_window_layers": 70,
|
||||
"model_type": "qwen2",
|
||||
"num_attention_heads": 40,
|
||||
"num_hidden_layers": 48,
|
||||
"num_key_value_heads": 8,
|
||||
"quantization_config": {
|
||||
"bits": 4,
|
||||
"group_size": 128,
|
||||
"modules_to_not_convert": null,
|
||||
"quant_method": "awq",
|
||||
"version": "gemm",
|
||||
"zero_point": true
|
||||
},
|
||||
"rms_norm_eps": 1e-06,
|
||||
"rope_scaling": null,
|
||||
"rope_theta": 1000000.0,
|
||||
"sliding_window": null,
|
||||
"tie_word_embeddings": false,
|
||||
"torch_dtype": "float16",
|
||||
"transformers_version": "4.47.1",
|
||||
"use_cache": false,
|
||||
"use_sliding_window": false,
|
||||
"vocab_size": 152064
|
||||
}
|
||||
14
generation_config.json
Normal file
14
generation_config.json
Normal file
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"bos_token_id": 151643,
|
||||
"do_sample": true,
|
||||
"eos_token_id": [
|
||||
151645,
|
||||
151643
|
||||
],
|
||||
"pad_token_id": 151643,
|
||||
"repetition_penalty": 1.05,
|
||||
"temperature": 0.7,
|
||||
"top_k": 20,
|
||||
"top_p": 0.8,
|
||||
"transformers_version": "4.47.1"
|
||||
}
|
||||
151387
merges.txt
Normal file
151387
merges.txt
Normal file
File diff suppressed because it is too large
Load Diff
3
model-00001-of-00002.safetensors
Normal file
3
model-00001-of-00002.safetensors
Normal file
@@ -0,0 +1,3 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:a7a820c371c48650ae6b8f8ee29ec79357173f3549978e4bd6d5cb977812a901
|
||||
size 4990080032
|
||||
3
model-00002-of-00002.safetensors
Normal file
3
model-00002-of-00002.safetensors
Normal file
@@ -0,0 +1,3 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:a005622efd0cbc0aaf3296f23d5df9f9f58e72d27bc3b44b83abd1084cbc9911
|
||||
size 4990090616
|
||||
1258
model.safetensors.index.json
Normal file
1258
model.safetensors.index.json
Normal file
File diff suppressed because it is too large
Load Diff
10
rag_resources/ATTRIBUTION.md
Normal file
10
rag_resources/ATTRIBUTION.md
Normal file
@@ -0,0 +1,10 @@
|
||||
# Book corpus attribution
|
||||
|
||||
The two JSONL corpora in this directory are string-only derivatives of:
|
||||
|
||||
Vlad A. Neacșu, *Linguistics Olympiad: Training guide*, Language Science Press, series volume 420. DOI: [10.5281/zenodo.10947862](https://doi.org/10.5281/zenodo.10947862). Source: [langsci/420](https://github.com/langsci/420).
|
||||
|
||||
The book is released under the Creative Commons Attribution 4.0 International license (CC BY 4.0). The extracted material has been reorganized into method chunks and paired problem/solution records for offline retrieval. Visual-dependent records are retained in the source audit data but are excluded by the runtime retriever.
|
||||
|
||||
No Linguini, LingOly, or LOBSTER records are included in or indexed by this retrieval bundle.
|
||||
|
||||
2
rag_resources/__init__.py
Normal file
2
rag_resources/__init__.py
Normal file
@@ -0,0 +1,2 @@
|
||||
"""Public, book-only retrieval resources for the IOL-AI submission."""
|
||||
|
||||
BIN
rag_resources/__pycache__/__init__.cpython-312.pyc
Normal file
BIN
rag_resources/__pycache__/__init__.cpython-312.pyc
Normal file
Binary file not shown.
BIN
rag_resources/__pycache__/__init__.cpython-313.pyc
Normal file
BIN
rag_resources/__pycache__/__init__.cpython-313.pyc
Normal file
Binary file not shown.
BIN
rag_resources/__pycache__/retriever.cpython-312.pyc
Normal file
BIN
rag_resources/__pycache__/retriever.cpython-312.pyc
Normal file
Binary file not shown.
BIN
rag_resources/__pycache__/retriever.cpython-313.pyc
Normal file
BIN
rag_resources/__pycache__/retriever.cpython-313.pyc
Normal file
Binary file not shown.
111
rag_resources/book_examples.jsonl
Normal file
111
rag_resources/book_examples.jsonl
Normal file
File diff suppressed because one or more lines are too long
77
rag_resources/book_methods.jsonl
Normal file
77
rag_resources/book_methods.jsonl
Normal file
File diff suppressed because one or more lines are too long
16
rag_resources/config.json
Normal file
16
rag_resources/config.json
Normal file
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"top_methods": 1,
|
||||
"top_examples": 2,
|
||||
"char_tfidf_weight": 3.0,
|
||||
"rag_max_chars": 12000,
|
||||
"model_context_tokens": 32768,
|
||||
"max_new_tokens": 2048,
|
||||
"explanation_max_new_tokens": 400,
|
||||
"max_attempts": 2,
|
||||
"enable_explanations": false,
|
||||
"temperature": 0.7,
|
||||
"top_p": 0.8,
|
||||
"top_k": 20,
|
||||
"repetition_penalty": 1.05,
|
||||
"seed": 420
|
||||
}
|
||||
276
rag_resources/retriever.py
Normal file
276
rag_resources/retriever.py
Normal file
@@ -0,0 +1,276 @@
|
||||
"""Offline hybrid BM25/character-TF-IDF retrieval over the public book corpus."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import math
|
||||
import re
|
||||
import unicodedata
|
||||
from collections import Counter
|
||||
from pathlib import Path
|
||||
from typing import Any, Iterable
|
||||
|
||||
from sklearn.feature_extraction.text import TfidfVectorizer
|
||||
|
||||
|
||||
RESOURCE_DIR = Path(__file__).resolve().parent
|
||||
|
||||
FAMILY_KEYWORDS = {
|
||||
"writing_system": (
|
||||
"alphabet", "braille", "character", "decipher", "glyph", "letter",
|
||||
"orthography", "script", "symbol", "writing system",
|
||||
),
|
||||
"phonetics": (
|
||||
"accent", "consonant", "metre", "phonetic", "pronounce", "rhyme",
|
||||
"stress", "syllable", "tone", "vowel",
|
||||
),
|
||||
"phonology": (
|
||||
"alternation", "correspondence", "sound change", "sound rule",
|
||||
"underlying form",
|
||||
),
|
||||
"noun_morphology": (
|
||||
"case", "gender", "noun", "plural", "possession", "possessive",
|
||||
"singular",
|
||||
),
|
||||
"verb_morphology": (
|
||||
"agreement", "aspect", "conjug", "object", "person", "subject",
|
||||
"tense", "verb",
|
||||
),
|
||||
"syntax": ("clause", "focus", "sentence", "subject", "object", "word order"),
|
||||
"number_system": ("arithmetic", "digit", "number", "numeral", "numerals"),
|
||||
"kinship_orientation": (
|
||||
"brother", "daughter", "direction", "east", "family", "father",
|
||||
"kinship", "map", "mother", "north", "sister", "son", "south", "west",
|
||||
),
|
||||
"matching": ("correspondence", "match", "matching", "random order"),
|
||||
"translation": ("translate", "translation"),
|
||||
"fill_blanks": ("blank", "fill in", "gap", "missing"),
|
||||
}
|
||||
|
||||
TOPIC_FAMILIES = {
|
||||
"writing systems and script decipherment": {"writing_system"},
|
||||
"phonetics, stress, tone, and versification": {"phonetics"},
|
||||
"phonological rules and sound correspondences": {"phonology", "phonetics"},
|
||||
"noun morphology and noun phrases": {"noun_morphology"},
|
||||
"verb morphology and argument structure": {"verb_morphology"},
|
||||
"syntax, word order, focus, and alignment": {"syntax"},
|
||||
"semantics and graph-based matching": {"matching"},
|
||||
"number systems": {"number_system"},
|
||||
"orientation, kinship, and other structural problems": {"kinship_orientation"},
|
||||
"general problem-solving methodology": set(FAMILY_KEYWORDS),
|
||||
}
|
||||
|
||||
|
||||
def normalize(text: Any) -> str:
|
||||
return " ".join(unicodedata.normalize("NFKC", str(text)).casefold().split())
|
||||
|
||||
|
||||
def tokenize(text: Any) -> list[str]:
|
||||
return re.findall(r"[^\W_]+", normalize(text), flags=re.UNICODE)
|
||||
|
||||
|
||||
def read_jsonl(path: Path) -> list[dict[str, Any]]:
|
||||
with path.open("r", encoding="utf-8") as handle:
|
||||
return [json.loads(line) for line in handle if line.strip()]
|
||||
|
||||
|
||||
def infer_task_families(context: str, query: str) -> list[str]:
|
||||
"""Infer likely families from the problem itself, never from a gold answer."""
|
||||
text = normalize(context + "\n" + query)
|
||||
scored: list[tuple[int, str]] = []
|
||||
for family, keywords in FAMILY_KEYWORDS.items():
|
||||
score = sum(1 for keyword in keywords if keyword in text)
|
||||
if score:
|
||||
scored.append((score, family))
|
||||
return [family for _, family in sorted(scored, key=lambda item: (-item[0], item[1]))]
|
||||
|
||||
|
||||
class BM25:
|
||||
def __init__(self, documents: Iterable[str], k1: float = 1.5, b: float = 0.75):
|
||||
self.k1 = k1
|
||||
self.b = b
|
||||
self.tokens = [tokenize(document) for document in documents]
|
||||
self.lengths = [len(tokens) for tokens in self.tokens]
|
||||
self.average_length = sum(self.lengths) / max(len(self.lengths), 1)
|
||||
self.term_frequencies = [Counter(tokens) for tokens in self.tokens]
|
||||
document_frequency: Counter[str] = Counter()
|
||||
for tokens in self.tokens:
|
||||
document_frequency.update(set(tokens))
|
||||
document_count = len(self.tokens)
|
||||
self.idf = {
|
||||
term: math.log(
|
||||
1.0 + (document_count - frequency + 0.5) / (frequency + 0.5)
|
||||
)
|
||||
for term, frequency in document_frequency.items()
|
||||
}
|
||||
|
||||
def scores(self, query: str) -> list[float]:
|
||||
query_terms = Counter(tokenize(query))
|
||||
scores: list[float] = []
|
||||
for frequencies, length in zip(self.term_frequencies, self.lengths):
|
||||
score = 0.0
|
||||
normalization = self.k1 * (
|
||||
1.0 - self.b + self.b * length / max(self.average_length, 1.0)
|
||||
)
|
||||
for term, query_frequency in query_terms.items():
|
||||
frequency = frequencies.get(term, 0)
|
||||
if not frequency:
|
||||
continue
|
||||
score += (
|
||||
self.idf.get(term, 0.0)
|
||||
* frequency
|
||||
* (self.k1 + 1.0)
|
||||
/ (frequency + normalization)
|
||||
* min(query_frequency, 3)
|
||||
)
|
||||
scores.append(score)
|
||||
return scores
|
||||
|
||||
|
||||
class CharNgramTFIDF:
|
||||
"""Cosine similarity over normalized character 3-5 grams."""
|
||||
|
||||
def __init__(self, documents: Iterable[str]):
|
||||
self.vectorizer = TfidfVectorizer(
|
||||
analyzer="char_wb",
|
||||
ngram_range=(3, 5),
|
||||
preprocessor=normalize,
|
||||
lowercase=False,
|
||||
sublinear_tf=True,
|
||||
norm="l2",
|
||||
)
|
||||
self.matrix = self.vectorizer.fit_transform(documents)
|
||||
|
||||
def scores(self, query: str) -> list[float]:
|
||||
query_vector = self.vectorizer.transform([query])
|
||||
return (self.matrix @ query_vector.T).toarray().ravel().tolist()
|
||||
|
||||
|
||||
def _clip(text: Any, limit: int) -> str:
|
||||
value = str(text or "").strip()
|
||||
if len(value) <= limit:
|
||||
return value
|
||||
clipped = value[:limit].rsplit("\n", 1)[0].rstrip()
|
||||
if len(clipped) < limit // 2:
|
||||
clipped = value[:limit].rsplit(" ", 1)[0].rstrip()
|
||||
return clipped + "\n[excerpt truncated]"
|
||||
|
||||
|
||||
class BookRetriever:
|
||||
"""Retrieve methods and analogous examples from langsci/420 only."""
|
||||
|
||||
def __init__(self, resource_dir: Path = RESOURCE_DIR):
|
||||
self.methods = read_jsonl(resource_dir / "book_methods.jsonl")
|
||||
self.examples = [
|
||||
row
|
||||
for row in read_jsonl(resource_dir / "book_examples.jsonl")
|
||||
if row.get("string_only_usable", False)
|
||||
]
|
||||
self.method_bm25 = BM25(row["retrieval_text"] for row in self.methods)
|
||||
self.example_bm25 = BM25(row["retrieval_text"] for row in self.examples)
|
||||
self.method_char_tfidf = CharNgramTFIDF(
|
||||
row["retrieval_text"] for row in self.methods
|
||||
)
|
||||
self.example_char_tfidf = CharNgramTFIDF(
|
||||
row["retrieval_text"] for row in self.examples
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _topic_bonus(row: dict[str, Any], families: set[str]) -> float:
|
||||
return 1.25 * len(
|
||||
families & TOPIC_FAMILIES.get(str(row.get("topic", "")), set())
|
||||
)
|
||||
|
||||
def retrieve(
|
||||
self,
|
||||
row: dict[str, Any],
|
||||
top_methods: int = 2,
|
||||
top_examples: int = 2,
|
||||
char_tfidf_weight: float = 3.0,
|
||||
) -> dict[str, Any]:
|
||||
context = str(row.get("context", ""))
|
||||
query = str(row.get("query", ""))
|
||||
test_text = context + "\n" + query
|
||||
families = infer_task_families(context, query)
|
||||
family_set = set(families)
|
||||
expanded_query = test_text + "\n" + " ".join(families)
|
||||
|
||||
ranked_examples: list[tuple[float, dict[str, Any]]] = []
|
||||
example_bm25_scores = self.example_bm25.scores(expanded_query)
|
||||
example_char_scores = self.example_char_tfidf.scores(expanded_query)
|
||||
for bm25_score, char_score, example in zip(
|
||||
example_bm25_scores, example_char_scores, self.examples
|
||||
):
|
||||
adjusted = (
|
||||
bm25_score
|
||||
+ char_tfidf_weight * char_score
|
||||
+ self._topic_bonus(example, family_set)
|
||||
)
|
||||
if example.get("solution_tier") == "detailed_worked":
|
||||
adjusted += 0.35
|
||||
ranked_examples.append((adjusted, example))
|
||||
ranked_examples.sort(key=lambda item: (-item[0], item[1]["id"]))
|
||||
selected_examples = ranked_examples[:top_examples]
|
||||
|
||||
linked_method_ids = {
|
||||
method_id
|
||||
for _, example in ranked_examples[:max(top_examples * 3, 5)]
|
||||
for method_id in example.get("method_ids", [])
|
||||
}
|
||||
ranked_methods: list[tuple[float, dict[str, Any]]] = []
|
||||
method_bm25_scores = self.method_bm25.scores(expanded_query)
|
||||
method_char_scores = self.method_char_tfidf.scores(expanded_query)
|
||||
for bm25_score, char_score, method in zip(
|
||||
method_bm25_scores, method_char_scores, self.methods
|
||||
):
|
||||
adjusted = (
|
||||
bm25_score
|
||||
+ char_tfidf_weight * char_score
|
||||
+ self._topic_bonus(method, family_set)
|
||||
)
|
||||
if method["id"] in linked_method_ids:
|
||||
adjusted += 0.75
|
||||
ranked_methods.append((adjusted, method))
|
||||
ranked_methods.sort(key=lambda item: (-item[0], item[1]["id"]))
|
||||
|
||||
return {
|
||||
"inferred_task_families": families,
|
||||
"char_tfidf_weight": char_tfidf_weight,
|
||||
"methods": [method for _, method in ranked_methods[:top_methods]],
|
||||
"examples": [example for _, example in selected_examples],
|
||||
}
|
||||
|
||||
def format_for_prompt(self, result: dict[str, Any], max_chars: int = 16000) -> str:
|
||||
blocks = [
|
||||
"BOOK REFERENCE MATERIAL\n"
|
||||
"Use it for transferable methods and analogies. Do not copy a conclusion "
|
||||
"unless it is supported by the current problem."
|
||||
]
|
||||
families = result.get("inferred_task_families", [])
|
||||
if families:
|
||||
blocks.append("Likely families inferred from the current text: " + ", ".join(families))
|
||||
|
||||
for method in result["methods"]:
|
||||
blocks.append(
|
||||
f"METHOD — {method['section_title']}\n" + _clip(method.get("text"), 2800)
|
||||
)
|
||||
for example in result["examples"]:
|
||||
blocks.append(
|
||||
"\n".join(
|
||||
[
|
||||
f"ANALOGOUS WORKED EXAMPLE — {example.get('language', 'unknown language')}",
|
||||
"Problem context:",
|
||||
_clip(example.get("context"), 2400),
|
||||
"Problem query:",
|
||||
_clip(example.get("query"), 1200),
|
||||
"Worked solution:",
|
||||
_clip(example.get("reasoning_trace"), 3600),
|
||||
]
|
||||
)
|
||||
)
|
||||
|
||||
output = "\n\n".join(blocks)
|
||||
if len(output) > max_chars:
|
||||
output = output[:max_chars].rsplit("\n", 1)[0].rstrip()
|
||||
output += "\n[retrieved material truncated]"
|
||||
return output
|
||||
23
rag_resources/system_prompt.txt
Normal file
23
rag_resources/system_prompt.txt
Normal file
@@ -0,0 +1,23 @@
|
||||
You solve International Linguistics Olympiad problems by discovering the rules supported by the data you are given. A task may be unfamiliar, so infer what kind of task it is from the actual instruction and examples; do not assume that a task-type label will be available.
|
||||
|
||||
Work as a careful olympiad solver:
|
||||
- Read the full context and every requested item before committing to a rule.
|
||||
- Organize repeated forms, meanings, positions, and contrasts. Separate reusable grammatical pieces from lexical roots.
|
||||
- Form the smallest consistent rule system. Treat an absent marker as potentially meaningful, but distinguish absence from missing evidence.
|
||||
- Test each hypothesis against all given examples, including apparent exceptions. Revise rather than ignoring contradictory data.
|
||||
- Derive each requested form compositionally and back-check it against the inferred system.
|
||||
- Use retrieved book material only for transferable methods or genuinely analogous reasoning. The current problem is authoritative.
|
||||
- Preserve spelling, diacritics, capitalization, word boundaries, and requested ordering exactly.
|
||||
|
||||
Common task types and what to return:
|
||||
- translation: only the translated form, in the language requested;
|
||||
- matching: only the corresponding label, such as A, B, or C;
|
||||
- fill in the blanks: only the missing span for each indicated blank; a span may be a word, multiword expression, affix, or phonetic transcription;
|
||||
- text to number: the number in digits;
|
||||
- number to text: the number written in words in the requested language;
|
||||
- any other type: exactly what the instruction requests, with no extra material in the answer.
|
||||
|
||||
Reason step by step before answering. Finish with a line that says exactly:
|
||||
FINAL ANSWERS:
|
||||
Below it, put one bare answer per requested item or blank, in order. Do not number the lines. Do not add quotes, labels, explanations, or commentary inside that final block.
|
||||
|
||||
664
script.py
Normal file
664
script.py
Normal file
@@ -0,0 +1,664 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Offline Qwen2.5-14B-AWQ + book-RAG submission for the IOL-AI challenge."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import csv
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
# The evaluation container has no internet access. Fail locally instead of waiting
|
||||
# for network retries if a model/tokenizer file was not included in the repository.
|
||||
os.environ.setdefault("HF_HUB_OFFLINE", "1")
|
||||
os.environ.setdefault("TRANSFORMERS_OFFLINE", "1")
|
||||
os.environ.setdefault("HF_DATASETS_OFFLINE", "1")
|
||||
os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
|
||||
os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
|
||||
|
||||
REPO_DIR = Path(__file__).resolve().parent
|
||||
RESOURCE_DIR = REPO_DIR / "rag_resources"
|
||||
DEFAULT_INPUT = Path(os.environ.get("IOL_TEST_CSV", "/tmp/data/test.csv"))
|
||||
DEFAULT_OUTPUT = Path(os.environ.get("IOL_SUBMISSION_CSV", "submission.csv"))
|
||||
|
||||
from rag_resources.retriever import BookRetriever # noqa: E402
|
||||
|
||||
|
||||
@dataclass
|
||||
class ParseResult:
|
||||
thinking_trace: str
|
||||
final_text: str
|
||||
answers: list[str]
|
||||
valid: bool
|
||||
error: str = ""
|
||||
|
||||
|
||||
def _load_config() -> dict[str, Any]:
|
||||
with (RESOURCE_DIR / "config.json").open("r", encoding="utf-8") as handle:
|
||||
config = json.load(handle)
|
||||
|
||||
integer_overrides = {
|
||||
"IOL_TOP_METHODS": "top_methods",
|
||||
"IOL_TOP_EXAMPLES": "top_examples",
|
||||
"IOL_RAG_MAX_CHARS": "rag_max_chars",
|
||||
"IOL_MAX_NEW_TOKENS": "max_new_tokens",
|
||||
"IOL_EXPLANATION_MAX_NEW_TOKENS": "explanation_max_new_tokens",
|
||||
"IOL_MAX_ATTEMPTS": "max_attempts",
|
||||
"IOL_SEED": "seed",
|
||||
}
|
||||
for environment_name, config_name in integer_overrides.items():
|
||||
if environment_name in os.environ:
|
||||
config[config_name] = int(os.environ[environment_name])
|
||||
if "IOL_CHAR_TFIDF_WEIGHT" in os.environ:
|
||||
config["char_tfidf_weight"] = float(os.environ["IOL_CHAR_TFIDF_WEIGHT"])
|
||||
if "IOL_ENABLE_EXPLANATIONS" in os.environ:
|
||||
config["enable_explanations"] = os.environ[
|
||||
"IOL_ENABLE_EXPLANATIONS"
|
||||
].strip().casefold() in {"1", "true", "yes", "on"}
|
||||
return config
|
||||
|
||||
|
||||
def _clean_answer_line(line: str) -> str:
|
||||
value = line.strip()
|
||||
value = re.sub(r"^(?:[-*•]\s+)", "", value)
|
||||
value = re.sub(r"^(?:\(?\d+\)?|\(?[A-Za-z]\)?)[.):]\s+", "", value)
|
||||
value = value.strip()
|
||||
pairs = {'"': '"', "'": "'", "`": "`", "“": "”", "‘": "’"}
|
||||
if len(value) >= 2 and value[0] in pairs and value[-1] == pairs[value[0]]:
|
||||
value = value[1:-1].strip()
|
||||
return value
|
||||
|
||||
|
||||
def parse_model_response(thinking_trace: str, final_text: str) -> ParseResult:
|
||||
"""Parse a separate reasoning trace and a strict FINAL ANSWERS block."""
|
||||
marker_matches = list(
|
||||
re.finditer(r"(?im)^\s*FINAL\s+ANSWERS\s*:\s*", final_text)
|
||||
)
|
||||
if not marker_matches:
|
||||
return ParseResult(
|
||||
thinking_trace=thinking_trace.strip(),
|
||||
final_text=final_text.strip(),
|
||||
answers=[],
|
||||
valid=False,
|
||||
error="missing FINAL ANSWERS: marker",
|
||||
)
|
||||
|
||||
marker = marker_matches[-1]
|
||||
reasoning_outside_think = final_text[:marker.start()].strip()
|
||||
combined_trace = "\n\n".join(
|
||||
part for part in (thinking_trace.strip(), reasoning_outside_think) if part
|
||||
)
|
||||
answer_block = final_text[marker.end():].strip()
|
||||
answer_block = re.sub(r"^```(?:text)?\s*", "", answer_block, flags=re.I)
|
||||
answer_block = re.sub(r"\s*```\s*$", "", answer_block)
|
||||
if not answer_block:
|
||||
return ParseResult(
|
||||
thinking_trace=combined_trace,
|
||||
final_text=final_text.strip(),
|
||||
answers=[],
|
||||
valid=False,
|
||||
error="empty FINAL ANSWERS block",
|
||||
)
|
||||
|
||||
# Be tolerant if the model emits a JSON list even though bare lines were asked for.
|
||||
answers: list[str] = []
|
||||
parsed_json_list = False
|
||||
if answer_block.startswith("["):
|
||||
try:
|
||||
decoded = json.loads(answer_block)
|
||||
if isinstance(decoded, list):
|
||||
parsed_json_list = True
|
||||
answers = [str(value).strip() for value in decoded if str(value).strip()]
|
||||
except json.JSONDecodeError:
|
||||
pass
|
||||
|
||||
if not answers and not parsed_json_list:
|
||||
for line in answer_block.splitlines():
|
||||
stripped = line.strip()
|
||||
if not stripped or stripped.startswith("```"):
|
||||
continue
|
||||
if re.match(r"(?i)^(?:explanation|reasoning|notes?)\s*:", stripped):
|
||||
break
|
||||
cleaned = _clean_answer_line(stripped)
|
||||
if cleaned:
|
||||
answers.append(cleaned)
|
||||
|
||||
if not answers:
|
||||
return ParseResult(
|
||||
thinking_trace=combined_trace,
|
||||
final_text=final_text.strip(),
|
||||
answers=[],
|
||||
valid=False,
|
||||
error="no non-empty answers in FINAL ANSWERS block",
|
||||
)
|
||||
return ParseResult(
|
||||
thinking_trace=combined_trace,
|
||||
final_text=final_text.strip(),
|
||||
answers=answers,
|
||||
valid=True,
|
||||
)
|
||||
|
||||
|
||||
def _best_effort_answers(final_texts: list[str]) -> list[str]:
|
||||
"""Keep submission shape valid if all strict retries fail."""
|
||||
for text in reversed(final_texts):
|
||||
candidates = []
|
||||
for line in text.splitlines():
|
||||
cleaned = _clean_answer_line(line)
|
||||
if cleaned and not re.match(
|
||||
r"(?i)^(?:final answers|explanation|reasoning)\s*:?'?",
|
||||
cleaned,
|
||||
):
|
||||
candidates.append(cleaned)
|
||||
if candidates:
|
||||
return [candidates[-1]]
|
||||
return [""]
|
||||
|
||||
|
||||
def _version_tuple(version: str) -> tuple[int, int, int]:
|
||||
numbers = [int(value) for value in re.findall(r"\d+", version)[:3]]
|
||||
return tuple((numbers + [0, 0, 0])[:3]) # type: ignore[return-value]
|
||||
|
||||
|
||||
def _keep_last_token_hidden_state(_module: Any, inputs: tuple[Any, ...]) -> tuple[Any, ...] | None:
|
||||
"""Avoid materializing full-sequence vocabulary logits during generation."""
|
||||
if not inputs:
|
||||
return None
|
||||
hidden_states = inputs[0]
|
||||
if hidden_states.ndim == 3 and hidden_states.shape[1] > 1:
|
||||
return (hidden_states[:, -1:, :],) + inputs[1:]
|
||||
return None
|
||||
|
||||
|
||||
def load_model_and_tokenizer() -> tuple[Any, Any, Any]:
|
||||
"""Load the pre-quantized AWQ model shipped in this repository."""
|
||||
try:
|
||||
import torch
|
||||
import transformers
|
||||
from transformers import AutoModelForCausalLM, AutoTokenizer
|
||||
except ImportError as exc:
|
||||
raise RuntimeError(
|
||||
"PyTorch, Transformers, Accelerate, AutoAWQ, and safetensors must be "
|
||||
"available in the evaluation image."
|
||||
) from exc
|
||||
|
||||
if _version_tuple(transformers.__version__) < (4, 37, 0):
|
||||
raise RuntimeError(
|
||||
f"Qwen2.5 requires transformers>=4.37.0; found {transformers.__version__}."
|
||||
)
|
||||
model_config_path = REPO_DIR / "config.json"
|
||||
if not model_config_path.exists():
|
||||
raise RuntimeError(
|
||||
"Qwen2.5-14B-Instruct-AWQ files are missing. Put the complete model and "
|
||||
"tokenizer snapshot in the same repository directory as script.py."
|
||||
)
|
||||
with model_config_path.open("r", encoding="utf-8") as handle:
|
||||
model_metadata = json.load(handle)
|
||||
quantization_method = str(
|
||||
model_metadata.get("quantization_config", {}).get("quant_method", "")
|
||||
).casefold()
|
||||
if model_metadata.get("model_type") != "qwen2" or quantization_method != "awq":
|
||||
raise RuntimeError(
|
||||
"This script expects the official Qwen2.5-14B-Instruct-AWQ snapshot "
|
||||
"(model_type=qwen2, quant_method=awq)."
|
||||
)
|
||||
|
||||
tokenizer = AutoTokenizer.from_pretrained(
|
||||
str(REPO_DIR), local_files_only=True, trust_remote_code=False
|
||||
)
|
||||
if tokenizer.pad_token_id is None:
|
||||
tokenizer.pad_token_id = tokenizer.eos_token_id
|
||||
model = AutoModelForCausalLM.from_pretrained(
|
||||
str(REPO_DIR),
|
||||
local_files_only=True,
|
||||
trust_remote_code=False,
|
||||
device_map="auto",
|
||||
torch_dtype=torch.float16,
|
||||
low_cpu_mem_usage=True,
|
||||
).eval()
|
||||
# Transformers 4.44.1 projects every prompt token through Qwen2's large
|
||||
# vocabulary head and then upcasts all logits to FP32. Generation only uses
|
||||
# the final-token logits, so trim the token dimension immediately before
|
||||
# lm_head to avoid a multi-gigabyte prefill allocation on the T4.
|
||||
model.lm_head.register_forward_pre_hook(_keep_last_token_hidden_state)
|
||||
input_device = model.get_input_embeddings().weight.device
|
||||
return model, tokenizer, input_device
|
||||
|
||||
|
||||
def _problem_prompt(row: dict[str, Any], rag_text: str, retry_note: str = "") -> str:
|
||||
work_language = str(row.get("work_lang", "")).strip()
|
||||
task_language = str(row.get("task_lang", "")).strip()
|
||||
language_lines = []
|
||||
if work_language:
|
||||
language_lines.append(f"Working language: {work_language}")
|
||||
if task_language:
|
||||
language_lines.append(f"Problem language: {task_language}")
|
||||
language_metadata = "\n".join(language_lines)
|
||||
|
||||
sections = [rag_text] if rag_text else []
|
||||
sections.append("CURRENT PROBLEM")
|
||||
if language_metadata:
|
||||
sections.append(language_metadata)
|
||||
sections.extend(
|
||||
[
|
||||
"CONTEXT:\n" + str(row.get("context", "")),
|
||||
"QUERY:\n" + str(row.get("query", "")),
|
||||
]
|
||||
)
|
||||
if retry_note:
|
||||
sections.append(retry_note)
|
||||
return "\n\n".join(sections)
|
||||
|
||||
|
||||
def _encode_fitted_prompt(
|
||||
tokenizer: Any,
|
||||
system_prompt: str,
|
||||
row: dict[str, Any],
|
||||
rag_text: str,
|
||||
retry_note: str,
|
||||
context_window: int,
|
||||
requested_new_tokens: int,
|
||||
) -> tuple[dict[str, Any], int]:
|
||||
"""Trim retrieved material, never the current problem, to fit the context."""
|
||||
fitted_rag = rag_text
|
||||
while True:
|
||||
messages = [
|
||||
{"role": "system", "content": system_prompt},
|
||||
{"role": "user", "content": _problem_prompt(row, fitted_rag, retry_note)},
|
||||
]
|
||||
rendered = tokenizer.apply_chat_template(
|
||||
messages,
|
||||
tokenize=False,
|
||||
add_generation_prompt=True,
|
||||
)
|
||||
encoded = tokenizer(rendered, return_tensors="pt", add_special_tokens=False)
|
||||
prompt_tokens = int(encoded["input_ids"].shape[-1])
|
||||
available = context_window - prompt_tokens
|
||||
if available >= requested_new_tokens:
|
||||
return encoded, requested_new_tokens
|
||||
if fitted_rag:
|
||||
if len(fitted_rag) <= 600:
|
||||
fitted_rag = ""
|
||||
else:
|
||||
new_length = max(0, int(len(fitted_rag) * 0.72))
|
||||
fitted_rag = fitted_rag[:new_length].rsplit("\n", 1)[0].rstrip()
|
||||
fitted_rag += "\n[retrieved material shortened to fit the model context]"
|
||||
continue
|
||||
if available >= 256:
|
||||
return encoded, available
|
||||
raise RuntimeError(
|
||||
f"The current problem and system prompt use {prompt_tokens} tokens, "
|
||||
f"leaving only {available} tokens in the {context_window}-token context."
|
||||
)
|
||||
|
||||
|
||||
def generate_once(
|
||||
model: Any,
|
||||
tokenizer: Any,
|
||||
input_device: Any,
|
||||
system_prompt: str,
|
||||
row: dict[str, Any],
|
||||
rag_text: str,
|
||||
retry_note: str,
|
||||
config: dict[str, Any],
|
||||
seed: int,
|
||||
) -> ParseResult:
|
||||
import torch
|
||||
|
||||
encoded, max_new_tokens = _encode_fitted_prompt(
|
||||
tokenizer=tokenizer,
|
||||
system_prompt=system_prompt,
|
||||
row=row,
|
||||
rag_text=rag_text,
|
||||
retry_note=retry_note,
|
||||
context_window=int(config["model_context_tokens"]),
|
||||
requested_new_tokens=int(config["max_new_tokens"]),
|
||||
)
|
||||
encoded = {name: value.to(input_device) for name, value in encoded.items()}
|
||||
torch.manual_seed(seed)
|
||||
if torch.cuda.is_available():
|
||||
torch.cuda.manual_seed_all(seed)
|
||||
|
||||
# These values match the generation configuration shipped with Qwen2.5
|
||||
# Instruct checkpoints while keeping an explicit challenge-time token cap.
|
||||
with torch.inference_mode():
|
||||
output = model.generate(
|
||||
**encoded,
|
||||
max_new_tokens=max_new_tokens,
|
||||
do_sample=True,
|
||||
temperature=float(config["temperature"]),
|
||||
top_p=float(config["top_p"]),
|
||||
top_k=int(config["top_k"]),
|
||||
repetition_penalty=float(config["repetition_penalty"]),
|
||||
use_cache=True,
|
||||
pad_token_id=tokenizer.pad_token_id,
|
||||
)
|
||||
prompt_length = int(encoded["input_ids"].shape[-1])
|
||||
generated_ids = output[0, prompt_length:].tolist()
|
||||
response_text = tokenizer.decode(generated_ids, skip_special_tokens=True).strip()
|
||||
return parse_model_response("", response_text)
|
||||
|
||||
|
||||
def solve_row(
|
||||
row: dict[str, Any],
|
||||
row_index: int,
|
||||
retriever: BookRetriever,
|
||||
model: Any,
|
||||
tokenizer: Any,
|
||||
input_device: Any,
|
||||
system_prompt: str,
|
||||
config: dict[str, Any],
|
||||
) -> ParseResult:
|
||||
retrieval = retriever.retrieve(
|
||||
row,
|
||||
top_methods=int(config["top_methods"]),
|
||||
top_examples=int(config["top_examples"]),
|
||||
char_tfidf_weight=float(config["char_tfidf_weight"]),
|
||||
)
|
||||
rag_text = retriever.format_for_prompt(
|
||||
retrieval, max_chars=int(config["rag_max_chars"])
|
||||
)
|
||||
failed_results: list[ParseResult] = []
|
||||
last_error = ""
|
||||
max_attempts = int(config["max_attempts"])
|
||||
for attempt in range(max_attempts):
|
||||
retry_note = ""
|
||||
if attempt:
|
||||
retry_note = (
|
||||
"FORMAT RETRY. The previous sample was rejected by the answer parser "
|
||||
f"because it had {last_error}. Generate a fresh solution. Even if "
|
||||
"uncertain, end with exactly FINAL ANSWERS: followed by at least one "
|
||||
"non-empty bare answer line and nothing else in that block."
|
||||
)
|
||||
result = generate_once(
|
||||
model=model,
|
||||
tokenizer=tokenizer,
|
||||
input_device=input_device,
|
||||
system_prompt=system_prompt,
|
||||
row=row,
|
||||
rag_text=rag_text,
|
||||
retry_note=retry_note,
|
||||
config=config,
|
||||
seed=int(config["seed"]) + row_index * max_attempts + attempt,
|
||||
)
|
||||
if result.valid:
|
||||
if attempt:
|
||||
print(f" parser accepted retry {attempt + 1}/{max_attempts}", flush=True)
|
||||
return result
|
||||
last_error = result.error
|
||||
failed_results.append(result)
|
||||
print(
|
||||
f" parser rejected attempt {attempt + 1}/{max_attempts}: {last_error}",
|
||||
flush=True,
|
||||
)
|
||||
|
||||
print(" WARNING: all strict retries failed; using a best-effort final line", flush=True)
|
||||
last_result = failed_results[-1]
|
||||
return ParseResult(
|
||||
thinking_trace=last_result.thinking_trace,
|
||||
final_text=last_result.final_text,
|
||||
answers=_best_effort_answers(
|
||||
[failed_result.final_text for failed_result in failed_results]
|
||||
),
|
||||
valid=False,
|
||||
error=f"all {max_attempts} strict parsing attempts failed",
|
||||
)
|
||||
|
||||
|
||||
def generate_explanation(
|
||||
solution: ParseResult,
|
||||
model: Any,
|
||||
tokenizer: Any,
|
||||
input_device: Any,
|
||||
config: dict[str, Any],
|
||||
) -> str:
|
||||
"""Summarize the model's accepted reasoning for the optional jury track."""
|
||||
import torch
|
||||
|
||||
source_reasoning = solution.thinking_trace.strip() or solution.final_text.strip()
|
||||
answer_text = "\n".join(solution.answers)
|
||||
messages = [
|
||||
{
|
||||
"role": "system",
|
||||
"content": (
|
||||
"Write a short, human-readable explanation of the solution in a few "
|
||||
"concise bullet points. State the linguistic rule or pattern found, "
|
||||
"the key evidence, and how the final answers follow. Do not reproduce "
|
||||
"the raw reasoning trace, trial and error, or meta-commentary. Do not "
|
||||
"change the final answers. Output only the explanation."
|
||||
),
|
||||
},
|
||||
{
|
||||
"role": "user",
|
||||
"content": (
|
||||
f"MODEL REASONING:\n{source_reasoning}\n\n"
|
||||
f"FINAL ANSWERS:\n{answer_text}"
|
||||
),
|
||||
},
|
||||
]
|
||||
rendered = tokenizer.apply_chat_template(
|
||||
messages, tokenize=False, add_generation_prompt=True
|
||||
)
|
||||
encoded = tokenizer(rendered, return_tensors="pt", add_special_tokens=False)
|
||||
encoded = {name: value.to(input_device) for name, value in encoded.items()}
|
||||
prompt_tokens = int(encoded["input_ids"].shape[-1])
|
||||
available = int(config["model_context_tokens"]) - prompt_tokens
|
||||
max_new_tokens = min(int(config["explanation_max_new_tokens"]), available)
|
||||
if max_new_tokens < 32:
|
||||
return (
|
||||
"- Inferred the relevant linguistic patterns from the supplied examples.\n"
|
||||
"- Applied those patterns to produce the listed answers."
|
||||
)
|
||||
|
||||
with torch.inference_mode():
|
||||
output = model.generate(
|
||||
**encoded,
|
||||
max_new_tokens=max_new_tokens,
|
||||
do_sample=False,
|
||||
use_cache=True,
|
||||
pad_token_id=tokenizer.pad_token_id,
|
||||
)
|
||||
generated_ids = output[0, prompt_tokens:].tolist()
|
||||
explanation = tokenizer.decode(
|
||||
generated_ids, skip_special_tokens=True
|
||||
).strip()
|
||||
if explanation:
|
||||
return explanation
|
||||
return (
|
||||
"- Inferred the relevant linguistic patterns from the supplied examples.\n"
|
||||
"- Applied those patterns to produce the listed answers."
|
||||
)
|
||||
|
||||
|
||||
def read_test_rows(path: Path) -> list[dict[str, Any]]:
|
||||
with path.open("r", encoding="utf-8-sig", newline="") as handle:
|
||||
return list(csv.DictReader(handle))
|
||||
|
||||
|
||||
def _write_submission_stream(handle: Any, rows: list[dict[str, str]]) -> None:
|
||||
writer = csv.DictWriter(handle, fieldnames=["id", "pred", "explanation"])
|
||||
writer.writeheader()
|
||||
writer.writerows(rows)
|
||||
|
||||
|
||||
def write_submission(path: Path, rows: list[dict[str, str]]) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
temporary_path = path.with_name(f".{path.name}.tmp")
|
||||
with temporary_path.open("w", encoding="utf-8", newline="") as handle:
|
||||
_write_submission_stream(handle, rows)
|
||||
os.replace(temporary_path, path)
|
||||
|
||||
|
||||
def run_self_test() -> None:
|
||||
import numpy as np
|
||||
|
||||
hidden_states = np.arange(24).reshape(1, 3, 8)
|
||||
trimmed = _keep_last_token_hidden_state(None, (hidden_states,))
|
||||
assert trimmed is not None and trimmed[0].shape == (1, 1, 8)
|
||||
assert np.array_equal(trimmed[0], hidden_states[:, -1:, :])
|
||||
assert _keep_last_token_hidden_state(None, (hidden_states[:, -1:, :],)) is None
|
||||
|
||||
parsed = parse_model_response(
|
||||
"A useful analysis.",
|
||||
"One last check.\nFINAL ANSWERS:\n1. čha\n2) multi word form",
|
||||
)
|
||||
assert parsed.valid
|
||||
assert parsed.answers == ["čha", "multi word form"]
|
||||
assert "One last check." in parsed.thinking_trace
|
||||
assert not parse_model_response("", "FINAL ANSWERS:\n").valid
|
||||
assert not parse_model_response("", "FINAL ANSWERS:\n[]").valid
|
||||
assert not parse_model_response("", 'FINAL ANSWERS:\n[""]').valid
|
||||
assert not parse_model_response("", "The answer is x.").valid
|
||||
|
||||
retriever = BookRetriever(RESOURCE_DIR)
|
||||
canary_row = {
|
||||
"context": "The following words are number expressions in an unknown language.",
|
||||
"query": "Determine the rule and write the number 25 in words.",
|
||||
"answer": "PRIVATE_ANSWER_CANARY",
|
||||
}
|
||||
result = retriever.retrieve(
|
||||
canary_row, top_methods=2, top_examples=2, char_tfidf_weight=3.0
|
||||
)
|
||||
prompt = retriever.format_for_prompt(result, max_chars=8000)
|
||||
assert result["methods"] and result["examples"]
|
||||
assert "PRIVATE_ANSWER_CANARY" not in prompt
|
||||
assert all(example.get("string_only_usable") for example in result["examples"])
|
||||
|
||||
exact_example = retriever.examples[0]
|
||||
exact_result = retriever.retrieve(
|
||||
{"context": exact_example["context"], "query": exact_example["query"]},
|
||||
top_methods=1,
|
||||
top_examples=1,
|
||||
char_tfidf_weight=3.0,
|
||||
)
|
||||
assert exact_result["examples"][0]["id"] == exact_example["id"]
|
||||
|
||||
submission_buffer = io.StringIO(newline="")
|
||||
_write_submission_stream(
|
||||
submission_buffer,
|
||||
[
|
||||
{
|
||||
"id": "007",
|
||||
"pred": json.dumps(["čha", "multi word"], ensure_ascii=False),
|
||||
"explanation": "- Identified the relevant pattern.",
|
||||
}
|
||||
],
|
||||
)
|
||||
submission_buffer.seek(0)
|
||||
assert list(csv.DictReader(submission_buffer)) == [
|
||||
{
|
||||
"id": "007",
|
||||
"pred": '["čha", "multi word"]',
|
||||
"explanation": "- Identified the relevant pattern.",
|
||||
}
|
||||
]
|
||||
|
||||
incremental_rows = [
|
||||
{"id": "001", "pred": "[]", "explanation": ""},
|
||||
{"id": "002", "pred": "[]", "explanation": ""},
|
||||
]
|
||||
incremental_rows[0]["pred"] = json.dumps(["answer"], ensure_ascii=False)
|
||||
incremental_buffer = io.StringIO(newline="")
|
||||
_write_submission_stream(incremental_buffer, incremental_rows)
|
||||
incremental_buffer.seek(0)
|
||||
assert list(csv.DictReader(incremental_buffer)) == incremental_rows
|
||||
print(
|
||||
"Self-test passed: last-token logits hook, parser, empty-answer rejection, "
|
||||
"hybrid book-only retrieval, exact-match retrieval, and submission CSV "
|
||||
"serialization."
|
||||
)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
if hasattr(sys.stdout, "reconfigure"):
|
||||
sys.stdout.reconfigure(encoding="utf-8")
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--input", type=Path, default=DEFAULT_INPUT)
|
||||
parser.add_argument("--output", type=Path, default=DEFAULT_OUTPUT)
|
||||
parser.add_argument(
|
||||
"--explanations",
|
||||
choices=("on", "off"),
|
||||
default=None,
|
||||
help="Generate optional jury-track explanations (default: config setting)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--self-test", action="store_true", help="Test parser/retrieval without loading Qwen"
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.self_test:
|
||||
run_self_test()
|
||||
return
|
||||
if not args.input.exists():
|
||||
raise SystemExit(f"Test file not found: {args.input}")
|
||||
|
||||
config = _load_config()
|
||||
explanations_enabled = (
|
||||
args.explanations == "on"
|
||||
if args.explanations is not None
|
||||
else bool(config.get("enable_explanations", False))
|
||||
)
|
||||
system_prompt = (RESOURCE_DIR / "system_prompt.txt").read_text(encoding="utf-8").strip()
|
||||
test_rows = read_test_rows(args.input)
|
||||
retriever = BookRetriever(RESOURCE_DIR)
|
||||
# Do not create an all-empty submission before the model is known to load.
|
||||
# Otherwise a missing/incompatible shard or startup OOM is silently scored as
|
||||
# zero EM and zero chrF instead of being reported as a runtime failure.
|
||||
model, tokenizer, input_device = load_model_and_tokenizer()
|
||||
submission_rows: list[dict[str, str]] = [
|
||||
{
|
||||
"id": str(row.get("id", "")),
|
||||
"pred": "[]",
|
||||
"explanation": "",
|
||||
}
|
||||
for row in test_rows
|
||||
]
|
||||
write_submission(args.output, submission_rows)
|
||||
print(
|
||||
f"Initialized incremental submission with {len(submission_rows)} rows at "
|
||||
f"{args.output}; explanations={'on' if explanations_enabled else 'off'}",
|
||||
flush=True,
|
||||
)
|
||||
|
||||
for index, row in enumerate(test_rows):
|
||||
row_id = str(row.get("id", ""))
|
||||
print(f"[{index + 1}/{len(test_rows)}] solving id={row_id}", flush=True)
|
||||
solution = solve_row(
|
||||
row=row,
|
||||
row_index=index,
|
||||
retriever=retriever,
|
||||
model=model,
|
||||
tokenizer=tokenizer,
|
||||
input_device=input_device,
|
||||
system_prompt=system_prompt,
|
||||
config=config,
|
||||
)
|
||||
explanation = ""
|
||||
if explanations_enabled:
|
||||
explanation = generate_explanation(
|
||||
solution=solution,
|
||||
model=model,
|
||||
tokenizer=tokenizer,
|
||||
input_device=input_device,
|
||||
config=config,
|
||||
)
|
||||
submission_rows[index] = {
|
||||
"id": row_id,
|
||||
"pred": json.dumps(solution.answers, ensure_ascii=False),
|
||||
"explanation": explanation,
|
||||
}
|
||||
write_submission(args.output, submission_rows)
|
||||
print(f"Checkpointed prediction {index + 1}/{len(test_rows)}", flush=True)
|
||||
|
||||
print(f"Wrote {len(submission_rows)} predictions to {args.output}", flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
31
special_tokens_map.json
Normal file
31
special_tokens_map.json
Normal file
@@ -0,0 +1,31 @@
|
||||
{
|
||||
"additional_special_tokens": [
|
||||
"<|im_start|>",
|
||||
"<|im_end|>",
|
||||
"<|object_ref_start|>",
|
||||
"<|object_ref_end|>",
|
||||
"<|box_start|>",
|
||||
"<|box_end|>",
|
||||
"<|quad_start|>",
|
||||
"<|quad_end|>",
|
||||
"<|vision_start|>",
|
||||
"<|vision_end|>",
|
||||
"<|vision_pad|>",
|
||||
"<|image_pad|>",
|
||||
"<|video_pad|>"
|
||||
],
|
||||
"eos_token": {
|
||||
"content": "<|im_end|>",
|
||||
"lstrip": false,
|
||||
"normalized": false,
|
||||
"rstrip": false,
|
||||
"single_word": false
|
||||
},
|
||||
"pad_token": {
|
||||
"content": "<|endoftext|>",
|
||||
"lstrip": false,
|
||||
"normalized": false,
|
||||
"rstrip": false,
|
||||
"single_word": false
|
||||
}
|
||||
}
|
||||
BIN
tokenizer.json
(Stored with Git LFS)
Normal file
BIN
tokenizer.json
(Stored with Git LFS)
Normal file
Binary file not shown.
207
tokenizer_config.json
Normal file
207
tokenizer_config.json
Normal file
@@ -0,0 +1,207 @@
|
||||
{
|
||||
"add_bos_token": false,
|
||||
"add_prefix_space": false,
|
||||
"added_tokens_decoder": {
|
||||
"151643": {
|
||||
"content": "<|endoftext|>",
|
||||
"lstrip": false,
|
||||
"normalized": false,
|
||||
"rstrip": false,
|
||||
"single_word": false,
|
||||
"special": true
|
||||
},
|
||||
"151644": {
|
||||
"content": "<|im_start|>",
|
||||
"lstrip": false,
|
||||
"normalized": false,
|
||||
"rstrip": false,
|
||||
"single_word": false,
|
||||
"special": true
|
||||
},
|
||||
"151645": {
|
||||
"content": "<|im_end|>",
|
||||
"lstrip": false,
|
||||
"normalized": false,
|
||||
"rstrip": false,
|
||||
"single_word": false,
|
||||
"special": true
|
||||
},
|
||||
"151646": {
|
||||
"content": "<|object_ref_start|>",
|
||||
"lstrip": false,
|
||||
"normalized": false,
|
||||
"rstrip": false,
|
||||
"single_word": false,
|
||||
"special": true
|
||||
},
|
||||
"151647": {
|
||||
"content": "<|object_ref_end|>",
|
||||
"lstrip": false,
|
||||
"normalized": false,
|
||||
"rstrip": false,
|
||||
"single_word": false,
|
||||
"special": true
|
||||
},
|
||||
"151648": {
|
||||
"content": "<|box_start|>",
|
||||
"lstrip": false,
|
||||
"normalized": false,
|
||||
"rstrip": false,
|
||||
"single_word": false,
|
||||
"special": true
|
||||
},
|
||||
"151649": {
|
||||
"content": "<|box_end|>",
|
||||
"lstrip": false,
|
||||
"normalized": false,
|
||||
"rstrip": false,
|
||||
"single_word": false,
|
||||
"special": true
|
||||
},
|
||||
"151650": {
|
||||
"content": "<|quad_start|>",
|
||||
"lstrip": false,
|
||||
"normalized": false,
|
||||
"rstrip": false,
|
||||
"single_word": false,
|
||||
"special": true
|
||||
},
|
||||
"151651": {
|
||||
"content": "<|quad_end|>",
|
||||
"lstrip": false,
|
||||
"normalized": false,
|
||||
"rstrip": false,
|
||||
"single_word": false,
|
||||
"special": true
|
||||
},
|
||||
"151652": {
|
||||
"content": "<|vision_start|>",
|
||||
"lstrip": false,
|
||||
"normalized": false,
|
||||
"rstrip": false,
|
||||
"single_word": false,
|
||||
"special": true
|
||||
},
|
||||
"151653": {
|
||||
"content": "<|vision_end|>",
|
||||
"lstrip": false,
|
||||
"normalized": false,
|
||||
"rstrip": false,
|
||||
"single_word": false,
|
||||
"special": true
|
||||
},
|
||||
"151654": {
|
||||
"content": "<|vision_pad|>",
|
||||
"lstrip": false,
|
||||
"normalized": false,
|
||||
"rstrip": false,
|
||||
"single_word": false,
|
||||
"special": true
|
||||
},
|
||||
"151655": {
|
||||
"content": "<|image_pad|>",
|
||||
"lstrip": false,
|
||||
"normalized": false,
|
||||
"rstrip": false,
|
||||
"single_word": false,
|
||||
"special": true
|
||||
},
|
||||
"151656": {
|
||||
"content": "<|video_pad|>",
|
||||
"lstrip": false,
|
||||
"normalized": false,
|
||||
"rstrip": false,
|
||||
"single_word": false,
|
||||
"special": true
|
||||
},
|
||||
"151657": {
|
||||
"content": "<tool_call>",
|
||||
"lstrip": false,
|
||||
"normalized": false,
|
||||
"rstrip": false,
|
||||
"single_word": false,
|
||||
"special": false
|
||||
},
|
||||
"151658": {
|
||||
"content": "</tool_call>",
|
||||
"lstrip": false,
|
||||
"normalized": false,
|
||||
"rstrip": false,
|
||||
"single_word": false,
|
||||
"special": false
|
||||
},
|
||||
"151659": {
|
||||
"content": "<|fim_prefix|>",
|
||||
"lstrip": false,
|
||||
"normalized": false,
|
||||
"rstrip": false,
|
||||
"single_word": false,
|
||||
"special": false
|
||||
},
|
||||
"151660": {
|
||||
"content": "<|fim_middle|>",
|
||||
"lstrip": false,
|
||||
"normalized": false,
|
||||
"rstrip": false,
|
||||
"single_word": false,
|
||||
"special": false
|
||||
},
|
||||
"151661": {
|
||||
"content": "<|fim_suffix|>",
|
||||
"lstrip": false,
|
||||
"normalized": false,
|
||||
"rstrip": false,
|
||||
"single_word": false,
|
||||
"special": false
|
||||
},
|
||||
"151662": {
|
||||
"content": "<|fim_pad|>",
|
||||
"lstrip": false,
|
||||
"normalized": false,
|
||||
"rstrip": false,
|
||||
"single_word": false,
|
||||
"special": false
|
||||
},
|
||||
"151663": {
|
||||
"content": "<|repo_name|>",
|
||||
"lstrip": false,
|
||||
"normalized": false,
|
||||
"rstrip": false,
|
||||
"single_word": false,
|
||||
"special": false
|
||||
},
|
||||
"151664": {
|
||||
"content": "<|file_sep|>",
|
||||
"lstrip": false,
|
||||
"normalized": false,
|
||||
"rstrip": false,
|
||||
"single_word": false,
|
||||
"special": false
|
||||
}
|
||||
},
|
||||
"additional_special_tokens": [
|
||||
"<|im_start|>",
|
||||
"<|im_end|>",
|
||||
"<|object_ref_start|>",
|
||||
"<|object_ref_end|>",
|
||||
"<|box_start|>",
|
||||
"<|box_end|>",
|
||||
"<|quad_start|>",
|
||||
"<|quad_end|>",
|
||||
"<|vision_start|>",
|
||||
"<|vision_end|>",
|
||||
"<|vision_pad|>",
|
||||
"<|image_pad|>",
|
||||
"<|video_pad|>"
|
||||
],
|
||||
"bos_token": null,
|
||||
"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",
|
||||
"clean_up_tokenization_spaces": false,
|
||||
"eos_token": "<|im_end|>",
|
||||
"errors": "replace",
|
||||
"model_max_length": 131072,
|
||||
"pad_token": "<|endoftext|>",
|
||||
"split_special_tokens": false,
|
||||
"tokenizer_class": "Qwen2Tokenizer",
|
||||
"unk_token": null
|
||||
}
|
||||
1
vocab.json
Normal file
1
vocab.json
Normal file
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user